Android – android.os.FileUriExposedException and all about it

If you as an Android developer working on an App and which is calling implicit Intents using a Uri, you will encounter FileUriExposedException on API 24+.

This exception starts occurring if your app will run in Android Nougat due to the fact that using file:// Uri’s are discouraged because it makes some assumptions about the destination app. For one thing, we assume that the destination app has READ_EXTERNAL_PERMISSION which may not be the case. If the destination app does not have the permission, this may result in unexpected behaviour which ends up with a crash.

android.os.fileuriexposedexception

Lets see how we can make it work –

In Android Nougat we have to use FileProvider to get rid of FileUriExposedException. Which can be done in 3 simple steps

Step 1

First of all, add the provider tag inside the application tag within AndroidManifest.xml

<application>
<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>

...
</application>

Read also –

Step 2

Once the provider get added in AndroidManifest.xml, next we need to create an xml file res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

 Step 3

Now comes the final step that is the code change

//Old approach
 private void callIntent(File file) {
        if (file.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);            
            intent.setDataAndType(Uri.fromFile(file), getString(R.string.mimetype));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        }
    }


//New Approach
 private void callIntent(File file) {
        if (file.exists()) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri apkURI = FileProvider.getUriForFile(
                    this, app.getPackageName() + ".provider", file);
            intent.setDataAndType(apkURI, getString(R.string.mimetype));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        }
    }

And that’s it, you are done. If you like this, do not forget to share it with fellow Android developers

Keep on reading other articles to build great apps.

 

Happy coding!!!

Leave a Reply

Your email address will not be published. Required fields are marked *