You should create a Provider Class
and extends
with FileProvider
. and register in manifest
and also if you using targetSdkVersion 29
add this permission AndroidManifest.xml
android:requestLegacyExternalStorage="true"
<provider
android:authorities="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true"
android:name=".provider.GenericFileProvider">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
And add a provider_paths.xml
file in xml
folder :
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
And use this method
public static void openFile(Context context, File file) {
Uri path = GenericFileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(path, "application/pdf);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
}
}
I hope this will help you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…