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

标签 android usb broadcast intentfilter

我有一个 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>

我还有一个服务,我想在其中监视连接和断开连接。我已连接广播接收器,它们在设备连接和分离时触发。但是,我希望这些广播接收器在仅附加/分离我的 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/

相关文章:

android - 如何从广播中执行正在运行的服务的方法?

apache-spark - 在另一个数据框的UDF中时如何引用数据框?

c - 用于通过 wifi radio 向其范围内的设备发送广播数据包的套接字程序

android - PendingIntent 不会启动所需的 fragment

python - 构建 pyinstaller 可执行文件时,我可以控制架构(32 位与 64 位)吗?

c++ - 使用 Qt 进行 USB 编程

c++ - USB 磁盘写入延迟 (windows)

android - 升级依赖项后无法解析 ActivityTestRule。无法导入 ActivityTestRule

java - 在 Eclipse 中找不到资源

java - 如何在不丢弃中间字符串的情况下验证在 EditText 中键入的字符串?