注意点:蓝牙在同一时间只能和一台设备进行配对,不可能同时和多个设备进行配对的
实现思路:先将周围所有的蓝牙设备都扫描出来,放到一个队列里面。扫描结束之后(在广播里面可以监听扫描结束),从队列里面选出一个蓝牙设备进行配对。在配对成功或者配对失败(在广播里面可以监听)的时候,再从队列里面选出一个进行配对,之后其实就形成了一个循环,也就是每次监听到上一次配对状态成功或者失败时,就开始了下一次配对,直到队列里面没有元素为止。注意,在监听到正在配对状态时,不要开始下一次配对。
部分核心代码:
private LinkedBlockingQueue<BluetoothDevice> discoveryQueue;//扫描出来的所有蓝牙设备都放入该队列里面 broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action)){ //发现了蓝牙设备 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); discoveryQueue.offer(device);//将扫描到的设备放入队列 }else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ //扫描结束 if(isDiscoveryFirst){ dialog.dismiss(); cancelDiscovery(); pairDialog = DialogUtils.showLoadingDialog(BluetoothListActivity.this, "开始自动配对"); //从队列里面取出一个进行配对 getFromQueueToPair(); isDiscoveryFirst = false; } }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){ //绑定状态发生变化的时候 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1); switch (state) { case BluetoothDevice.BOND_NONE: Log.d(TAG, "和" + device.getName() + ".." + device.getAddress() + "配对失败"); //从队列里面取出一个进行配对 getFromQueueToPair(); break; case BluetoothDevice.BOND_BONDED: Log.d(TAG, "和" + device.getName() + ".." + device.getAddress() + "配对成功"); //从队列里面取出一个进行配对 getFromQueueToPair(); OnReceiveMsgListenerImpl2 onReceiveMsgListenerImpl2 = new OnReceiveMsgListenerImpl2(); BluetoothManager bluetoothManager = new BluetoothManager(new Handler(), onReceiveMsgListenerImpl2); bluetoothManager.setDevice(device); onReceiveMsgListenerImpl2.setBluetoothManager(bluetoothManager); bluetoothManager.start(); bluetoothManagers.add(bluetoothManager); break; } } } }; /** * 从队列里面取出一个进行配对 */ private void getFromQueueToPair() { MyThreadPool.getInstance().execute(new Runnable() { @Override public void run() { BluetoothDevice device1 = discoveryQueue.poll(); if(device1 != null){ BluetoothUtils.createBond(device1); }else{ pairDialog.dismiss(); } } }); }