实现功能:蓝牙配对
在上篇的基础上,配对第一个找到的蓝牙设备
1、重写Handler中找到蓝牙设备后的逻辑
/** 判断是否是第一个发现的蓝牙设备*/
private boolean hasFindOneDevice = false;
case ACTION_FOND:
Intent intentFond = (Intent) msg.obj;
if (!hasFindOneDevice) {// //连接该蓝牙设备
BluetoothDevice findFirstdevice = intentFond
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(TAG,"第一个发现的蓝牙:" + findFirstdevice.getName());
if (findFirstdevice.getBondState() == BluetoothDevice.BOND_NONE) {
// 利用反射方法调用 BluetoothDevice.createBond(BluetoothDevice remoteDevice);
Method createBondMethod;
try {
createBondMethod = BluetoothDevice.class
.getMethod("createBond");
createBondMethod.invoke(findFirstdevice);
} catch (Exception e) {
e.printStackTrace();
}
hasFindOneDevice = true;
} else {
BluetoothDevice finddevice = intentFond
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(TAG, "find device:" + finddevice.getName());
}
}
获取配对信息:首先,在BroadCast中注册该Action
btDiscoveryFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);// 指明一个远程设备的连接状态的改变
在自定义的receiver中添加设备状态改变的情况
else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED
.equals(action)) {// 远程设备的连接状态改变
Log.e(TAG, "接收到 action=BluetoothDevice.ACTION_BOND_STATE_CHANGED");
msg.what = BOND_STATE_CHANGE;
handler.sendMessage(msg);
}
设置状态改变时要执行的逻辑代码
case BOND_STATE_CHANGE:
Intent intent2 = (Intent) msg.obj;
final BluetoothDevice stateChangeDevice = intent2
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e(TAG, "蓝牙设备的状态" + stateChangeDevice.getBondState());
switch (stateChangeDevice.getBondState()) {
case BluetoothDevice.BOND_BONDING:
Log.e(TAG, "正在配对......");
break;
case BluetoothDevice.BOND_BONDED:
Log.e(TAG, "完成配对");
break;
case BluetoothDevice.BOND_NONE:
Log.e(TAG, "取消配对");
break;
default:
break;
}
本文主要介绍了在Android平台上实现蓝牙设备配对的功能。基于上篇文章,详细讲述了如何找到并连接到第一个搜索到的蓝牙设备,包括在BroadcastReceiver中监听蓝牙设备状态变化,以及在设备状态改变时执行的相应逻辑。
5569

被折叠的 条评论
为什么被折叠?



