6

I'm using the Storage Access Framework to get write access on the sd-card (API >= 21).

It works fine on most devices, but some like the Galaxy S7 (Edge, API 23) throw an SecurityException when calling takePersistableUriPermission().

Caused by: java.lang.SecurityException: No persistable permission grants found for UID 10150 and Uri 0 @ content://com.android.externalstorage.documents/tree/70CD-6B92

code:

//call the SAF
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                        startActivityForResult(intent, Config.REQUEST_SAF);

//Persist permissions
int flags = resultData.getFlags();
flags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

this.getContentResolver().takePersistableUriPermission(treeUri, flags); //throws exception

The exception doesn't occur on all S7 devices. I've tested the code successfully on 2 devices but this one throws the SecurityException.

May i have to add some flags to the call of the SAF?

intent.addFlags(
Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

Any help is appreciated.

Farasy
  • 304
  • 2
  • 8
  • Did you ever resolve this issue? – Daniel Kotin Sep 08 '16 at 13:26
  • Not yet. Seems like nobody knows where it comes from. – Farasy Sep 10 '16 at 08:50
  • I am facing the same issue on Samsung devices. @Farasy Did you find any solution of this problem ? I posted the question here - https://stackoverflow.com/questions/74369880/securityexception-using-storage-access-framework-in-some-devices – Smeet Nov 09 '22 at 04:54
  • @Smeet Unfortunately no persistent solution found. However, this is a non common issue and on certain devices only. – Farasy Nov 17 '22 at 13:18

2 Answers2

6

I tried adding grantUriPermission before takePersistableUriPermission and it's the only thing that worked for me to avoid the error thrown by the system SecurityException:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
    getContext().grantUriPermission(getContext().getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
} catch (IllegalArgumentException e) {
    // on Kitkat api only 0x3 is allowed (FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION)
    getContext().grantUriPermission(getContext().getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
} catch (SecurityException e) {
    Log.e("", e.toString());
}

try {
    int takeFlags = intent.getFlags();
    takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    getContext().getContentResolver().takePersistableUriPermission(uri, takeFlags);
} catch (SecurityException e) {
    Log.e("", e.toString());
}
}
box
  • 4,450
  • 2
  • 38
  • 38
0

try adding this flag:

intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
Mina Wissa
  • 10,923
  • 13
  • 90
  • 158