Search code examples
javaandroidpermissionsuriandroid-contentprovider

How to re-request URI permission after it is revoked?


In my app, I'm opening files from phone storage. I have problems with keeping URI permissions working (not with the EXTERNAL_STORAGE one).

I first request opening the file as:

Intent mediaIntent = new Intent();
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    mediaIntent.setAction(Intent.ACTION_GET_CONTENT);
} else {
    mediaIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
    mediaIntent.addCategory(Intent.CATEGORY_OPENABLE);
}
mediaIntent.setType("audio/*");
startActivityForResult(mediaIntent, 1);

I am able to get the URI permission and take the "persistable" one as:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
        Uri uri = data.getData();
        int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getContentResolver().takePersistableUriPermission(uri, takeFlags);
        }
    }
}

I am then saving uri.toString() in SharedPreferences to be able to read the file afterwards. Closing the app or rebooting the phone work fine and I can still access the file. However, if I uninstall the app through adb uninstall and then try to access the file afterwards through:

String[] proj = { OpenableColumns.DISPLAY_NAME };
getApplicationContext().getContentResolver().query(uri, proj, null, null, null);

it turns out that I don't have access to the URI anymore (checkCallingUriPermission returns PackageManager.PERMISSION_DENIED).

Is there a way to ask ContentProvider to re-grant the URI permissions again after the previous one stopped working?

Calling:

ContentResolver cr = getApplicationContext().getContentResolver();
cr.takePersistableUriPermission(uri, takeFlags);

gives me

No persistable permission grants found for UID X and Uri Y

Solution

  • Is there a way to ask ContentProvider to re-grant the URI permissions again after the previous one stopped working?

    No, other than to go back through ACTION_OPEN_DOCUMENT again, as you did the first time.

    Uninstalling the app is designed to leave little behind. From the device's standpoint, your reinstalled app has nothing do to with the original installation of that app.

    Also, as Pawel hints at, there the question of where your reinstalled app is getting this Uri. In principle, while persisting a document Uri locally is OK (if you took the persistable permissions), transferring it off-device (backup, your server, etc.) may not work that well.