3

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

安卓清单:

<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());
        }

    }
4

1 回答 1

3

这个问题很老,但我仍然会尝试一下。为了对这些 USB 命令采取行动,我使用了广播接收器。```

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);
}
于 2018-02-05T04:23:58.520 回答