Persist URI permissions after App Restart

Viewed 324

Edit 1: Pinned shortcut means shortcut on home screen just like launcher icon of any app. Ex:

I have an app which pins PDF shortcuts to home screen. Currently users were facing an issue that after restarting the device, the pinned files do not open. I checked and found that URI permissions are revoked on OS restart. So I googled and found a couple of SO posts. But the issue didn't get resolved.

Here' what my code looks like:

            val file = File(path)
            val pdfIntent = Intent(Intent.ACTION_VIEW)

            val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                FileProvider.getUriForFile(this,
                        applicationContext.packageName + ".provider", file)
            } else {
                Uri.fromFile(file)
            }

 pdfIntent.setDataAndType(uri, "application/pdf")
            pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            pdfIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);


// Providing all PDF Readers access to the Uri.
            val resInfoList = packageManager.queryIntentActivities(pdfIntent, PackageManager.MATCH_DEFAULT_ONLY)
            for (resolveInfo in resInfoList) {
                val packageName: String = resolveInfo.activityInfo.packageName
                Log.d("Package", packageName)
                grantUriPermission(packageName, uri, Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
            }
            grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

...

...

          shortcutManager.requestPinShortcut(shortcut, null)

When I restart the device and open the shortcut (which opens in Android's default PDF Viewer), I get the following log when I debug:

com.google.android.apps.docs E/ContentUriOpener: content:com.parassidhu.pdfpin.provider: java.lang.SecurityException: Permission Denial: opening provider androidx.core.content.FileProvider from ProcessRecord{97a06 5716:com.google.android.apps.docs/u0a129} (pid=5716, uid=10129) that is not exported from UID 10138

By seeing other SO posts, I tried implementing grantUriPermission() as shown above but no benefit. I also tried contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) and it didn't work but I doubt I implemented it incorrectly.

This issue as per reports is happening on Oreo+ (including oreo). I tested it on Android 9 emulator. This code works perfectly until user hasn't restarted the app.

0 Answers
Related