You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio生成PDF后无法自动打开的技术问题咨询

问题分析与解决方案

你的代码在Android 7.0及以上系统会因为FileUriExposedException导致Intent无法正常启动,同时没有检查是否有应用能处理PDF打开请求,这就是生成PDF后无反应的核心原因。以下是修复步骤:

1. 配置FileProvider(解决Android 7.0+文件共享限制)

在AndroidManifest.xml的application标签内添加FileProvider配置:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

2. 创建文件路径配置文件

在res/xml目录下新建file_paths.xml(如果没有xml目录请手动创建),内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="downloads" path="Download/" />
</paths>

3. 修复showPdf()方法

替换原方法为以下代码,解决Uri权限问题并增加错误提示:

public void showPdf() {
    try {
        File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        String fileName = "document.pdf";
        File file = new File(downloadsDir, fileName);

        // 先检查文件是否存在
        if (!file.exists()) {
            Toast.makeText(this, "生成的PDF文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        Uri pdfUri;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // Android 7.0+使用FileProvider生成安全Uri
            pdfUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
            // 授予临时读取权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            pdfUri = Uri.fromFile(file);
        }

        intent.setDataAndType(pdfUri, "application/pdf");
        // 检查是否有应用能处理这个Intent
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, "未找到可打开PDF的应用,请先安装PDF阅读器", Toast.LENGTH_SHORT).show();
        }
        
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this, "打开PDF失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

4. 适配Android 13+权限(可选)

如果你的应用目标SDK是33及以上,需要在AndroidManifest.xml中添加读取文档的权限:

<uses-permission android:name="android.permission.READ_MEDIA_DOCUMENTS" />

内容的提问来源于stack exchange,提问作者Leonardo Miguel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 11:43:22