Android的webView应用与js互调app混合开发用例

android5.1.1 和 android7都测试过,都是正常使用的

android原生与html交互可以实现APP混合开发

WebView 底层还是调用的WebKit

AndroidManifest.xml 记得要配置 上网权限

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

主要代码文件:

WebViewAction.java
package com.example.a20200712;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.text.SimpleDateFormat;
import java.util.Date;

public class WebViewAction extends AppCompatActivity {
    private WebView layout_webview_content;
    private EditText layout_webview_url;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_view_layout);
        layout_webview_url = findViewById(R.id.layout_webview_url);
        layout_webview_content = findViewById(R.id.layout_webview_content);


        WebSettings webSettings = layout_webview_content.getSettings();

        // 设置与Js交互的权限
        webSettings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        // 由于设置了弹窗检验调用结果,所以需要支持js对话框
        // webview只是载体,内容的渲染需要使用webviewChromClient类去实现
        // 通过设置WebChromeClient对象处理JavaScript的对话框
        //设置响应js 的Alert()函数
        layout_webview_content.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(WebViewAction.this);
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }
        });


        // 通过addJavascriptInterface()将Java对象映射到JS对象
        //参数1:Javascript对象名 this  === new WebViewAction();
        //参数2:Java对象名
        layout_webview_content.addJavascriptInterface(this, "webViewAction");//AndroidtoJS类对象映射到js的test对象

    }

    /**
     * 供js调用客户端 入参 和返回值,只能是字符串类型
     *
     * @param a
     * @param b
     * @return
     */
    @JavascriptInterface
    public String calc(String a, String b) {
        Integer ret = (Integer.valueOf(a) + Integer.valueOf(b));
        Log.i("mw", "android方法被调用了,a:" + a + ",b:" + b + ",请算结果:" + ret);
        return a == null || b == null ? "-1" : String.valueOf(ret);
    }


    public void toUrl(View view) {
        //设置URL 资源路径
        layout_webview_content.loadUrl(layout_webview_url.getText().toString());
        //在APP应用内打开WebView
        layout_webview_content.setWebViewClient(new WebViewClient());
    }

    /**
     * 关闭JS调用android方法
     *
     * @param view
     */
    public void closeJSInvokeAndroid(View view) {
        layout_webview_content.removeJavascriptInterface("webViewAction");
    }

    public void invokeJS(View view) {

        // 通过Handler发送消息
        layout_webview_content.post(new Runnable() {
            @Override
            public void run() {

                Date currentTime = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = formatter.format(currentTime);

                String jsParam = "当前时间:" + dateString;
                // 注意调用的JS方法名要对应上

                // 调用javascript的callJS()方法
                //1、这种调用方式无返回值可用 ,看起来简洁  支持Android 4.4以下版本
                //layout_webview_content.loadUrl("javascript:callJS('"+jsParam+"')");

                //2、这种调用方式可接收返回值,效率还高于1  只支持Android 4.4以上方法
                layout_webview_content.evaluateJavascript("javascript:callJS('" + jsParam + "')", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        //此处为 js 返回的结果
                        Log.i("mw", "js返回值:" + value);
                    }
                });
            }
        });


    }

    /**
     * 重写back按扭,如果可以返回上一级 并且上一级有页面
     */
    @Override
    public void onBackPressed() {
        //如果webView可以返回上一级
        if (layout_webview_content.canGoBack()) {
            layout_webview_content.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

web_view_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入地址"
        android:id="@+id/layout_webview_url"
        ></EditText>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="进入"
            android:onClick="toUrl"
            android:layout_weight="1"></Button>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Android调用js"
            android:onClick="invokeJS"
            android:layout_weight="1"></Button>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="关闭调用Android"
            android:onClick="closeJSInvokeAndroid"
            android:layout_weight="1"></Button>
    </LinearLayout>
    <WebView
        android:id="@+id/layout_webview_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>
</LinearLayout>

webView.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Android与js互调案例</title>
</head>
<body>

<h3 id="testTxt">你好</h3>
</body>
<script type="text/javascript">
function callJS(jsParam){
	//弹出alert
	alert("android调用JS进来了");
	//js调用android方法
	var ret = webViewAction.calc(3,2);
	document.getElementById("testTxt").innerHTML = jsParam +"=====调用android返回值:"+ret;
	return "JS把值处理后又返回到Android==="+jsParam;
}
</script>
</html>

http://www.mwview.com/v/c/r/html/demo_android_webView  

猜你喜欢

转载自blog.csdn.net/m0_37622302/article/details/107402387