Use FileProvider, here is the sample code:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider" ,file);
intent.setDataAndType(data, "/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
Also you need to include FileProvider in the manifest file
Inside the application tag just do like this:
<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>
Also create a xml folder in the resource directory and create a file provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="PATH here" path=""/>
</paths>
If `targetSdkVersion` is higher than **24**, then [FileProvider][1] is used to grant access.
Create an xml file(Path: 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>
<br>
Add a **Provider** in **[AndroidManifest.xml][2]**
<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>
and **replace**
Uri uri = Uri.fromFile(fileImagePath);
to
Uri uri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider",fileImagePath);
and you are good to go. Hope it helps.
[1]: https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjiyKWypuDVAhVIso8KHcA2BvIQFgglMAA&url=https%3A%2F%2Fdeveloper.android.com%2Freference%2Fandroid%2Fsupport%2Fv4%2Fcontent%2FFileProvider.html&usg=AFQjCNEBbyss3j2b0k_XQncN1I9vLhrlGQ
[2]: https://developer.android.com/guide/topics/manifest/manifest-intro.html