Android检测外接USB设备的几种方法
16lz
2023-05-28
遇到需要监测USB键盘的问题,搜集了一些方法做总结。
1. 使用BroadcastReceiver监听系统广播
private void detectUsbWithBroadcast() { Log.d(TAG, "listenUsb: register"); IntentFilter filter = new IntentFilter(); filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED); filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED); filter.addAction("android.hardware.usb.action.USB_STATE"); registerReceiver(mUsbStateChangeReceiver, filter); Log.d(TAG, "listenUsb: registered"); } private BroadcastReceiver mUsbStateChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive: " + intent.getAction()); } };
2. 使用InputManager检测输入设备
private void detectUsbDeviceWithInputManager() { InputManager im = (InputManager) getSystemService(INPUT_SERVICE); int[] devices = im.getInputDeviceIds(); for (int id : devices) { InputDevice device = im.getInputDevice(id);// Log.d(TAG, "detectUsbDeviceWithInputManager: " + device.getName()); //do something } }
3. 使用Configuration
private void detectUsbKeyboardWithConfig() { Configuration config = getResources().getConfiguration(); if (config.keyboard == Configuration.KEYBOARD_NOKEYS) { Log.i(TAG, "detectUsbKeyboardWithConfig: config: no keyboard"); } else { Log.i(TAG, "detectUsbKeyboardWithConfig: config: has keyboard: " + config.keyboard); } }
4. 使用UsbManager
private void detectUsbDeviceWithUsbManager() { HashMap deviceHashMap = ((UsbManager) getSystemService(USB_SERVICE)).getDeviceList(); for (Map.Entry entry : deviceHashMap.entrySet()) { Log.d(TAG, "detectUsbDeviceWithUsbManager: " + entry.getKey() + ", " + entry.getValue()); } }
5. 调用Linux命令
private void detectInputDeviceWithShell() { try { //获得外接USB输入设备的信息 Process p = Runtime.getRuntime().exec("cat /proc/bus/input/devices"); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = in.readLine()) != null) { String deviceInfo = line.trim(); //对获取的每行的设备信息进行过滤,获得自己想要的。// if (deviceInfo.contains("Name=")) Log.d(TAG, "detectInputDeviceWithShell: " + deviceInfo); } Log.d(TAG, "-----------------------"); } catch (Exception e) { e.printStackTrace(); } }
对于usb键盘,以上2、5两种方法是行之有效的,其他的并不能检测到,具体原因不明。
根据网上所说,Linux下USB设备分为字符设备(顺序访问)和块设备(随机访问),而键盘属于字符设备,U盘属于块设备,或许是因为这个原因导致二者的差别?
更多相关文章
- 箭头函数的基础使用
- NPM 和webpack 的基础使用
- Python list sort方法的具体使用
- 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
- android 使用html5作布局文件: webview跟javascript交互
- Android(安卓)Resource介绍和使用
- "Failed to fetch URL https://dl-ssl.google.com/android/repos
- 使用NetBeans搭建Android开发环境
- android 零星调试笔记