【问题标题】:How to open Pdf viewer via Intent in Android如何在 Android 中通过 Intent 打开 Pdf 查看器
【发布时间】:2019-01-10 19:32:52
【问题描述】:

VB.NET / SQL Developer 是 Android 开发的新手,但概念正在普及。

我已经成功实现了 DownloadManager 以将 PDF 从 URI 下载到 DIRECTORY_DOWNLOADS 文件夹,但是当我尝试使用 Intent 打开时,我只会提示 Dropbox 和 Word 而不是普通应用程序.. 代码:

Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(Uri.parse(DIRECTORY_DOWNLOADS + File.separator + "WinLib" + File.separator + "WinLib.pdf"), "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);


try{
    startActivity(pdfIntent);
}catch(ActivityNotFoundException e) {
    Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}

当我单击“下载”文件夹中的文件时,我会看到 Drive PDF Viewer 和 OneDrive PDF Viewer 的选项。

正如我所说,我是 Android/Java 的菜鸟,所以请不要苛刻,但我们将不胜感激,因为 Google 已经在这方面干涸了!

提前致谢

戴夫

解决方案

用户“Shine”将我指向“Martin Himmel”post 的方向。

我必须将 intent.setData 和 intent.setType 结合起来,因为当我使用 setType 时,它​​会将数据重置为 null,因此找不到文件。

完成后我收到了错误:

android.os.FileUriExposedException: file:///storage/emulated/0/Download/WinLib/WinLib.pdf exposed beyond app through ClipData.Item.getUri()

解决方案在“eranda.del”的post中找到。

所以我的最终代码如下所示:

public String get_mime_type(String url) {
    String ext = MimeTypeMap.getFileExtensionFromUrl(url);
    String mime = null;
    if (ext != null) {
        mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
    }
    return mime;
}

public void open_file(String filename) {
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS), filename);

    Uri uri = Uri.fromFile(file);
    String mime = get_mime_type(uri.toString());

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, mime);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    this.startActivity(Intent.createChooser(intent, "Open file with"));
}

感谢 Shine 和其他帮助我完成这项任务的贡献者,非常感谢!

戴夫

【问题讨论】:

  • 使用FileProvider 使文件可用,看看这是否会增加您可以支持的应用范围。
  • 感谢 CommonsWare 的指点,非常感谢。

标签: android android-intent


【解决方案1】:

您确定Uri.parse(DIRECTORY_DOWNLOADS + File.separator + "WinLib" + File.separator + "WinLib.pdf") 参数吗?我会尝试使用类似于here 描述的方法来尝试FileProvider.getUriForFile()。通过这种方式,您可以轻松地检查通过以下方式传递给意图的 pdf 的 Uri 和 mime 类型:

String mime = getContentResolver().getType(uri);

我还认为在您的情况下需要 .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) 调用,以便授予外部查看 Intent 的读取权限。

【讨论】:

  • 感谢您的帮助 Shine,让我完成了 95% 的工作。我将添加我需要进行的更改的详细信息(或至少尝试),以使我达到 100%。
猜你喜欢
  • 1970-01-01
  • 2012-05-18
  • 2012-09-17
  • 2022-01-22
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 2012-08-05
  • 2020-10-28
相关资源
最近更新 更多