Android 使用webView加载html页面

1、首先在布局xml里面指定WebView根节点

复制代码
  <WebView
        android:id="@+id/myWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

2、在.java的onCreate()里使用

复制代码
@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three);

        //1. asset目录下的index.html文件
        String filePath = "file:///android_asset/html/index.html";
        //2.本地内存中的index.html文件
        // 获取文件夹路径
        String htmlPath = getExternalFilesDir("html").getPath();
        File htmlFile = new File(htmlPath);
        // 判断是否存在,不存在则创建
        if (htmlFile.exists()){
            htmlPath =  htmlFile.getPath()+File.separator+"index.html";
        }else {
            htmlFile.mkdirs();
            htmlPath =  htmlFile.getPath()+File.separator+"index.html";
        }
        // 地址
        String localFilePath = "file:///"+htmlPath;
        //3.指定的URL的html文件
        /**
         * 若是不显示,在AndroidManifest.xml中添加android:usesCleartextTraffic="true"
         * 并且设置网络权限
         */
        String urlPath = "https://www.baidu.com/";


        myWebView = findViewById(R.id.myWebView);
        WebSettings myWebSettings = myWebView.getSettings();
        // webView解决加载html页面空白问题
        myWebSettings.setJavaScriptEnabled(true);// 设置支持javascript
        myWebSettings.setUseWideViewPort(true);//将图片调整到适合webView大小
        myWebSettings.setLoadWithOverviewMode(true);//缩放至屏幕大小
        myWebSettings.setDomStorageEnabled(true);//设置DOM缓存,当H5网页使用localstorage时一定要设置
        myWebSettings.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);// 设置去缓存,防止加载的是上一次数据
        myWebSettings.setDatabaseEnabled(true);

        // 解决加载本地内存中报错 err_access_denied
        myWebSettings.setAllowFileAccess(true);
        myWebSettings.setAllowContentAccess(true);

        // 解决webView报错 Loading local files from file:// urls is not possible due browser security restrictions
        /**
        *  设置是否允许运行在一个file schema URL环境下的JavaScript访问来自其他任何来源的内容,
         * 包括其他file schema URLs。
         * 通过此API可以设置是否允许通过file url加载的Javascript可以访问其他的源,
         * 包括其他的文件和http,https等其他的源。与上面的类似,实现一个就可以。
         * webSetting.setAllowUniversalAccessFromFileURLs(true);
        * */
        myWebSettings.setAllowUniversalAccessFromFileURLs(true);
        /**
         * 设置是否允许运行在一个file schema URL环境下的JavaScript访问来自其他任何来源的内容,
         * 包括其他file schema URLs。
         * 通过此API可以设置是否允许通过file url加载的Javascript可以访问其他的源,
         * 包括其他的文件和http,https等其他的源。与上面的类似,实现一个就可以。
         */
        //myWebSettings.setAllowUniversalAccessFromFileURLs(true);


        //加载html
        if (filePath != null) {
            myWebView.loadUrl(urlPath);
        }


    }

3、创建assets目录(与res目录同一级别)

4、将要访问的*.html页面放置到assets目录即可

5、使用X5内核 腾讯SDK

地址: 腾讯浏览服务

下载sdk:腾讯浏览服务-SDK下载

放置在libs文件夹,引用

AS高版本:

复制代码
implementation(fileTree("libs"))

AS低版本:

复制代码
android{
    ...
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}
 

dependencies{
    ...
    compile files('libs/tbs_sdk_thirdapp_v4.3.0.386_44286_sharewithdownloadwithfile_withoutGame_obfs_20230210_114429.jar')
}

AndroidManifest.xml配置权限

复制代码
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 <application
        android:name=".activity.app.MyAplication"
        ***
/application>

Application.java设置初始化

复制代码
package com.example.yuanzhoulv.activity.app;;
import android.app.Application;
import com.tencent.smtt.sdk.QbSdk;

public class MyAplication extends Application {

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        //搜集本地tbs内核信息并上报服务器,服务器返回结果决定使用哪个内核。

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调,为true表示x5内核加载成功,否则表示x5内核加载失败,会自动切换到系统内核。
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);
    }


}

使用:

*.xml

复制代码
  <com.tencent.smtt.sdk.WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

*.java

复制代码
        //1. asset目录下的index.html文件
        String filePath = "file:///android_asset/html/index.html";
        //2.本地内存中的index.html文件
        // 获取文件夹路径
        String htmlPath = getExternalFilesDir("html").getPath();
        File htmlFile = new File(htmlPath);
        // 判断是否存在,不存在则创建
        if (htmlFile.exists()){
            htmlPath =  htmlFile.getPath()+File.separator+"index.html";
        }else {
            htmlFile.mkdirs();
            htmlPath =  htmlFile.getPath()+File.separator+"index.html";
        }
        // 地址
        String localFilePath = "file:///"+htmlPath;
        //3.指定的URL的html文件
        /**
         * 若是不显示,在AndroidManifest.xml中添加android:usesCleartextTraffic="true"
         * 并且设置网络权限
         */
        String urlPath = "https://www.baidu.com/";




webView = findViewById(R.id.webView);
        com.tencent.smtt.sdk.WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);// 设置支持javascript
        webSettings.setUseWideViewPort(true);//将图片调整到适合webView大小
        webSettings.setLoadWithOverviewMode(true);//缩放至屏幕大小
        webSettings.setDomStorageEnabled(true);//设置DOM缓存,当H5网页使用localstorage时一定要设置
        webSettings.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);// 设置去缓存,防止加载的是上一次数据
        webSettings.setDatabaseEnabled(true);

        // 解决加载本地内存中报错 err_access_denied
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);

        webSettings.setAllowUniversalAccessFromFileURLs(true);

        //加载html
        if (filePath != null) {
            webView.loadUrl(localFilePath);
        }
相关推荐
独立开阀者_FwtCoder3 分钟前
面试官:为什么在 Vue3 中 ref 变量要用 .value?
前端·javascript·vue.js
NetX行者6 分钟前
基于Vue 3的AI前端框架汇总及工具对比表
前端·vue.js·人工智能·前端框架·开源
独立开阀者_FwtCoder6 分钟前
手握两大前端框架,Vercel 再出手拿下 Nuxt.js,对前端有什么影响?
前端·javascript·vue.js
独立开阀者_FwtCoder7 分钟前
弃用 html2canvas!快 93 倍的截图神器!
前端·javascript·vue.js
weixin_3993806921 分钟前
TongWeb8.0.9.0.3部署后端应用,前端访问后端报405(by sy+lqw)
前端
伍哥的传说42 分钟前
H3初识——入门介绍之常用中间件
前端·javascript·react.js·中间件·前端框架·node.js·ecmascript
洛小豆1 小时前
深入理解Pinia:Options API vs Composition API两种Store定义方式完全指南
前端·javascript·vue.js
洛小豆1 小时前
JavaScript 对象属性访问的那些坑:她问我为什么用 result.id 而不是 result['id']?我说我不知道...
前端·javascript·vue.js
叹一曲当时只道是寻常1 小时前
Softhub软件下载站实战开发(十六):仪表盘前端设计与实现
前端·golang
超级土豆粉2 小时前
npm 包 scheduler 介绍
前端·npm·node.js