Search code examples
androidandroid-intenturiintentfilterandroid-contentresolver

Receiver app - handle permission for intent filter URI


I'm so confused with the whole Fileprovider thing Android has. All day I spend watching videos and looking at other posts... I hope somebody can quickly help me.

I have an app that processes images/PDF etc... and uploads them to a server. For this I implemented an intent filter on my entry activity.

   <intent-filter>
            <action android:name="android.intent.action.SEND_MULTIPLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="image/*" />
        </intent-filter>

That activity gets the intent, but sends its data to another activity.

   (intent.getParcelableArrayListExtra<Parcelable>(Intent.EXTRA_STREAM) as? ArrayList<Uri>)?.let {
        activity.startActivity(MainActivity.newInstance(activity, it))
    }

and

 public static Intent newInstance(@NonNull Context context, @NonNull ArrayList<Uri> images) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.putParcelableArrayListExtra(INTENT_EXTRA_IMAGES, images);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    return intent;
}

That activity tries to read the Uri with the contentresolver

val openInputStream = context.contentResolver?.openInputStream(originalFileUri)

But when doing so it will crash - sometimes...

If I shared a photo from the gallery app it all works fine. If I share a photo from the downloads folder then I get

java.lang.SecurityException: Permission Denial: opening provider com.android.providers.downloads.DownloadStorageProvider from ProcessRecord{40bd561 8082:APPNAME/u0a749} (pid=8082, uid=10749) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

If I share a photo from whatsapp to my app I get

java.lang.SecurityException: Permission Denial: opening provider com.whatsapp.contentprovider.MediaProvider from ProcessRecord{a684e0e 6544:APPNAME/u0a749} (pid=6544, uid=10749) that is not exported from UID 10140

I'm clueless why this is...


Solution

  • That activity gets the intent, but sends its data to another activity.

    That's not really ideal.

    But, if you have to do it, add FLAG_GRANT_READ_URI_PERMISSION (and, if needed, FLAG_GRANT_WRITE_URI_PERMISSION) to the Intent that you use to start MainActivity. Otherwise, MainActivity may not have permission to work with the content.