Webview加载本地内部存储的HTML

2,417 阅读1分钟

需求:Webview 加载App内部路径的HTML

例:/data/user/0/packagename/files/web/index.html

问题:在Android N以后直接用webview 加载此路径是无效的。

解决:FileProvider

1.在AndroidManifest.xml中的application标签内 加入FileProvider 注:packagename 为你app的applicationid

    <provider
    android:name="androidx.core.content.FileProvider"
            android:authorities="packagename"
            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 file_paths.xml内的内容为:

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

注:路径不用xml中内容不同,如下: --> Context.getFilesDir() --> Context.getCacheDir() --> Environment.getExternalStorageDirectory() --> Context.getExternalFilesDir(String) --> Context.getExternalCacheDir() --> Context.getExternalMediaDirs()

3.获取URI后web加载

这里假设已经知道本地html文件路径为 /data/user/0/packagename/files/web/index.html

(给Android初学者提示:代码中路径不建议如此直接硬编码,建议用Context.getFilesDir() 、Environment.getExternalStorageDirectory()等方法获取 )

下面为Java代码

 File file = new File("/data/user/0/packagename/files/web/index.html");
 Uri uri = FileProvider.getUriForFile(this,"packagename",file); 

 mWebView.loadUrl(uri.toString());