In Android N, Opening a file from the SD card is different. When targeting Android N, file:// URIs are not allowed anymore. We should use content:// URIs instead.

FileProvider class is used to give access to the particular file or folder to make them accessible for other apps.

FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.

Step 1 : Defining a FileProvider in Manifest

<manifest>

<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>
</manifest>

Step 2 : Create xml folder in res folder and create xml file name as provider_paths and wirte following code in it.

<?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 : Retrieving the Content URI for a File

File file = new File(Environment.getExternalStorageDirectory(), “MyPhoto.jpg”);
Uri uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + “.provider”, file);

 

You may also like

Leave a Reply