Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

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



...

Read also –

  • Loading images from SD Card in a ListView
  • Styling custom views in Android

Step 2

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

 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!!!

The post Android – android.os.FileUriExposedException and all about it appeared first on { OneTouchCode.com }.



This post first appeared on Onetouchcode, please read the originial post: here

Share the post

Android – android.os.FileUriExposedException and all about it

×

Subscribe to Onetouchcode

Get updates delivered right to your inbox!

Thank you for your subscription

×