Android 配对连接HID蓝牙设备

前段时间公司项目的需要连接蓝牙设备,我们这个蓝牙设备是一个蓝牙手柄,相当于是一个蓝牙外设键盘,所以是属于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线程池得要这么用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • 最近项目使用蓝牙,之前并没有接触,还是发现了很多坑,查阅了很多资料,说的迷迷糊糊,今天特查看官方文档。 说下遇到的...
    King9527阅读 1,692评论 0 1
  • 蓝牙 注:本文翻译自https://developer.android.com/guide/topics/conn...
    RxCode阅读 8,468评论 11 99
  • 前言 最近在做Android蓝牙这部分内容,所以查阅了很多相关资料,在此总结一下。 基本概念 Bluetooth是...
    猫疏阅读 14,222评论 7 113
  • Guide to BluetoothSecurity原文 本出版物可免费从以下网址获得:https://doi.o...
    公子小水阅读 7,617评论 0 6
  • Android 平台包含蓝牙网络堆栈支持,凭借此项支持,设备能以无线方式与其他蓝牙设备交换数据。应用框架提供了通过...
    虎三呀阅读 743评论 0 1