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