Demo下载:http://www.demodashi.com/demo/13891.html
最近客户需求,android系统的一个设备,想连接一个扫描枪(类似蓝牙键盘,只支持hid协议),并且可以收到其数据,填写到输入框中。我这里借了一个蓝牙鼠标,用来与android设备连接。
1 Hid简介
HID设备(Hunman Interface Device Profile),即人机交互设备,常见的有鼠标,键盘,游戏手柄,等等。一般有线方式都是通过USB连线连接到机器设备,作为用户输入设备。在蓝牙技术中,HID设备的接入就是无线的了。
网上查资料说hid从android4.0开始支持(可能是usb hid),不过蓝牙hid应该从android4.2开始支持的,如下图所示:
android4.1.2中的Bluetooth应用中没有hid的相关代码,而android4.2源码中Bluetooth应用中才有hid的代码。
2 主要代码
连接hid设备步骤:
- 开启蓝牙
- 获得inputDevice profile
- 扫描
- 配对
- 连接
2.1 开启蓝牙,通过广播接收者监听蓝牙相关状态。
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "不支持蓝牙功能", 0).show();
// 不支持蓝牙
return;
}
// 如果没有打开蓝牙
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
// 初始化广播接收者
mBroadcastReceiver = new BlueBroadcastReceiver();
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");
this.registerReceiver(mBroadcastReceiver, intentFilter);
2.2 获得inputDevice profile
// 4.2以上才支持HID模式
if (Build.VERSION.SDK_INT >=