Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 enclosing the used code below.

private void openLocalPDF(File pdffile) {

       File file = new File(Environment.getExternalStorageDirectory(), pdffile.getName());
        Uri path = PdfFileProvider.getUriForFile(activity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
        Intent target = new Intent(Intent.ACTION_VIEW);
        target.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        target.setDataAndType(path, "application/pdf");
        Intent intent = Intent.createChooser(target, "Open File");
        try {
                activity.startActivity(intent);
            } catch (ActivityNotFoundException e) {
            Toast.makeText(getActivity(), "Please install some pdf viewer app", Toast.LENGTH_LONG).show();
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
290 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...