android - 在 Android 中显示 PDF

标签 android pdf

在我的 onCreate() 中我做了这个检查:

//
// check if we have a PDF viewer, else bad things happen
//
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/pdf");

List<ResolveInfo> intents = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

if (intents == null || intents.size() == 0) {
       // display message then...
       finish();
}

在我的 HTC Desire 上,这不会返回匹配项,即使我有 Adob​​e 的 PDF 查看器也是如此。这个问题的答案android: open a pdf from my app using the built in pdf viewer提到 Adob​​e 可能没有任何公共(public) Intents,因此上述检查显然不会返回任何内容。

任何人都可以验证您是否应该能够从 Intent 启动 Acrobat,或者是否有其他方法或 PDF 查看器可供使用。

实际用例是使用如下代码下载发票副本并将其存储在本地存储中:

 URL url = new URL(data);
 InputStream myInput = url.openConnection().getInputStream();

 FileOutputStream fos = openFileOutput(fname, Context.MODE_WORLD_READABLE);

 // transfer bytes from the input file to the output file
 byte[] buffer = new byte[8192];
 int length;
 while ((length = myInput.read(buffer)) > 0) {
    fos.write(buffer, 0, length);
    progressDialog.setProgress(i++);
 }
 fos.close();

然后显示

// read from disk, and call intent
openFileInput(fname);   // will throw FileNotFoundException

File dir = getFilesDir();       // where files are stored
File file = new File(dir, fname);   // new file with our name

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.setType("application/pdf");

startActivity(intent);

最佳答案

将手机连接到 PC,启动 Eclipse 并打开 LogCat。然后用浏览器下载一个PDF文件并打开。您应该会看到这样一行(我使用的是 HTC desire):

09-14 17:45:58.152: INFO/ActivityManager(79): 启动 Activity :Intent { act=android.intent.action.VIEW dat=file:///sdcard/download/FILENAME.pdf typ=application/pdf flg=0x4000000 cmp=com.htc.pdfreader/.ActPDFReader

尝试使用组件信息明确 Intent 。文档在这里说:

> component -- Specifies an explicit name of a component class to use for the intent. Normally this is determined by looking at the other information in the intent (the action, data/type, and categories) and matching that with a component that can handle it. If this attribute is set then none of the evaluation is performed, and this component is used exactly as is. By specifying this attribute, all of the other Intent attributes become optional.

缺点是您将绑定(bind)到 htc 阅读器。但是您可以先尝试隐式 Intent ,如果失败则尝试显式 Intent 作为后备。

关于android - 在 Android 中显示 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3706370/

相关文章:

java - Android开发环境难点

c# - PDFsharp 1.50 测试版 3 : Empty owner password error when adding password to PDF

pdf - 什么是 "Tagged PDF"?

r - ggplot pdf中的嵌入式字体

linux - 是否可以为 perl 模块导入 truetype 字体?

android - 隐式广播接收器的替代品?

android - 包装的 android-app 在恢复 "no current context"时崩溃

android - 应用程序启动时看到的是白屏和操作栏,而不是黑屏

ios - uiwebview显示pdf文档的安全问题

Android ndk-build 选项用于删除符号表信息