当前位置:   article > 正文

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

usbmanager.action_usb_device_detached

遇到需要监测USB键盘的问题,搜集了一些方法做总结。

1. 使用BroadcastReceiver监听系统广播

  1. private void detectUsbWithBroadcast() {
  2. Log.d(TAG, "listenUsb: register");
  3. IntentFilter filter = new IntentFilter();
  4. filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
  5. filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
  6. filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
  7. filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
  8. filter.addAction("android.hardware.usb.action.USB_STATE");
  9. registerReceiver(mUsbStateChangeReceiver, filter);
  10. Log.d(TAG, "listenUsb: registered");
  11. }
  12. private BroadcastReceiver mUsbStateChangeReceiver = new BroadcastReceiver() {
  13. @Override
  14. public void onReceive(Context context, Intent intent) {
  15. Log.d(TAG, "onReceive: " + intent.getAction());
  16. }
  17. };


2. 使用InputManager检测输入设备

  1. private void detectUsbDeviceWithInputManager() {
  2. InputManager im = (InputManager) getSystemService(INPUT_SERVICE);
  3. int[] devices = im.getInputDeviceIds();
  4. for (int id : devices) {
  5. InputDevice device = im.getInputDevice(id);
  6. // Log.d(TAG, "detectUsbDeviceWithInputManager: " + device.getName());
  7. //do something
  8. }
  9. }


3. 使用Configuration

  1. private void detectUsbKeyboardWithConfig() {
  2. Configuration config = getResources().getConfiguration();
  3. if (config.keyboard == Configuration.KEYBOARD_NOKEYS) {
  4. Log.i(TAG, "detectUsbKeyboardWithConfig: config: no keyboard");
  5. } else {
  6. Log.i(TAG, "detectUsbKeyboardWithConfig: config: has keyboard: " + config.keyboard);
  7. }
  8. }


4. 使用UsbManager

  1. private void detectUsbDeviceWithUsbManager() {
  2. HashMap<String, UsbDevice> deviceHashMap = ((UsbManager) getSystemService(USB_SERVICE)).getDeviceList();
  3. for (Map.Entry entry : deviceHashMap.entrySet()) {
  4. Log.d(TAG, "detectUsbDeviceWithUsbManager: " + entry.getKey() + ", " + entry.getValue());
  5. }
  6. }


5. 调用Linux命令

  1. private void detectInputDeviceWithShell() {
  2. try {
  3. //获得外接USB输入设备的信息
  4. Process p = Runtime.getRuntime().exec("cat /proc/bus/input/devices");
  5. BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
  6. String line = null;
  7. while ((line = in.readLine()) != null) {
  8. String deviceInfo = line.trim();
  9. //对获取的每行的设备信息进行过滤,获得自己想要的。
  10. // if (deviceInfo.contains("Name="))
  11. Log.d(TAG, "detectInputDeviceWithShell: " + deviceInfo);
  12. }
  13. Log.d(TAG, "-----------------------");
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }


对于usb键盘,以上2、5两种方法是行之有效的,其他的并不能检测到,具体原因不明。

根据网上所说,Linux下USB设备分为字符设备(顺序访问)和块设备(随机访问),而键盘属于字符设备,U盘属于块设备,或许是因为这个原因导致二者的差别?

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/210513
推荐阅读
  

闽ICP备14008679号