本文主要是介绍蓝牙的配对,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
官方蓝牙Api
蓝牙之开启和关闭
蓝牙之扫描可连接设备
通过反射BluetoothDevice中的“createBond”和“removeBond”两个函数实现配对和移除配对
- 创建配对
/*** 创建配对** @param device*/@RequiresApi(api = Build.VERSION_CODES.KITKAT)public void CreateBond(BluetoothDevice device){if (device==null)return;if (!BluetoothManager.newInstance().isBlueEnable()){return;}if (BluetoothManager.newInstance().getBluetoothAdapter().isDiscovering()){BluetoothManager.newInstance().getBluetoothAdapter().cancelDiscovery();}/**如果该蓝牙没有配对*/if (device.getBondState()==BluetoothDevice.BOND_NONE){try {//反射Method createBondMethod = device.getClass().getMethod("createBond");//配对密码
// String pinPwd = "1234";
// device.setPin(pinPwd.getBytes());Boolean returnValue = (Boolean) createBondMethod.invoke(device);returnValue.booleanValue();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
- 取消配对
/*** 取消配对** @param device*/public void cancelBond(BluetoothDevice device){if (device==null)return;if (!BluetoothManager.newInstance().isBlueEnable()){return;}/**如果该蓝牙没有配对*/if (device.getBondState()==BluetoothDevice.BOND_NONE){try {//反射Method createBondMethod = device.getClass().getMethod("removeBond");Boolean returnValue = (Boolean) createBondMethod.invoke(device);returnValue.booleanValue();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
- 通过广播接收配对状态
注册广播
public void init(){IntentFilter filter4 = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);IntentFilter filter5 = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);getContext(). registerReceiver(pinBlueReceiver,filter4);getContext(). registerReceiver(pinBlueReceiver,filter5);}
广播接收器
public class PinBlueReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();Log.d(TAG, "action:" + action);BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){try {//1.确认配对Method setPairingConfirmation = device.getClass().getDeclaredMethod("setPairingConfirmation",boolean.class);setPairingConfirmation.invoke(device,true);//2.终止有序广播Log.d("order...", "isOrderedBroadcast:"+isOrderedBroadcast()+",isInitialStickyBroadcast:"+isInitialStickyBroadcast());//如果没有将广播终止,则会出现一个一闪而过的配对框。abortBroadcast();//3.调用setPin方法进行配对...Method removeBondMethod = device.getClass().getDeclaredMethod("setPin", new Class[]{byte[].class});Boolean returnValue = (Boolean) removeBondMethod.invoke(device, new Object[]{pin.getBytes()});} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {switch (device.getBondState()) {case BluetoothDevice.BOND_NONE:Log.d(TAG, "取消配对");break;case BluetoothDevice.BOND_BONDING:Log.d(TAG, "配对中");break;case BluetoothDevice.BOND_BONDED:Log.d(TAG, "配对成功");break;}}}}
这篇关于蓝牙的配对的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!