Android监听USB插拔事件

Android监听USB插拔事件有两种方式:

一种是在Mainifest.xml中注册

 
               
           

                            android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />

android.hardware.usb.action.USB_DEVICE_ATTACHED即在usb插入是的action意图。在android.hardware.usb.UsbManager类中有多种action的定义,有兴趣的可以查看一下。

device_filter.xml文件是对usb端口和接口的过滤。

 






即当包含由上述的usb插入时,即会发送USB_DEVICE_ATTACHED action,启动activity。

另一种方式是在代码中遍历匹配,如下所示:

//使用usb时API版本必须是12以上
UsbManager usbManager=(UsbManager) getSystemService(Context.USB_SERVICE);
Map deviceList=usbManager.getDeviceList();
Iterator iterator=deviceList.values().iterator();
while(iterator.hasNext()){
UsbDevice usbDevice=iterator.next();
int deviceID=usbDevice.getDeviceId();
int productID=usbDevice.getProductId();
int vendorID=usbDevice.getVendorId();
//进行匹配todo....
}

ps:API的最低版本是12或以上,12以下的版本没有此功能。

你可能感兴趣的:(android学习)