Unable To Open The Pdf In Android
I am new in android and working on one android project in which I have to display a chosen pdf from the device either from internal storage(Priority) or from external Storage. I am
Solution 1:
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"
<providerandroid:authorities="androidx.core.content.FileProvider"android:exported="false"android:grantUriPermissions="true"android:name=".provider.GenericFileProvider"><meta-dataandroid: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"?><pathsxmlns:android="http://schemas.android.com/apk/res/android"><external-pathname="external_files"path="."/></paths>
And use this method
publicstaticvoid 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.
Solution 2:
Follow below steps:
Step - 1: Create provider_paths.xml
in your xml
directory
<?xml version="1.0" encoding="utf-8"?><pathsxmlns:android="http://schemas.android.com/apk/res/android"><external-pathname="external_files"path="."/></paths>
Step - 2: Add FileProvider
in your AndroidManifest.xml
file
<providerandroid:name="androidx.core.content.FileProvider"android:authorities="${applicationId}.provider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/provider_paths" /></provider>
Step - 3: Since your file is in internal/external storage use getExternalStorageDirectory()
Filefile=newFile(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uripath= FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
Intenttarget=newIntent(Intent.ACTION_VIEW);
target.setDataAndType(path, "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intentintent= Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "Please install some pdf viewer app", Toast.LENGTH_LONG).show();
}
Post a Comment for "Unable To Open The Pdf In Android"