在我的 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 上,这不会返回匹配项,即使我有 Adobe 的 PDF 查看器也是如此。这个问题的答案android: open a pdf from my app using the built in pdf viewer提到 Adobe 可能没有任何公共(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/