2

I'm using the following code to get access to a USB Device on Android.

private final String ACTION_USB_PERMISSION = "com.myapp.USB_PERMISSION";

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            log(Log.INFO, TAG, "on intent received >" + intent.getAction());
            if (ACTION_USB_PERMISSION.equals(action)) {
                log(Log.INFO, TAG, "On receive for usb permission");
                synchronized (this) {
                    UsbDevice device = (UsbDevice) intent
                            .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(
                            UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        log(Log.INFO, TAG, "Usb connection permission accepted");
                        //permission granted
                        if (device != null) {
                            log(Log.INFO, TAG, "usb connection devices");

                        } else {
                            log(Log.INFO, TAG, "No usb connection devices");
                        }
                    } else {
                        log(Log.INFO, TAG, "Usb connection permission denied");
                        UIHelper.showToastLong("Usb permission is needed to use the USB Device", activity);
                    }
                }
            }
        }
};

UsbManager usbManager = (UsbManager) activity.getSystemService(Context.USB_SERVICE);
PendingIntent permissionIntent = PendingIntent.getBroadcast(activity, 0,
        new Intent(ACTION_USB_PERMISSION), 0);
activity.registerReceiver(mUsbReceiver, new IntentFilter(ACTION_USB_PERMISSION));
while (true) {
    if (!usbManager.hasPermission(usbDevice)) {
        usbManager.requestPermission(usbDevice, permissionIntent);
    } else {
        break;
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

This works fine on Android 10. But doesn't work on Android 7.1.2

The Permission Request Pop Up keeps showing up over and over again and the mUsbReceiver is never triggered. What's the cause for this?

Nimila Hiranya
  • 4,842
  • 10
  • 35
  • 52

1 Answers1

0
  • I think you should not use loop here. Try using the usbManager.requestPermission(usbDevice, permissionIntent); in the case where UsbManager.EXTRA_PERMISSION_GRANTED is returned false.
  • And also unregister the receiver in onDestroy() if you are registering it in onCreate() and unregister in onPause() if registered in onResume().