How to obtain USB storage permissions on Android 6+?

2.1k views Asked by At

I've already obtained this permission:

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

save file to local is ok. But I cannot save to USB storage device.

How to obtain another write permission?

1

There are 1 answers

1
Martin Zeitler On

UsbManager.requestPermission() can be used with a BroadcastReceiver:

private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if(device != null) {
                      //call method to set up device communication
                    }
                } else {
                    Log.d(TAG, "permission denied for device " + device);
                }
            }
        }
    }

};

which has to be registered:

private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);   
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);

and then one can request the permission:

UsbDevice device;
mUsbManager.requestPermission(device, mPermissionIntent);

see USB Host for how to transfer - and how to releaseInterface() and close().