android监听usb的插入与拔出

usb的插入与拔出的监听,系统已经为我们提供了接口。

USB设备插入系统检测到ACTION_USB_DEVICE_ATTACHED

USB设备拔出系统检测到ACTION_USB_DEVICE_DETACHED

实现步骤如下(注意我这里使用的是动态注册广播接收者,你也可以改为静态注册):

1、创建广播接收者:

BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    Log.e(TAG,"拔出usb了");
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device != null) {
                        Log.e(TAG,"设备的ProductId值为:"+device.getProductId());
                        Log.e(TAG,"设备的VendorId值为:"+device.getVendorId());
                    }
                }else if(UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)){
                    Log.e(TAG,"插入usb了");
                }
            }
        };
2、注册广播接收者,开始监听usb插入与拔出实践

IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mUsbReceiver, usbDeviceStateFilter);
就这么简单,你懂了把。本人提供了usb调试助手,应用宝下载地址: 点击打开链接



你可能感兴趣的:(嵌入式开发)