我想从 url 下载 PDF,如果未检测到 PDF 查看器,我还想触发 catch
短语。
这是我的代码:
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(materialPdfUrl)));
} catch (ActivityNotFoundException e) {
openDialog(getString(R.string.error),
getString(R.string.no_pdf_reader));
}
现在的问题是 ActivityNotFoundException 永远不会被触发,因为它总是下载 PDF,即使周围没有 PDF 查看器。你建议我怎么做?
编辑: 这是我的旧代码:
Intent pdfIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(materialPdfUrl));
pdfIntent.setType("application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(pdfIntent);
最佳答案
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(materialPdfUrl)));
正在启动一个 Implicit Intent
,因此不会抛出 ActivityNotFoundException
。
如果您阅读此 http://developer.android.com/guide/components/intents-filters.html#ccases
Consider, for example, what the browser application does when the user follows a link on a web page. It first tries to display the data (as it could if the link was to an HTML page). If it can't display the data, it puts together an implicit intent with the scheme and data type and tries to start an activity that can do the job. If there are no takers, it asks the download manager to download the data. That puts it under the control of a content provider, so a potentially larger pool of activities (those with filters that just name a data type) can respond.
因此,如果未找到 PDF 查看器,Android 下载管理器将尝试下载文件(而不是抛出异常)。
如果您想查看 pdf 或被告知您无法查看(而不是下载),那么您将需要使用 PackageManager
手动查询系统,以确定应用程序是否会响应您的 Intent ,而不仅仅是发射和遗忘。
仅供引用 ActivityNotFoundException
将因 Explicit Intent's
类似以下内容而被抛出:
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.facebook","NewsFeedActivity.java"));
startActivity(intent);```
关于android - 未触发 ActivityNotFoundException 打开下载的 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20652928/