打开下载的PDF文件

时间:2018-05-25 09:57:34

标签: android android-intent android-fileprovider

我尝试使用FileProvider通过隐式意图打开下载的pdf文件。

我使用DownloadManager从远程服务器下载pdf文件,它工作正常。哪个存放在它的目的地。

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadURL));
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
    request.setAllowedOverRoaming(false);
    request.setTitle(mFilename);
    request.setDescription("Downloading...");
    request.setVisibleInDownloadsUi(true);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/FOLDER_NAME/" + mFilename);

完成下载后,我想打开它。

public void OpenPdfFile(){
    File sharedFile = new File(Environment.DIRECTORY_DOWNLOADS, "/FOLDER_NAME/" + mFilename);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri uri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID+ ".provider", sharedFile);
    intent.setDataAndType(uri, "application/pdf");

    PackageManager pm = mContext.getPackageManager();
    if (intent.resolveActivity(pm) != null) {
        mContext.startActivity(intent);
    }
}
清单文件中的

<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_paths.xml一样

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external-path" path="." />
</paths>

它让我犯了这个错误

java.lang.IllegalArgumentException:无法找到包含/Download/FOLDER_NAME/demo_presentationfile.PDF

的已配置根目录

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

  

文件sharedFile =新文件(Environment.DIRECTORY_DOWNLOADS,“/ FOLDER_NAME /”+ mFilename);

评估为不可能的文件系统路径。如果您检查sharedFile.getAbsolutePath()的值,您会看到。

更改为:

File sharedFile = new File(Environment.getExternalStoragePublicDirectory( 
        Environment.DIRECTORY_DOWNLOADS), "FOLDER_NAME/" + mFilename);
相关问题