测试Android webview 加载本地html

最近开发一个需要未联网功能的App, 不熟悉使用Java原生开发界面,于是想使用本地H5做界面,本文测试了使用本地html加载远程数据。直接上代码:

MainActivity.java

java 复制代码
package com.alex.webviewlocal;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private String url="file:///android_asset/web/index.html";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webview);
        WebSettings webSettings = webView.getSettings();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript
        webSettings.setUseWideViewPort(true);   // 将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true);  // 缩放至屏幕的大小
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setUserAgentString("User-Agent");
        webSettings.setLightTouchEnabled(true); // 设置用鼠标激活被选项
        webSettings.setBuiltInZoomControls(true);   // 设置支持缩放
        webSettings.setDomStorageEnabled(true); //设置DOM缓存,当H5网页使用localstorage时,一定要设置
        webSettings.setDatabaseEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 设置去缓存,防止加载的为上一次加载的数据
        webSettings.setSupportZoom(true);   // 设置支持变焦
        webView.setHapticFeedbackEnabled(false);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccessFromFileURLs(true);

        webView.loadUrl(url);

//        try{
//            if(Build.VERSION.SDK_INT>=16){
//                Class<?> clazz = webView.getSettings().getClass();
//                Method method = clazz.getMethod(
//                        "setAllowUniversalAccessFromFileURLs", boolean.class);
//                if(method!=null){
//                    method.invoke(webView.getSettings(),true);
//                }
//            }
//        } catch (NoSuchMethodException e) {
//            throw new RuntimeException(e);
//        } catch (InvocationTargetException e) {
//            throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }
//
//        webView.loadUrl(url);
//        webView.setWebViewClient(new WebViewClient(){
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//                return super.shouldOverrideUrlLoading(view, request);
//            }
//        });

    }
}

activity_main.xml

xml 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></WebView>
</LinearLayout>

h5 文件

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./vue.min.js"></script>
    <script src="./axios.min.js"></script>
</head>
<body>
    <div id="app">
        <h2>{{message}}</h2>
        <ul>
            <li v-for="user in users" :key="user.id">{{user.name}}</li>
        </ul>
    </div>
    <script>
        var app = new Vue({
            el:'#app',
            data(){
                return {
                    message:'Hello Vue!',
                    users:[]
                }
            },
            mounted(){
                axios.get('https://jsonplaceholder.typicode.com/users').then(response => {
                    this.users = response.data
                }).catch(error => {
                    console.log(error)
                })
            }
        })
    </script>
</body>
</html>

最终效果:

相关推荐
木木子225 分钟前
[特殊字符] 音乐播放器——状态驱动的多媒体控制
android·开发语言·华为·php·harmonyos
程序猿小泓9 分钟前
从 Claude Code 学 Agent Harness:一个前端工程师的 AI Agent 学习笔记
前端·人工智能·学习
雨白21 分钟前
C 语言基础:结构体、联合体与枚举
android
柒和远方1 小时前
从审计日志到可下载证据包:事务型 Outbox、租约 fencing 与保留水位
前端·后端·架构
minglie11 小时前
npm ali-oss库依赖冲突
前端·npm
CryptoPP2 小时前
BSE股票K线数据接入实战:从接口调用到前端图表展示
大数据·前端·网络·人工智能·websocket·网络协议
阿巴斯甜2 小时前
Android 代码混淆
android
没落英雄3 小时前
5. 从零开始搭建一个 AI Agent —— 人机协作与中断恢复
前端·人工智能·架构
apihz4 小时前
台风实时与历史详情查询免费 API 接口完整教程
android·开发语言·tcp/ip·dubbo·台风·天气预报
品尚公益团队4 小时前
C#在asp.net网页开发中的带cookie登录实现
前端·c#·asp.net