I’m developing an Android application that manages USB devices using an external library. The MainActivity instantiates this library, which handles USB device events (connect/disconnect) and permissions via a BroadcastReceiver. My goal is to automatically grant permission to devices specified in an XML filter file upon connection, without explicitly calling requestPermission.
Here’s what I’ve set up:
In AndroidManifest.xml, I added a <intent-filter>
for USB_DEVICE_ATTACHED and specified a device_filter.xml file to match specific devices:
<uses-feature android:name="android.hardware.usb.host" />
<application ... >
<activity android:name=".MainActivity" android:exported="true">
<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>
</application>
My device_filter.xml contains vendor and product IDs for devices I want to handle:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<usb-device vendor-id="2965" product-id="6032" />
<usb-device vendor-id="10374" product-id="32807" />
</resources>
In my UsbCdc class, which handles the USB logic, I initialize a BroadcastReceiver that listens for ACTION_USB_PERMISSION and USB_DEVICE_ATTACHED:
public UsbCdc(Context context) {
mContext = context;
mUsbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
PendingIntent permissionIntent = PendingIntent.getBroadcast(mContext, 0,
new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
ContextCompat.registerReceiver(mContext, mUsbReceiver, filter, ContextCompat.RECEIVER_EXPORTED);
}
When I connect devices that match device_filter.xml, hasPermission(device) still returns false. In mUsbReceiver, if a device lacks permissions, I call mUsbManager.requestPermission(device, permissionIntent). However, ACTION_USB_PERMISSION is not triggered afterward, even though I have manually granted permissions.
Is automatic permission granting for devices in device_filter.xml dependent on the Android version or specific device settings? Why might ACTION_USB_PERMISSION not be triggered after calling requestPermission in the BroadcastReceiver?