安卓 - 没有找到处理意图的活动 {act = android.intent.action.VIEW} - 尝试打开PDF文件

13

我花了很多时间来寻找解决方案,但仍然找不到。

我正在尝试在我的安卓应用程序中打开PDF文件。

以下是我的代码:

try 
    {
        File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        Log.d("CheckingURI", uri.toString());
        intent.setDataAndType(uri, "application/pdf");
        startActivity(intent);
    } 
    catch (Exception e) 
    {
        Log.d("OpenPDFError", e.getMessage());
    }

Tomcat日志显示没有处理意图的活动

09-19 19:55:02.938: D/CheckingURI(30483): file:///mnt/sdcard/pdf/Read.pdf
09-19 19:55:02.948: D/OpenPDFError(30483): No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///mnt/sdcard/pdf/Read.pdf typ=application/pdf }

是否还有其他方法可以完成这个任务,或者我可以使用其他默认的PDF阅读器打开PDF文件吗?如果可以,应该如何操作?

更新: 主要问题是我没有在模拟器上安装PDF阅读器应用程序...

2个回答

7
试试这个替代方案:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/pdf/Read.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

注意:上述方法仅在您拥有预安装的PDF查看器时才有效。如果没有,则需要安装一个PDF查看器。


1
又出现了这个错误:找不到可处理的活动来处理意图 { act=android.intent.action.VIEW dat=file:///mnt/sdcard/pdf/Read.pdf typ=application/pdf flg=0x40000000 }。 - Russell Ghana
1
@RasoolGhana:也许您的设备或模拟器上没有安装 PDF 阅读器。请尝试安装 PDF 阅读器,然后重试。 - ChuongPham
谢谢,一直在寻找这个。对于“未找到活动...”错误的警告中的解释加1。 - user2693443

5

如果没有找到要启动的PDF文件,您只需向用户弹出某种错误消息即可(在错误对话框中,您可以让用户知道他需要一些PDF应用程序,并将他发送到Play商店),虽然我建议您使用这段代码而不是您正在使用的通用异常捕获器:

try {
    /* your code */
    ...
} catch (ActivityNotFoundException e) {
    e.printStackTrace();
}

或者您可以使用一些PDF库,比如像这个


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接