蓝牙的搜索是通过广播来实现的。关键代码如下:
1、用于发现蓝牙的广播接受者
/**
* 接收器
* 当搜索蓝牙设备完成时调用
*/
private BroadcastReceiver _foundReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//将结果添加到列表中
_devices.add(device);
DeviceInfo info=new DeviceInfo();
info.setmDeviceName(device.getName());
info.setmDeviceMacAddr(device.getAddress());
infos.add(info);
info=null;
// 显示列表
showDevices();
}
};
private BroadcastReceiver _discoveryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
// 卸载注册的接收器
unregisterReceiver(_foundReceiver);
unregisterReceiver(this);
_discoveryFinished = true;
}
};
2、获得蓝牙