android USB插拔检测

这里是可以检测一些可以操作的USB设备,比如U盘,打印机等可以通信的都可以检测出来,像鼠标是检测不出来的。


IntentFilter usbDeviceStateFilter = new IntentFilter();
usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(usbBroadcastReceiver,usbDeviceStateFilter);

//USB监听
class USBBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        String action=intent.getAction();
        LogUtil.i(TAG,action);
        if(UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {

            EventBus.getDefault().post(new SettingBusEvent("USB_CONNECTED"));
        }
        else if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
            EventBus.getDefault().post(new SettingBusEvent("USB_DISCONNECTED"));
    }
};


你可能感兴趣的:(Android开发)