Android扫描蓝牙设备是个异步的过程,核心的步骤为:调用bluetoothAdapter的startDiscovery()进行设备扫描,扫描的结果通过广播接收处理!具体如下:
1.申请相关权限
12
2.注册广播
1 private void registerBroadcast() {2 // Register for broadcasts when a device is discovered3 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);4 mContext.registerReceiver(mReceiver, filter);5 6 // Register for broadcasts when discovery has finished7 filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);8 mContext.registerReceiver(mReceiver, filter);9 }
3.扫描设备
1 private void doDiscovery() {2 // If we're already discovering, stop it3 if (mBluetoothAdapter.isDiscovering()) {4 mBluetoothAdapter.cancelDiscovery();5 }6 // Request discover from BluetoothAdapter7 mBluetoothAdapter.startDiscovery();8 }
4.广播中处理扫描到的设备
1 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 2 @Override 3 public void onReceive(Context context, Intent intent) { 4 String action = intent.getAction(); 5 6 if (BluetoothDevice.ACTION_FOUND.equals(action)) { 7 // TODO discovery finds a device 8 9 } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED10 .equals(action)) {11 // TODO discovery is finished12 }13 }14 };