Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

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 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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...