蓝牙扫描功能

Posted gali

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了蓝牙扫描功能相关的知识,希望对你有一定的参考价值。

1.加入需要的权限

<uses-feature
        android:name="android.hardware.bluetooth_le"
        android:required="true" />

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

2.扫描界面实现

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/bai"
    android:orientation="vertical"
    tools:context="myapplication.com.myblue.Search_Activity"
    android:weightSum="1">

    <LinearLayout
        android:layout_height="45dp"
        android:layout_width="match_parent"
        android:background="@color/theme"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/imageView1"
            android:layout_height="@dimen/zhuyemian"
            android:layout_width="@dimen/zhuyemian"
            android:layout_gravity="center_vertical"
            android:src="@mipmap/search_back"/>
        <TextView
            android:id="@+id/textView1"
            android:layout_height="@dimen/titlebar"
            android:layout_width="0dp"
            android:text="@string/zhuyemian"
            android:gravity="center_horizontal|center_vertical"
            android:textSize="@dimen/title_size"
            android:layout_weight="1"/>
        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:id="@+id/textView_shoushuo"
             android:layout_gravity="center_vertical"
            android:textSize="@dimen/activity_vertical_margin"
            android:src="@mipmap/search"/>
    </LinearLayout>
    <ListView

        android:layout_gravity="center"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp"
        android:layout_height="260dp"
        android:layout_width="match_parent"
        android:id="@+id/listView"
        android:layout_weight="0.73" />
</LinearLayout>

4.功能实现

package myapplication.com.myblue;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

import myapplication.com.myblue.activity.Zhuye_Activity;
import myapplication.com.myblue.adapter.MyAdapter;

public class Search_Activity extends AppCompatActivity {
    BluetoothAdapter mBluetoothAdapter;
    ArrayList<String> datas = new ArrayList<String>();
    ListView listview;
  //  ArrayAdapter<String> ad;
    MyAdapter ad;
    ImageView imageView1;
    ImageView textView_shoushuo;
    TextView textView1;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        Intent intent=new Intent(this,Zhuye_Activity.class);
        startActivity(intent);

        initView();
        mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver,filter);
        IntentFilter filter2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver,filter2);
        textView_shoushuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!mBluetoothAdapter.isEnabled())
                {
                    mBluetoothAdapter.enable();
                }
                mBluetoothAdapter.startDiscovery();
                textView1.setText("搜索中...");
            }
        });

       // ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, datas);
        ad=new MyAdapter(datas,getApplicationContext());
        listview.setAdapter(ad);
    }
     public void initView(){
         imageView1= (ImageView) findViewById(R.id.imageView1);
         imageView1.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 finish();
             }
         });
         listview= (ListView) findViewById(R.id.listView);
         textView_shoushuo= (ImageView) findViewById(R.id.textView_shoushuo);
         textView1= (TextView) findViewById(R.id.textView1);
         listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String s= (String) parent.getItemAtPosition(position);
                 Intent intent=new Intent(Search_Activity.this,Zhuye_Activity.class);
                 intent.putExtra("mac",s);
                 /**
                  * 离开本页面时广播就解除注册,并关闭蓝牙
                  * **/
                 mBluetoothAdapter.disable();
                 unregisterReceiver(mReceiver);

                 startActivity(intent);

             }
         });

    }
    /**
     *
     * 解除注册
     * **/
    public void onDestroy() {

        super.onDestroy();
        //解除注册
        unregisterReceiver(mReceiver);
        Log.e("destory","解除注册");
    }
    /**
     * 打开蓝牙设备
     * **/
    public void enable() {
        //蓝牙设备
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //启用
        mBluetoothAdapter.enable();
    }

    /***
     * 定义广播接收
     * **/
    private BroadcastReceiver mReceiver=new BroadcastReceiver(){



        @Override
        public void onReceive(Context context, Intent intent) {

            String action=intent.getAction();

            Log.e("ywq", action);
            if(action.equals(BluetoothDevice.ACTION_FOUND))
            {
                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(device.getBondState()==BluetoothDevice.BOND_BONDED)
                {    //显示已配对设备
                  //  这里的datas.indexof()用来判断是否重复添加
            String s=device.getName()+"*"+device.getAddress();
          if(datas.indexOf(s)==-1){
               datas.add(device.getName()+"*"+device.getAddress());
            }
}else if(device.getBondState()!=BluetoothDevice.BOND_BONDED) { 
            String s=device.getName()+"*"+device.getAddress();
               if(datas.indexOf(s)==-1){
                 datas.add(device.getName()+"*"+device.getAddress());
                  }
} }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){ // text2.setText("搜索完成..."); textView1.setText("搜索完成..."); } } }; }

4.ListView适配器

package myapplication.com.myblue.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

import myapplication.com.myblue.R;

/**
 * Created by Administrator on 2016/11/24.
 */
public class MyAdapter extends BaseAdapter {
    ArrayList<String> datas;
    Context context;

    public MyAdapter(ArrayList<String> datas, Context context) {
        this.datas = datas;
        this.context = context;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            convertView= LayoutInflater.from(context).inflate(R.layout.searchitem_layout, null);
            holder=new ViewHolder();
            holder.textViewl=(TextView) convertView.findViewById(R.id.textView_item);
            convertView.setTag(holder);
        }else{
            holder=(ViewHolder) convertView.getTag();
        }
        String s=datas.get(position);
        holder.textViewl.setText("MAC:"+s);

        return convertView;
    }
    class  ViewHolder{
        TextView textViewl;
    }
}

ListView—item布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@color/bai"
    android:layout_height="40dp">
<TextView
    android:id="@+id/textView_item"
    android:layout_height="40dp"
    android:textColor="@color/hei"
    android:textSize="@dimen/textsize"
    android:layout_width="match_parent"
    />
</LinearLayout>

 

以上是关于蓝牙扫描功能的主要内容,如果未能解决你的问题,请参考以下文章

Qt低功耗蓝牙系列三(低功耗蓝牙客户端的程序设计纯Android代码)

Qt低功耗蓝牙系列三(低功耗蓝牙客户端的程序设计纯Android代码)

iOS蓝牙开发梳理:广播端和扫描端实现

iOS蓝牙开发梳理:广播端和扫描端实现

断网了,如何让微信小程序,可以用蓝牙

Android 蓝牙扫描代码