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