使用Intent打开文件(Android)

ajt*_*yng 2 java android android-intent

我想使用Intent打开任何文件(如果可能的话).我openFile(Uri file, String mimeType)定义了我的方法,并使用注册的BroadcastReceiver调用它.这是方法:

private void openFile(Uri file, String mimeType) {
    Intent openFile = new Intent(Intent.ACTION_VIEW);
    openFile.setData(file);
    try {
        context.startActivity(openFile);
    } catch (ActivityNotFoundException e) {
        Log.i(TAG, "Cannot open file.");
    }
}
Run Code Online (Sandbox Code Playgroud)

我目前没有使用mimeType,我只是想让它发挥作用.在具有Uri的.pdf上调用openFile方法的结果content://downloads/all_downloads/3980只是在pdf查看器中打开的空白pdf(mime类型可能正确解释),其中3980 downloadID显示为文件名.

没有PDF显示

我知道发生了什么,因为内容Uri无论出于何种原因都没有得到妥善解决.我得到了Uri,Uri localUri = downloadManager.getUriForDownloadedFile(downloadId);其中downloadId的长线是从那里回来的downloadManager.enqueue(request);

当我有内容类型Uri时如何打开文件?

Com*_*are 7

打电话addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION).否则,其他应用程序将无权使用其标识的内容Uri.

请注意,这仅适用于有权使用由此标识的内容Uri.