Issue with getting USB device permission from BroadcastReceiver?

375 Views Asked by At

I am using below code to get usb access permission from user when its detected, but it never get detected in android 11. Any help would be highly appreciated

public final String ACTION_USB_PERMISSION = "com.domain.ftd.USB_PERMISSION";

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
        @Override
        public void onReceive(Context context, Intent intent) {


            if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
                boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
                Log.e("usb started","really");
                if (granted) {
                     //DO SOMETHING 
                }
         }

     @Override
        protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
             usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
            IntentFilter filter = new IntentFilter();
            filter.addAction(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            registerReceiver(broadcastReceiver, filter);
    
    
    
    
        }
                        

     
    
1

There are 1 best solutions below

0
On

You need to register the broadcast receiver and call the requestPermission() method to display a dialog that asks users for permission to connect to the device, please refer the official doc and search for keyword "requestPermission()"

permissionIntent = PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_MUTABLE)
lateinit var device: UsbDevice
        ...
usbManager.requestPermission(device, permissionIntent)