Search code examples
androidandroid-4.4-kitkat

IllegalArgumentException in grantUriPermission on API level 19


The following line of code

context.getApplicationContext().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);

raises this exception when running on devices with API level 19 (KitKat), but not on later versions:

java.lang.IllegalArgumentException: Requested flags 0x40, but only 0x3 are allowed
  at android.os.Parcel.readException(Parcel.java:1476)
  at android.os.Parcel.readException(Parcel.java:1426)
  at android.app.ActivityManagerProxy.grantUriPermission(ActivityManagerNative.java:3461)
  at android.app.ContextImpl.grantUriPermission(ContextImpl.java:1732)
  at android.content.ContextWrapper.grantUriPermission(ContextWrapper.java:577)

Why is that so?


Solution

  • I believe this is caused by a change added in KitKat which should have fixed content access but they broke it.

    You would need to run a check using Build.VERSION.SDK_INT < 19 (ie. pre-KitKat)

    if(Build.VERSION.SDK_INT < 19) {
        context.getApplicationContext().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
    } else {
        takePersistableUriPermission(packageName, uri);
    } 
    

    http://developer.android.com/reference/android/content/ContentResolver.html#takePersistableUriPermission