目录

一、配对方法 

二、解除配对方法

三、配对/解除配对结果

四、justwork配对模式下,不弹出配对框

五、pincode配对模式下,不弹出配对框

六、小结


在之前的文章【Android】蓝牙开发—— 经典蓝牙配对介绍(Java代码实现演示)附Demo源码 中,简单介绍和演示了经典蓝牙的配对方式,今天就在之前的基础上继续讲讲,蓝牙的配对、解除配对以及如何实现不弹出配对框。

关于“配对”、“解除配对”的说法,还有叫“绑定”、“解绑”,这里提前说一下,在之前的文章中出现,防止小伙伴们不理解。

一、配对方法 

蓝牙配对方式,目前有两种,一种是通过反射的方法,还有一种是直接调用官方API的方法。

第一种:反射的方法,在低于Android API 19时,配对的方法是隐藏的方法,所以只有通过反射方法实现。

 /**     * 第一种     * 执行配对 反射     * @param bluetoothDevice 蓝牙设备     * @return true 执行绑定 false 未执行绑定     */    public boolean boundDevice(BluetoothDevice bluetoothDevice){        if(bluetoothDevice == null){            Log.e(TAG,"boundDevice-->bluetoothDevice == null");            return false;        }        try {            return ClsUtils.createBond(BluetoothDevice.class,bluetoothDevice);        } catch (Exception e) {            e.printStackTrace();        }        return true;    }

 ClsUtils.java中createBond()方法如下:

/**     * 与设备配对 参考源码:platform/packages/apps/Settings.git     * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java     */    @SuppressWarnings("unchecked")    static public boolean createBond(@SuppressWarnings("rawtypes") Class btClass, BluetoothDevice btDevice)            throws Exception {        Method createBondMethod = btClass.getMethod("createBond");        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);        return returnValue.booleanValue();    }

 第二种:官方API,但是只支持Android API 19以上的设备。

/**     * 第二种     * 执行配对 官方API     * @param bluetoothDevice  蓝牙设备     * @return  true 执行绑定 false 未执行绑定     */    public boolean boundDeviceAPI(BluetoothDevice bluetoothDevice){        if(bluetoothDevice == null){            return false;        }        //注意:Android 4.4版本之后的API        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {            return bluetoothDevice.createBond();        }        return false;    }

 

二、解除配对方法

蓝牙解除配对的方式,因为是隐藏的方法,目前只有通过反射进行调用。

/**     * 执行解除配对  反射     * @param bluetoothDevice 蓝牙设备     * @return  true 执行解绑  false未执行解绑     */    public boolean disBoundDevice(BluetoothDevice bluetoothDevice){        if(bluetoothDevice == null){            Log.e(TAG,"disBoundDevice-->bluetoothDevice == null");            return false;        }        try {            return ClsUtils.removeBond(BluetoothDevice.class,bluetoothDevice);        } catch (Exception e) {            e.printStackTrace();        }        return true;    }

 ClsUtils.java中removeBond()方法如下:

/**     * 与设备解除配对 参考源码:platform/packages/apps/Settings.git     * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java     */    @SuppressWarnings("unchecked")    static public boolean removeBond(Class btClass, BluetoothDevice btDevice)            throws Exception {        Method removeBondMethod = btClass.getMethod("removeBond");        Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);        return returnValue.booleanValue();    }

三、配对/解除配对结果

配对、解除配对的结果是通过系统广播出来的,所以我们在使用的时候,需要注册广播接收器来获取配对状态。

这里我们自定义广播接收器。在onCreate()中注册该广播,在onDestroy()中注销广播。

 /**     * 蓝牙广播接收器     */    private class BtBroadcastReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            if(TextUtils.equals(action,BluetoothDevice.ACTION_BOND_STATE_CHANGED)){                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);                int bondSate = bluetoothDevice.getBondState();                switch(bondSate) {                    case BluetoothDevice.BOND_NONE:                        Log.d(TAG, "已解除配对");                        break;                    case BluetoothDevice.BOND_BONDING:                        Log.d(TAG, "正在配对...");                        break;                    case BluetoothDevice.BOND_BONDED:                        Log.d(TAG, "已配对");                        break;                }            }        }    }
 //注册广播接收 btBroadcastReceiver = new BtBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); //配对状态监听 registerReceiver(btBroadcastReceiver,intentFilter);
//注销广播接收unregisterReceiver(btBroadcastReceiver);

四、justwork配对模式下,不弹出配对框

1、配对的时候

justwork配对模式下,不管是调用反射的配对方法还是官方API的配对方法,都不会弹出配对框,实现自动配对。

2、经典蓝牙第一次连接的时候(即连接之前,与设备是没有配对的状态)

经典蓝牙建立连接时,有两种方式,一种是建立安全的连接,即需要配对的连接;

还有一种就是建立不安全的连接,即不需要配对的连接。建立不安全的连接,实际上是因为没有进行配对,当然就不会有配对框弹出。

//1、建立安全的蓝牙连接,会弹出配对框BluetoothSocket BluetoothSocket=bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
//2、建立不安全的蓝牙连接,不进行配对,就不弹出配对框BluetoothSocket BluetoothSocket=bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(uuid));

五、pincode配对模式下,不弹出配对框

1、注册BluetoothDevice.ACTION_PAIRING_REQUEST广播监听

 //注册广播接收 btBroadcastReceiver = new BtBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); //配对状态监听 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {            intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);  //配对请求        } registerReceiver(btBroadcastReceiver,intentFilter);

2、在广播接收器中处理

 /**     * 蓝牙广播接收器     */    private class BtBroadcastReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            if(TextUtils.equals(action,BluetoothDevice.ACTION_BOND_STATE_CHANGED)){                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);                int bondSate = bluetoothDevice.getBondState();                switch(bondSate) {                    case BluetoothDevice.BOND_NONE:                        Log.d(TAG, "已解除配对");                        break;                    case BluetoothDevice.BOND_BONDING:                        Log.d(TAG, "正在配对...");                        break;                    case BluetoothDevice.BOND_BONDED:                        Log.d(TAG, "已配对");                        break;                }            }else if(TextUtils.equals(action,BluetoothDevice.ACTION_PAIRING_REQUEST)){                int type = -1;                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {                    type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,BluetoothDevice.ERROR);                    Log.d(TAG, "ACTION_PAIRING_REQUEST--"+type);                    //PAIRING_VARIANT_PIN 0                     if(type == BluetoothDevice.PAIRING_VARIANT_PIN){                        //防止弹出一闪而过的配对框                        abortBroadcast();                        //弹框后自动输入密码、自动确定                        boolean isSetPin = curBluetoothDevice.setPin("0000".getBytes());                        Log.d(TAG, "setPin()-->" + isSetPin);                    }            }        }    }

 因为官方的BluetoothDevice.setPin() 是支持API 19以上的设备,所以在低于API 19的设备上,需要使用反射的方法来获取setPin()方法。

 /**     * 蓝牙广播接收器     */    private class BtBroadcastReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            if(TextUtils.equals(action,BluetoothDevice.ACTION_BOND_STATE_CHANGED)){                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);                int bondSate = bluetoothDevice.getBondState();                switch(bondSate) {                    case BluetoothDevice.BOND_NONE:                        Log.d(TAG, "已解除配对");                        break;                    case BluetoothDevice.BOND_BONDING:                        Log.d(TAG, "正在配对...");                        break;                    case BluetoothDevice.BOND_BONDED:                        Log.d(TAG, "已配对");                        break;                }            }else if(TextUtils.equals(action,BluetoothDevice.ACTION_PAIRING_REQUEST)){                int type = -1;                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {                    type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,BluetoothDevice.ERROR);                    Log.d(TAG, "ACTION_PAIRING_REQUEST--"+type);                    //PAIRING_VARIANT_CONSENT 0                     if(type == BluetoothDevice.PAIRING_VARIANT_PIN){                        //防止弹出一闪而过的配对框                        abortBroadcast();                        //弹框后自动输入密码、自动确定                        try {                            boolean isSetPin = ClsUtils.autoBond(BluetoothDevice.class,curBluetoothDevice,"0000");                            Log.d(TAG, "setPin()-->" + isSetPin);                        } catch (Exception e) {                            e.printStackTrace();                        }                    }            }        }    }

ClsUtils.java中autoBond()方法如下:

 //自动配对设置Pin值    static public boolean autoBond(Class btClass,BluetoothDevice device,String strPin) throws Exception {        Method autoBondMethod = btClass.getMethod("setPin",new Class[]{byte[].class});        Boolean result = (Boolean)autoBondMethod.invoke(device,new Object[]{strPin.getBytes()});        return result;    }

 

六、小结

1、justwork配对模式下,

(1)调用反射的配对方法或者官方API的配对方法,都能实现自动配对,不会弹出配对框。

(2)调用官方API首次连接,且建立非安全的连接,不会弹出配对框,但是本质是因为没有执行配对操作。

2、pincode配对模式下,实现自动配对的方法,只适用Android 8.0及以下的系统,Android 9.0及以上系统不生效。

3、如果想要实现弹出配对框时自动输入或点击,可以使用无障碍服务(Accessibility Service)。通过获取界面的控件,比如输入框、按钮,然后模拟输入或点击,实现自动配对。

注意:上面所说的justwork或pincode模式也不是绝对的,因为这完全是由蓝牙设备软件工程师决定的,所以实际开发时还是要根据实际的设备进行方式的选择。

更多相关文章

  1. Qt on Android(安卓)实现App普通全屏、沉浸模式、粘性沉浸模式
  2. Android(安卓)App调用SDK 登录第一次总是失败的解决方法
  3. [置顶] android 程序开发的插件化 模块化方法 之二
  4. [置顶] Android(安卓)轻松实现网络交互模板
  5. [置顶] Android(安卓)自定义ViewGroup实现整个Item布局竖直跑马
  6. Android(安卓)bugs——RecyclerView scrollToPosition不会触发sc
  7. Android坐标系统常用方法属性总结
  8. Android(安卓)ROM分析(1):刷机原理及方法
  9. android 游戏:俄罗斯方块的小结

随机推荐

  1. android sdk+MyEclipse+adt 配置与开发
  2. 【android】欢迎来到Android多进程时代
  3. Android中使用animation的方法
  4. Android的IPC机制Binder的各个部分
  5. Android(安卓)模拟器几个小问题
  6. 搭建Android开发环境
  7. Android(安卓)Project Structure
  8. Universal-Image-Loader(android图片缓存)
  9. Android兼容性测试框架(CTS)手册
  10. Android初步了解入门