我想出了如何解决我的问题。That非常有帮助。
首先,我需要准备反射方法,该方法返回 hid 配置文件的 input_device 隐藏常量:
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(LOG_TAG, e.toString(), e);
}
}
}
return -1;
}
我可以使用值 4,而不是该函数,但我想做得优雅一些。
第二步是定义特定配置文件的侦听器:
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Log.i("btclass", profile + "");
if (profile == ConnectToLastBluetoothBarcodeDeviceTask.getInputDeviceHiddenConstans()) {
List<BluetoothDevice> connectedDevices = proxy.getConnectedDevices();
if (connectedDevices.size() == 0) {
} else if (connectedDevices.size() == 1) {
BluetoothDevice bluetoothDevice = connectedDevices.get(0);
...
} else {
Log.i("btclass", "too many input devices");
}
}
}
@Override
public void onServiceDisconnected(int profile) {
}
};
在第三步中我调用了
mBluetoothAdapter.getProfileProxy(getActivity(), mProfileListener,
ConnectToLastBluetoothBarcodeDeviceTask.getInputDeviceHiddenConstant());
一切都清楚地工作,mProfileListener 返回特定配置文件蓝牙设备/-es 的列表。
最有趣的事情发生在 onServiceConnected() 方法中,该方法返回隐藏类 BluetoothInputDevice 的对象:)