gpt4 book ai didi

android - BroadcastReceiver 监控连接的特定 USB 设备

转载 作者:行者123 更新时间:2023-11-29 00:17:50 27 4
gpt4 key购买 nike

我有一个 Activity 在连接特定 USB 设备时启动,如设备过滤器文件中所指定,效果很好:

<activity
android:name="com.mycompany.DerpApp.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</activity>

我还有一项服务,我想在其中监视连接和断开连接。我已经连接了 BroadcastReceivers,它们会在设备连接和分离时触发。但是,我希望这些广播接收器仅在我的 device_filter.xml 中指定的设备连接/分离时触发。

m_usbDisconnectReceiver = new UsbDisconnectReceiver();
registerReceiver(m_usbDisconnectReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));

m_usbConnectReceiver = new UsbConnectReceiver();
registerReceiver(m_usbConnectReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));

我不确定如何将我的 device_filter 文件附加到以编程方式创建的广播接收器。为此,我可以在 IntentFilter 中做些什么吗?我认为提供给 onReceive() 的 Intent 有一个 UsbDevice 作为它的额外功能之一,但最好是我可以过滤掉它,这样事件就不会触发。如果这不可能,我如何检查 UsbDevice 是否是我的 device_filter 的一部分?

最佳答案

如果您绝对必须以编程方式创建 BroadcastReceiver,那么您还需要以编程方式过滤设备。

试试这个:

public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED))
{
UsbDevice d = (UsbDevice)
intent.getExtras().get(UsbManager.EXTRA_DEVICE);

if (d.getVendorId() == MY_VENDOR_ID && d.getDeviceId() == MY_DEVICE_ID)
{
// Your code here
}
}
}

关于android - BroadcastReceiver 监控连接的特定 USB 设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25384418/

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