蓝牙配对绑定原理不再赘述了,终端的实现可以参照文章后的参考链接,本处主要记录总结下Android端的配对绑定实现过程。
1、动态注册系统广播,接收蓝牙配对请求
intentFilter = new IntentFilter();
intentFilter.addAction("android.bluetooth.device.action.PAIRING_REQUEST");//配对请求
blePairRequestReceiver = new BlePairRequestReceiver();
registerReceiver(blePairRequestReceiver,intentFilter);
2、定义蓝牙配对请求广播接收器,因为配对时的操作比较耗时,所以单独开启了线程,防止ANR
class BlePairRequestReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")){
// 从Intent中获取设备对象
LogUtil.d(TAG,"BlePairRequestReceiver PAIRING_REQUEST");
MineDeviceActivity.btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//开启线程,蓝牙配对绑定
new Thread(){
@Override
public void run() {
if(Build.VERSION.SDK_INT >18){ //版本兼容
btDevice.createBond();//绑定
}else{
BleBondUtil.createBond(btDevice); //绑定
}
}
}.start();
}
}
}
3、BleBondUtil工具类,18以下版本需要反射方式实现
//绑定
public static boolean createBond(BluetoothDevice bleDevice) {
boolean result = false;
try {
final Method createBond = bleDevice.getClass().getMethod("createBond");
final Boolean invoke = (Boolean) createBond.invoke(bleDevice);
result = invoke.booleanValue();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return result;
}
//与设备解除配对
public static boolean removeBond(BluetoothDevice bleDevice) {
boolean result = false;
try{
final Method removeBond = bleDevice.getClass().getMethod("removeBond");
final Boolean returnValue = (Boolean) removeBond.invoke(bleDevice);
result = returnValue.booleanValue();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
【参考】
1、终端配对绑定的实现
1)静态密码设置:http://blog.chinaunix.net/uid-28852942-id-5513867.html
2)动态密码:http://blog.chinaunix.net/uid-28852942-id-5592664.html
3)连接时触发配对:http://blog.chinaunix.net/uid-28852942-id-5700019.html
4)配对绑定实现过程:http://blog.chinaunix.net/uid-28852942-id-5753120.html
2、Android端配对绑定的实现:
https://blog.csdn.net/u010603798/article/details/70789216
https://www.cnblogs.com/jason-star/archive/2012/09/10/2678368.html
https://blog.csdn.net/xiang_041259/article/details/79945362
https://blog.csdn.net/qiandaxiong/article/details/78720436(自动配对)
https://blog.csdn.net/qq_30710673/article/details/79816168(工具类)