gpt4 book ai didi

Android USB 操作(ACTION_USB_DEVICE_ATTACHED 和 ACTION_USB_DEVICE_DETACHED)在 BroadcastReceiver 中不起作用

转载 作者:行者123 更新时间:2023-11-29 01:11:08 25 4
gpt4 key购买 nike

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

Android list :

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

}

最佳答案

这个问题很老了,但我还是会尝试一下。为了对这些 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);
}

关于Android USB 操作(ACTION_USB_DEVICE_ATTACHED 和 ACTION_USB_DEVICE_DETACHED)在 BroadcastReceiver 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com