蓝牙设备的查找与绑定
查找蓝牙设备
查找蓝牙设备分为两个部分,第一个是已经绑定的设备,第二个是搜素新的蓝牙设备。对于已经绑定的蓝牙设备来说,通过BluetoothAdapter的getBondedDevices()方法获得,此方法返回的是一个集合Set,可以直接获取需要的信息。
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for (BluetoothDevice device : devices) {
System.out.println(device.getName() + " : " + device.getAddress());
}
查找新的设备,要调用startDiscovery()方法,这个方法并不会在我们的程序中执行,它是系统进程来的,然后通过异步发送广播的方式来通知。所以我们还要注册一个广播接收器来接收系统的广播,这个广播的action为BluetoothDevice.ACTION_FOUND。它携带两个值,一个是BluetoothDevice.EXTRA_DEVICE另一个是BluetoothDevice.EXTRA_CLASS分别表示哪一个具体的设备和这个设备的类型。
private class BluetoothDeviceScanListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 这里可以把我们的将我们的设备添加到一个列表中
System.out.println(device.getName() + " : " + device.getAddress());
}
}
#设置蓝牙可搜索
/**
* 打开蓝牙可见性
* @param context
*/
public void enableVisibly(Context context) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(discoverableIntent);
}
在官方的文档中一直强调,查找设备这个动作是会消耗大量的系统资源的,而且它会大大减少蓝牙的可用带宽,所以当我们找到了目标设备后,应该由我们主动调用cancelDiscovery()这个方法来取消搜索,而不应该期待默认的搜索时间到了,由系统来取消搜索。