Android Camera crash when using an Uri from FileProvider

Problem

There is THIS great article which explains where the problem is with using a file Uri from a FileProvider. When you pass a file Uri to the camera app it crashes with the awful exception from below.

Here is the exception you might get:

java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{423c0ad0 13416:com.google.android.gallery3d/u0a10020} (pid=13416, uid=10020) that is not exported from uid 10079

Solution

You must grant permissions to read and write to the Uri. Use the grantUriPermission and revokeUriPermission methods on the Context object.

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> resolvedIntentActivities = context.getPackageManager()
                                                    .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolvedIntentInfo : resolvedIntentActivities) {
    String packageName = resolvedIntentInfo.activityInfo.packageName;

    context.grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}

When you are done relying on the Uri just delete the permission:

context.revokeUriPermissionfileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

You may also like...