簡體   English   中英

使用Android Intent打開PDF文件

[英]Opening PDF file using Android intent

所以這是場景:

我正在從網絡下載PDF並將其保存在/0/Download/NSIT - Notices/"fileName".pdf

現在像這樣發送Intent:

private void openPDF(String fileName) {
    Log.d(TAG, "openPDF: called");
    Intent intent = new Intent(Intent.ACTION_VIEW);File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download", "NSIT - Notices");
    File myPDF = new File(Environment.getExternalStorageDirectory() + "/Download/NSIT - Notices", fileName + ".pdf");
    Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", myPDF);
    Log.d(TAG, "openPDF: intent with uri: " + uri);
    intent.setDataAndType(uri, "application/pdf");
    context.startActivity(Intent.createChooser(intent, "Open with..."));
}

現在,任何PDF閱讀器(Google Drive PDF閱讀器,System PDF Viewer)都在說

The File Does Not Exist

圖片: 在此處輸入圖片說明

Google坐着不做任何事(這就是為什么不包括其圖片)

Mainfest.xml

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

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

我在AsyncTask中在此處創建文件,但從該AsyncTask的postExecute打開

File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download", "NSIT - Notices");
            File myPDF = new File(myDir, params[1] + ".pdf");
            if (!myDir.exists())
                myDir.mkdirs();
            try {
                fileOutputStream = new FileOutputStream(myPDF);
                fileOutputStream.write(response.bodyAsBytes());
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "doInBackground: Download complete");

logcat的

在此處輸入圖片說明

以前它是拋出FileUriExposedException然后我使用此FileProvider 問題是我的應用下載的pdf文件已成功創建,我可以從任何文件管理器(現在為ES File Explorer)成功打開它,但無法從我的應用中打開它:(。我是FileProvider 。需要幫助!

PS:那也不是我的設備問題。 使用其他兩款具有不同ROM和API> = 23的手機進行了測試

請設置intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

它將把您文件的訪問權限授予其他提供商

請參閱文件提供程序的文檔

內容提供程序是否可供其他應用程序使用:

true:提供程序可用於其他應用程序。 任何應用程序都可以使用提供者的內容URI來訪問它,但要遵守為提供者指定的權限。

false:該提供程序不可用於其他應用程序。 訪問您的應用程序的提供程序。 只有具有與提供者相同的用戶ID(UID)的應用程序才可以訪問它。

嘗試更改android:exported =“ true”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM