Android检测外接USB设备的几种方法

您所在的位置:网站首页 安卓usb麦克风驱动apk Android检测外接USB设备的几种方法

Android检测外接USB设备的几种方法

2024-07-14 04:56| 来源: 网络整理| 查看: 265

遇到需要监测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盘属于块设备,或许是因为这个原因导致二者的差别?



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3