首页 > 代码库 > android蓝牙学习

android蓝牙学习

学习路线

1 蓝牙权限

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> //安卓6.0版本需要位置权限

 

2 打开蓝牙

public void onOpen(View v) {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //获取蓝牙适配器

        if (!bluetoothAdapter.isEnabled()) {                     //如果蓝牙是关闭的,则打开
            bluetoothAdapter.enable();
            showMessage("Open bluetooth");
        } else {
            showMessage("Bluetooth is already open");
        }
    }

 

 

3 扫描周围蓝牙(获取配对蓝牙)

   扫描周围的蓝牙需要定义一个广播接收器

private BroadcastReceiver mReceiver=new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            Log.i("boye", action);
            if(action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);    //获取当前扫描到的设备

                if(device.getBondState()==BluetoothDevice.BOND_BONDED) {                  //显示已配对设备
                    textView.append("\n"+device.getName()+"==>"+device.getAddress()+"\n");
                    Toast.makeText(context, "发现已配对设备:" + device.getName(), Toast.LENGTH_LONG).show();
                } else if(device.getBondState()!=BluetoothDevice.BOND_BONDED) {
                    textView3.append("\n"+device.getName()+"==>"+device.getAddress()+"\n");
                    Toast.makeText(context, "发现未配对设备:" + device.getName(), Toast.LENGTH_LONG).show();
                }
            } else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
                    textView2.setText("搜索完成...");
            }
        }
    };

广播过滤器

IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);                  //过滤出发现
registerReceiver(mReceiver,filter);                                                  //注册广播
IntentFilter filter2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);   //过滤出扫描结束
registerReceiver(mReceiver,filter2);                                                 //注册广播

 

4  蓝牙配对

public void createBond(BluetoothDevice btDev, Handler handler) {
        if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
            //如果这个设备取消了配对,则尝试配对
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //安卓版本大于等于4.3
                btDev.createBond();
            }
        } else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) {
            //如果这个设备已经配对完成,则尝试连接
            connect(btDev, handler);
        }
    }

 

 

 

5  蓝牙的连接

private void connect(BluetoothDevice btDev, Handler handler) {
        try {
            //通过和服务器协商的uuid来进行连接
            mBluetoothSocket = btDev.createRfcommSocketToServiceRecord(BltContant.SPP_UUID);
            if (mBluetoothSocket != null)
                //全局只有一个bluetooth,所以我们可以将这个socket对象保存在appliaction中
                BltAppliaction.bluetoothSocket = mBluetoothSocket;

            Log.i("blueTooth", "开始连接...");
            //在建立之前调用
            if (getmBluetoothAdapter().isDiscovering())
                //停止搜索
                getmBluetoothAdapter().cancelDiscovery();
            //如果当前socket处于非连接状态则调用连接
            if (!getmBluetoothSocket().isConnected()) {
                //你应当确保在调用connect()时设备没有执行搜索设备的操作。
                // 如果搜索设备也在同时进行,那么将会显著地降低连接速率,并很大程度上会连接失败。
                getmBluetoothSocket().connect();
            }
            Log.i("blueTooth", "已经连接");
            if (handler == null) return;
            //结果回调
            Message message = new Message();
            message.what = 4;
            message.obj = btDev;
            handler.sendMessage(message);
        } catch (Exception e) {
            Log.i("blueTooth", "...连接失败");
            try {
                getmBluetoothSocket().close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

 

 

 

6  蓝牙通信

(1)发送消息

public static void sendMessage(String message) {
        if (BltAppliaction.bluetoothSocket == null || TextUtils.isEmpty(message)) return;
        try {
            //message += "\n";
            OutputStream outputStream = BltAppliaction.bluetoothSocket.getOutputStream();
            outputStream.write(message.getBytes("utf-8"));
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

(2)接收消息

public static void receiveMessage(Handler handler) {
        if (BltAppliaction.bluetoothSocket == null || handler == null) return;
        try {
            InputStream inputStream = BltAppliaction.bluetoothSocket.getInputStream();
            byte[] buffer = new byte[200];
            inputStream.read(buffer);
            Log.i("boye收到的信息",new String(buffer));

            Message message = new Message();
            message.obj = new String(buffer);
            message.what = 1;
            handler.sendMessage(message);
          
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

android蓝牙学习