上一篇文章已经写了如何打开蓝牙设备,显示已经配对成功的蓝牙设备,http://blog.csdn.net/liuzuyi200/article/details/37740401
这篇文章主要写如何搜索蓝牙设备
(2)搜索蓝牙设备需要执行startDiscovery()这个方法,这个过程会大约持续12秒。
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
mBluetoothAdapter.startDiscovery();
要执行这个方法必须注册一个BroadcastReceiver,属性BluetoothDevice.ACTION_FOUND的intent
private final BroadcastReceiver Receiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
textview1.append(device.getName() + ":"
+ device.getAddress() + "\n\n");
}
}
}
};
注册BroadcastReceiver用下面这句话完成,分别在调用开始和结束时使用