Android 获取USB输入设备信息/区分虚拟键盘和外接键盘输入

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这个接口里获取输入设备信息的方法,有了设备信息,区分判断就是很简单的事情了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值