Android USB操作(ACTION_USB_DEVICE_ATTACHED& ACTION_USB_DEVICE_DETACHED)无法在BroadcastReceiver

时间:2017-03-21 07:20:00

标签: android android-broadcastreceiver android-usb

我正在使用需要侦听USB事件的应用程序(ACTION_USB_DEVICE_ATTACHED& ACTION_USB_DEVICE_DETACHED)。我创建了一个侦听这些动作的接收器。但是,当发生任何这些事件时,我的接收器不会启动。

Android Manifest:

<uses-feature android:name="android.hardware.usb.host" />

<receiver android:name=".USBEventReceiver">
            <intent-filter >
                <action android:name="android.hardware.usb.action.USB_STATE"/>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"/>
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/usb_device"/>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"
                android:resource="@xml/usb_device"/>
 </receiver>

BroadCastReceiver onReceive方法:

public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        UsbManager usbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);

        if (intent.getExtras().getBoolean("connected")) {
            Log.d(TAG, "onReceive: connected");
        } else if (!intent.getExtras().getBoolean("connected")) {
            Log.d(TAG, "onReceive: disconnected");
        }

        if (usbManager != null) Log.d(TAG, "onReceive: " + usbManager.getDeviceList().toString());

        if (device != null) Log.d(TAG, "USB Attached: " + device);


        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            Log.d(TAG, "onReceive: " + device.getManufacturerName());
            Log.d(TAG, "onReceive: " + device.getProductName());
            Log.d(TAG, "onReceive: " + device.getSerialNumber());
            Log.d(TAG, "onReceive: " + device.getSerialNumber());
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            Log.d(TAG, "onReceive: " + device.getManufacturerName());
            Log.d(TAG, "onReceive: " + device.getProductName());
            Log.d(TAG, "onReceive: " + device.getSerialNumber());
        }

    }

1 个答案:

答案 0 :(得分:1)

这个问题已经过时了,但我还是会捅它。为了对这些USB命令采取措施,我使用了BroadCast接收器。 ```

private final Broadcast Receiver mUsbReceiver = 
    switch(intent.getAction() {
        case UsbService.ACTION_USB_ATTACHED:
           //do something
        case UsbService.ACTION_USB_DETACHED:
            //do something

```

您需要在以下内容中注册接收器:

private void setFilters() {
    IntentFilter filter = new IntentFilter();

    //New Service Filters
    filter.addAction(UsbService.ACTION_USB_ATTACHED);
    filter.addAction(UsbService.ACTION_USB_DETACHED);    
    registerReceiver(mUsbReceiver, filter);
}