Android 查找附近的蓝牙设备
示例
BluetoothAdapter首先声明。
BluetoothAdapter mBluetoothAdapter;
现在创建一个BroadcastReceiver用于ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); //找到设备 if (BluetoothDevice.ACTION_FOUND.equals(action)) { //从Intent获取BluetoothDevice对象 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //将名称和地址添加到阵列适配器以显示在列表中 mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } };
注册BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter);
然后通过致电开始发现附近的蓝牙设备startDiscovery
mBluetoothAdapter.startDiscovery();
不要忘记注销BroadcastReceiver内部onDestroy
unregisterReceiver(mReceiver);