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

如何将本地docx文件加载到Android WebView并解决ACTION_VIEW打开崩溃问题

问题解决方案

一、WebView无法加载本地docx文件问题

原生Android WebView本身不支持直接解析docx、pdf等Office格式文件,你直接传入本地docx的file://路径必然无法加载,可选择以下两种方案解决:

  • 方案1:将docx文件转成HTML格式后再传给WebView加载,可借助Apache POI等工具完成格式转换。
  • 方案2:集成第三方Office渲染组件(如腾讯TBS、开源的Docx4j相关渲染库),不使用原生WebView直接加载docx源文件。

另外你当前WebView配置存在错误:setAppCachePath(url) 该方法要求传入的是缓存文件夹路径,你错误传入了docx文件路径,直接删除该行错误配置即可。

二、ACTION_VIEW打开本地文件报错问题

FileUriExposedException是Android 7.0+的系统限制,必须使用FileProvider适配,你已经使用FileProvider仍报错是缺少了必要配置和权限授予,按以下步骤修复:

  1. 首先在AndroidManifest.xml中注册FileProvider,注意authorities属性值要和你代码中写的com.xyzapp.app.provider完全一致:
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="com.xyzapp.app.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
  1. 在res/xml目录下新建file_paths.xml文件,配置你要共享的文件路径(你的文件存在应用缓存目录,配置如下即可):
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="app_cache" path="." />
</paths>
  1. 修改跳转Intent代码,添加临时读取权限授予,否则第三方应用没有权限读取你分享的文件:
val pdfOpenintent = Intent(Intent.ACTION_VIEW)
val fileUri = FileProvider.getUriForFile(
    applicationContext,
    "com.xyzapp.app.provider",
    getpathhh
)
pdfOpenintent.setDataAndType(fileUri, "*/*")
// 给目标应用授予临时读取权限
pdfOpenintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
pdfOpenintent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
try {
    startActivity(pdfOpenintent)
} catch (e: ActivityNotFoundException) {
    // 可在此处提示用户未安装支持打开该类型文件的应用
}

内容的提问来源于stack exchange,提问作者IRON MAN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:15:10