【问题标题】:How to open a pdf with intent in Android Q如何在Android Q中打开带有意图的pdf
【发布时间】:2021-07-11 06:54:41
【问题描述】:

我编写了一个代码,可以打开像 pdf 这样的文件。为此,我使用了如下意图:

public void openFile(Context context, File file) {
    String typeFile = "application/pdf";

    if (file.exists()) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), typeFile);
        PackageManager pm = context.getPackageManager();
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.setType(typeFile);
        Intent openInChooser = Intent.createChooser(intent, "Choose");
        List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
        if (resInfo.size() > 0) {
            try {
                context.startActivity(openInChooser);
            } catch (Throwable throwable) {
                Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show();
                // PDF apps are not installed
            }
        } else {
            Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show();
        }
    }
}

我的问题是,当我在 Android 10 和 11 上运行此代码时,else 中的 Toast 会执行,但在旧版本中这些代码可以正常工作。

那么我应该怎么做才能在 Android 10 和 11 中打开文件呢?

【问题讨论】:

    标签: android file android-intent


    【解决方案1】:

    您的应用应该在 Android 7.0+ 上崩溃,并带有 FileUriExposedException。你需要摆脱Uri.fromFile()switch to FileProvider

    另外,你可以摆脱queryIntentActivities()。你不需要它,部分是因为应该总是有一个选择器,部分是因为如果出于某种奇怪的原因没有选择器,你有try/catch 块来捕获ActivityNotFoundException。如果您使用queryIntentActivities() 的原因是为了避免选择器为空,请停止创建选择器——如果合适,操作系统会自动添加一个。或者,对于 Android 11+,您需要处理包可见性规则才能调用 queryIntentActivities()。请参阅thisthis 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 2012-05-15
      • 1970-01-01
      • 2020-10-28
      • 2021-02-17
      相关资源
      最近更新 更多