Introduction
In this article, we will learn how to handle “android.os.FileUriExposedException” if we have an app that shares files with other apps using a URI on API 24+. As of Android N, we need to use
FileProvider API.
Creating a New Project with Android Studio
- Open Android Studio and select "Create new project".
- Name the project as per your wish and select your activity template.
- Click the “Finish” button to create the new project in Android Studio.
Steps to change File Provider API
To replace “file://” to “uri://”, we should follow these three steps.
Step 1 - Change Manifest Entry
- Add the <provider /> tag with FileProvider inside the <application /> tag, as shown in the below code.
- <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>
- Here, provider_paths is an XML file which is used to specify the path to be accessed via File Provider API for Android N and above devices.
- Don't forget to add the following permission in your manifest file.
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Step 2 - Create an XML file in res/xml/provider_paths.xml
- Create a new XML folder in res. Then, create an XML file and name it as provider_paths.xml.
- Add the following code to the file.
- <?xml version="1.0" encoding="utf-8"?>
- <paths>
- <external-path name="external_files" path="."/>
- </paths>
Step 3 - Create an intent to open file for Android N
- Change the normal URI method for Android N.
- File file = new File("File Path");
- Uri.fromFile(file)
To
- File file = new File("File Path");
- Uri apkURI = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", file);
- Then, grant the Read URI permission for Android N & above devices. The following code shows how to use the "Open file" Intent for Android N devices and before Android N devices.
- File file = new File("File Path");
- Intent intent = new Intent(Intent.ACTION_VIEW);
- intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
- Uri apkURI = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", file);
- intent.setDataAndType(apkURI, "image/jpg");
- intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
- } else {
- intent.setDataAndType(Uri.fromFile(file), "image/jpg");
- }
- startActivity(intent);
Reference
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
If you have any doubts or need any help, contact me.
Next Article
It is the first part for accessing file URI for Android N & above devices. In the next article, we will learn how to access the Camera API for Android N and above devices.