Android 获取USB等多个输入设备信息-InputDevice
Activity内的onKeyDown函数可以捕获输入设备的输入,但是如果android接了多个usb或者其他接口的输入设备,这时候,怎么获取不同输入设备的信息呢?如果能获取到这个输入设备的信息,我们就可以区分不同的输入设备来响应不同的事件。
所以翻了一KeyEvent这个类,查看了里面的方法,发现有这么一个类InputDevice
InputDevice这个对象有两种获取方式
//第一种
InputDevice inputDevice = InputDevice.getDevice(event.getDeviceId());
//第二种 通过InputManager获取
InputManager inputManager = (InputManager)getSystemService(Context.INPUT_SERVICE);
InputDevice inputDevice = inputManager.getInputDevice(event.getDeviceId());
//不过都需要获取到DeviceId的前题 如果不在onKeyDown这个接口里呢?
//我们可以通过InputManager获取到当前的所有设备的DeviceId
int[] inputDeviceIds= inputManager.getInputDeviceIds();
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getDeviceId() == KeyCharacterMap.VIRTUAL_KEYBOARD) {//如果是虚拟键盘则不截获输入事件
return false;
}
InputDevice inputDevice = InputDevice.getDevice(event.getDeviceId());
Log.e("key", "onKeyDown: InputDevice:name=" + inputDevice.getName()+",productId="+inputDevice.getProductId()+",VendorId="+ inputDevice.getVendorId());
Log.e("key", "onKeyDown: keyCode=" + keyCode + "String=" + KeyEvent.keyCodeToString(keyCode));
//监听键盘以及二维码输入
return true;//截获事件
}
以上就是在onKeyDown这个接口里获取输入设备信息的方法,有了设备信息,区分判断就是很简单的事情了