美文网首页
Android 配对连接HID蓝牙设备

Android 配对连接HID蓝牙设备

作者: 光羽隼 | 来源:发表于2018-09-20 11:40 被阅读0次

    前段时间公司项目的需要连接蓝牙设备,我们这个蓝牙设备是一个蓝牙手柄,相当于是一个蓝牙外设键盘,所以是属于HID设备。刚开始也不知道还有HID蓝牙设备,所以就按照普通蓝牙设备连接。翻找了好久的资料,才一点一点做好。

    HID 是Human Interface Device的缩写,由其名称可以了解HID设备是直接与人交互的设备,例如键盘、鼠标与游戏杆等。不过HID设备并不一定要有人机接口,只要符合HID类别规范的设备都是HID设备。
    android4.1.2中的Bluetooth应用中没有hid的相关代码,而android4.2源码中Bluetooth应用中才有hid的代码。

    重点提一句,在实际使用中,其实设备的配对连接都不难,但是一定要开启子线程进行蓝牙设备的开关、配对和连接。不然很容易出现一堆异常。。。。

    使用蓝牙之前,我们需要在AndroidManifest.xml里边申请三个权限,因为我做的算是系统级的软件,就没有动态申请权限。

     <uses-permission android:name="android.permission.BLUETOOTH" />
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    这里说一下,刚开始遇到的第一个坑,就是很多博客里边只讲了前两个权限,而没有说第三个权限。

    1.首先是蓝牙设备的打开和关闭

    在了解蓝牙开关之前,我们首先要知道蓝牙适配器的类BluetoothAdapter,这个类的主要功能就是:

    • 开关蓝牙
    • 扫描蓝牙设备
    • 设置/获取蓝牙状态信息,例如:蓝牙状态值、蓝牙Name、蓝牙Mac地址等;

    直接上代码:

    //获取BluetoothAdapter,如果获取的BluetoothAdapter为空,则表示当前设备不支持蓝牙
    BluetoothManager bluetoothManager = (BluetoothManager) SPApplication.getInstance().getSystemService(Context.BLUETOOTH_SERVICE);
    if (bluetoothManager != null) {
           BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
     } else {
          ToastUtils.showShort("蓝牙暂时不可用");
          finishDelegate();
    }
    
    //判断蓝牙是否打开
    if (!mBluetoothAdapter.isEnabled()) {
      //蓝牙设备没有打开
    //打开蓝牙设备,这一步应该放到线程里边操作
    mBluetoothAdapter.enable();          
    } else {
    //蓝牙设备已经打开,需要关闭蓝牙
    //这一步也需要放到线程中操作
    mBluetoothAdapter.disable();         
     }
    

    2.开始进行蓝牙的扫描

    蓝牙的扫描是使用BluetoothAdapter对象中的方法startDiscovery(),不过首先我们需要注册一个广播接收者,接收蓝牙扫描的数据。

    1.广播接收者:
    public class BluetoothReciever extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                BluetoothDevice device;
                // 搜索发现设备时,取得设备的信息;注意,这里有可能重复搜索同一设备
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    //这里就是我们扫描到的蓝牙设备
                    device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
                }
                //状态改变时
                else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                    device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    switch (device.getBondState()) {
                        case BluetoothDevice.BOND_BONDING://正在配对
                            Log.d("BlueToothTestActivity", "正在配对......");
                            break;
                        case BluetoothDevice.BOND_BONDED://配对结束
                            Log.d("BlueToothTestActivity", "完成配对");
    
                            break;
                        case BluetoothDevice.BOND_NONE://取消配对/未配对
                            Log.d("BlueToothTestActivity", "取消配对");
    
                        default:
                            break;
                    }
                }
            }
        }
    

    创建并注册蓝牙扫描的广播接收者:

     // 初始化广播接收者
    mBroadcastReceiver = new BluetoothReciever();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    intentFilter.addAction("android.bluetooth.input.profile.action.CONNECTION_STATE_CHANGED");
    //这里我是用全局上下文注册广播接收者,防止在解注册的时候出错
    SPApplication.getInstance().registerReceiver(mBroadcastReceiver, intentFilter);
    

    开始进行蓝牙扫描

     mBluetoothAdapter.startDiscovery();
    

    开始扫描之后,广播接收者中就会出现我们扫描到的设备,设备信息存放在BluetoothDevice对象中,我们可以将这个对象存放到列表中,然后取出里边的信息展示到界面上。

    3.蓝牙设备的配对和连接过程

    HID蓝牙设备在配对成功之后还要进行连接这一步操作,而普通的蓝牙设备只需要配对这一步。顺便提一句,蓝牙设备的配对和连接需要放到子线程中操作。
    对其中的连接操作以及BluetoothProfile的我也不是很理解,这里可以参考Android HID设备的连接,这篇博客中对连接的步骤讲的还是很清楚的。
    这里我把蓝牙设备的配对和连接,我写到了Runnable的复写类里边,方便放到子线程中使用。

    public class BlueConnectThread implements Runnable {
        private Handler handler;
        private BluetoothDevice device;
        private BluetoothAdapter mAdapter;
        
        public BlueConnectThread(Handler handler, BluetoothDevice device, BluetoothAdapter adapter) {
            this.handler = handler;
            this.device = device;
            this.mAdapter = adapter;
        }
    
        @Override
        public void run() {
            //进行HID蓝牙设备的配对,配对成功之后才进行下边的操作
            if (pair(device)) {
                try {
                   //进行HID蓝牙设备的连接操作,并返回连接结果,这里边的第3个参数就是代表连接HID设备,
                    boolean profileProxy = mAdapter.getProfileProxy(SPApplication.getInstance(), connect, 4);
                    Thread.sleep(3000);
                    Message message = handler.obtainMessage(BluetoothDialog.CONNECT_BLUE);
                    //通过handler将连接结果和连接的代理返回主线程中。这个BluetoothProfile对象在后边还有用,所以要返回主线程中
                    if (profileProxy) {
                        message.arg1=1;
                    }else {
                        message.arg1=2;
                    }
                    message.obj = proxys;
                    handler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 配对
         *
         * @param bluetoothDevice
         */
        public boolean pair(BluetoothDevice bluetoothDevice) {
            device = bluetoothDevice;
            Method createBondMethod;
            try {
                createBondMethod = BluetoothDevice.class.getMethod("createBond");
                createBondMethod.invoke(device);
                return true;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return false;
        }
        /**
          *个人理解是获取当前设备设备是否支持INPUT_DEVICE设备(HID设备)
          */
        public static int getInputDeviceHiddenConstant() {
            Class<BluetoothProfile> clazz = BluetoothProfile.class;
            for (Field f : clazz.getFields()) {
                int mod = f.getModifiers();
                if (Modifier.isStatic(mod) && Modifier.isPublic(mod)
                        && Modifier.isFinal(mod)) {
                    try {
                        if (f.getName().equals("INPUT_DEVICE")) {
                            return f.getInt(null);
                        }
                    } catch (Exception e) {
                    }
                }
            }
            return -1;
        }
    
        private BluetoothProfile proxys;
        /**
         * 查看BluetoothInputDevice源码,connect(BluetoothDevice device)该方法可以连接HID设备,但是查看BluetoothInputDevice这个类
         * 是隐藏类,无法直接使用,必须先通过BluetoothProfile.ServiceListener回调得到BluetoothInputDevice,然后再反射connect方法连接
         */
        private BluetoothProfile.ServiceListener connect = new BluetoothProfile.ServiceListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                //BluetoothProfile proxy这个已经是BluetoothInputDevice类型了
                try {
                    proxys = proxy;
                    if (profile == getInputDeviceHiddenConstant()) {
                        if (device != null) {
                            //得到BluetoothInputDevice然后反射connect连接设备
                            @SuppressLint("PrivateApi") Method method = proxy.getClass().getDeclaredMethod("connect",
                                    new Class[]{BluetoothDevice.class});
                            method.invoke(proxy, device);
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
    
            @Override
            public void onServiceDisconnected(int profile) {
    
            }
        };
    }
    

    4.关闭当前界面

    需要注销广播接收者的注册
    @Override
    public void onPause() {
        super.onPause();
        SPApplication.getInstance().unregisterReceiver(mBroadcastReceiver);
    }
    
    解除连接的代理(暂时这样理解)

    做这一步的原因是因为每次退出蓝牙界面都会出现错误,

    android.app.ServiceConnectionLeaked: android.app.ServiceConnectionLeaked: Activity.com.xxxxxx.bluetoothconnect.MainActivity has leaked ServiceConnection android.bluetooth.BluetoothInputDevice$2@fd389e1 that was originally bound here
    

    这,,,这好像是连接那一步绑定了服务,在关闭界面的时候没有解绑服务。那我们只需要找到在哪开启了什么服务,再找到解绑这个服务的方法就行了。
    然后我就找到HID设备连接的方法getProfileProxy(SPApplication.getInstance(), connect, 4),进到源码中查看,被我发现了BluetoothAdapter里边的closeProfileProxy(int profile, BluetoothProfile proxy)这个方法,这个方法在源码中的注释是

     /**
         * Close the connection of the profile proxy to the Service.
         *
         * <p> Clients should call this when they are no longer using
         * the proxy obtained from {@link #getProfileProxy}.
         * Profile can be one of  {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or
         * {@link BluetoothProfile#A2DP}
         *
         * @param profile
         * @param proxy Profile proxy object
         */
     public void closeProfileProxy(int profile, BluetoothProfile proxy) 
    

    凭借我英语亚四级的水平,我们可以知道这个方法就是关闭服务的,这个服务跟连接有某种不可告人的关系。。。
    那我们就直接在关闭界面的时候使用就行了。注意,经验告诉我这个方法也需要在子线程中使用。
    刚才从子线程中传回来的BluetoothProfile对象在这里就能用到了。

     @Override
        public void onDestroyView() {
            super.onDestroyView();
            if (proxy != null) {
                ThreadPoolProxyFactory.getNormalThreadPoolProxy().execute(new Runnable() {
                    @Override
                    public void run() {
                        mBluetoothAdapter.closeProfileProxy(4, proxy);
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    

    -----------结束!
    这里我只做了蓝牙开关,扫描,连接配对的操作,关于蓝牙信号的接受和发送没有做。因为没有需求啊,哈哈哈。
    有时间我再把源码整理出来。
    里边的线程池参考Android线程池得要这么用

    相关文章

      网友评论

          本文标题:Android 配对连接HID蓝牙设备

          本文链接:https://www.haomeiwen.com/subject/lgdbgftx.html