蓝牙协议可以实现一个蓝牙设备和6到8个蓝牙设备进行通信。
1、蓝牙搜索的实现
利用蓝牙的发现和完成动作动态注册广播接受者获得蓝牙设备。
第一步,获得蓝牙适配器
BluetoothAdapter mBtAdapter= BluetoothAdapter.getDefaultAdapter();
<span style="white-space:pre"> </span>// 判断蓝牙是否打开
<span style="white-space:pre"> </span>if (!mAdapter.isEnabled()) {
<span style="white-space:pre"> </span>mAdapter.enable();
第二步动态注册蓝牙搜索广播接收者
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
并且可以利用意图过滤器设置广播的优先级
filter.setPriority(Integer.MAX_VALUE);
对应的广播接收者:
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
或者利用发现和完成动作定义两个广播接受者,在完成的动作中注销广播接收者。
关键代码如下:
/**
* 接收器 当搜索蓝牙设备完成时调用
*/
private BroadcastReceiver _foundReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
BluetoothDevice device = intent
.getPar