我可以将蓝牙键盘配对,但无法连接使其成为输入设备。 我查看了开发者网站提供的文档 - http://developer.android.com/guide/topics/connectivity/bluetooth.html#Profiles
文档中指出,Android 蓝牙 API 提供以下蓝牙配置文件的实现,但您可以实现 BluetoothProfile 接口来编写自己的类以支持特定的蓝牙配置文件:
- 耳机(Headset)
- A2DP
- 医疗健康设备(Health Device)
没有文档说明如何为 HID 蓝牙设备(键盘)实现 BluetoothProfile。
Android 已经为 HID 设备实现了蓝牙连接,但这些 API 是隐藏的。我尝试使用反射来使用它们,但是键盘并没有作为输入设备连接。这就是我所做的:
private void connect(final BluetoothDevice bluetoothDevice) {
if(bluetoothDevice.getBluetoothClass().getDeviceClass() == 1344){
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Log.i("btclass", profile + "");
if (profile == getInputDeviceHiddenConstant()) {
Class instance = null;
try {
//instance = Class.forName("android.bluetooth.IBluetoothInputDevice");
instance = Class.forName("android.bluetooth.BluetoothInputDevice");
Method connect = instance.getDeclaredMethod("connect", BluetoothDevice.class);
Object value = connect.invoke(proxy, bluetoothDevice);
Log.e("btclass", value.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(int profile) {
}
};
mBluetoothAdapter.getProfileProxy(this, mProfileListener,getInputDeviceHiddenConstant());
}
}
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) {
Log.e("", e.toString(), e);
}
}
}
return -1;
}