1
我正在開發一個需要偵聽USB事件的應用程序(ACTION_USB_DEVICE_ATTACHED & ACTION_USB_DEVICE_DETACHED)。我創建了一個接收器來監聽這些操作。但是,當發生這些事件時,我的接收器不會啓動。Android USB操作(ACTION_USB_DEVICE_ATTACHED&ACTION_USB_DEVICE_DETACHED)在BroadcastReceiver中不起作用
Android清單:
<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>
廣播接收器的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());
}
}
難道你得到解決嗎? – RohitMat
@RohitMat是的,我確實得到了一個。 –