我正在开发一个需要监听 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());
}
}