I am having trouble opening file inside external storage with Android N.
File path
file:///storage/emulated/0/Download/SamplePDFFile_5mb.pdf
Initial implementation Perfectly work on Android version lower than 7
File file = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SamplePDFFile_5mb.pdf");
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
The same implementation doesn't work on 7 with below exception.
android.os.FileUriExposedException
So i found out similar questions and follow this in order to fix new android security feature for app targeting to 24 or higher.
New implementation
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SamplePDFFile_5mb.pdf");
//old way
//Uri uri = Uri.fromFile(file);
//new way
Uri uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
provider_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
AndroidManifest.xml
<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>
Even after adding required tag in Android Manifest, provider_paths.xml and FileProvider, i am not able to open the file. Opening activity close on itself.no error or messages in logcat.
After N need to check runtime permission .
Maybe late, but I solved it by adding an temporary permission to the intent, by doing the following:
This was helpful: Granting Content Provider URI Permissions