一、需求
在Android 开发过程中,在App中实现检测USB是否插入。
二、实现过程
1、使用UsbManager.ACTION_USB_DEVICE_DETACHED和UsbManager.ACTION_USB_DEVICE_ATTACHED检测USB的插拔无法实现。
2、使用UsbManager.ACTION_USB_STATE和UsbManager.ACTION_USB_CONNECTED
1 private boolean isUsbPlugged() { 2 Intent usbStateIntent = registerReceiver(null, new IntentFilter(UsbManager.ACTION_USB_STATE)); 3 if (usbStateIntent == null) { 4 return false; 5 } 6 final String usbAction = usbStateIntent.getAction(); 7 if (UsbManager.ACTION_USB_STATE.equals(usbAction)) { 8 Bundle extras = usbStateIntent.getExtras(); 9 boolean connected = extras.getBoolean(UsbManager.USB_CONNECTED); 10 if (connected) { 11 Toast.makeText(AgingTest.this, "USB inserted!", Toast.LENGTH_SHORT).show(); 12 } else { 13 Toast.makeText(AgingTest.this, "USB no inserted!", Toast.LENGTH_SHORT).show(); 14 } 15 } 16 return true; 17 }标签:Toast,usbStateIntent,USB,UsbManager,App,ACTION,Android From: https://www.cnblogs.com/tangtangsweet/p/17402628.html