2019-05-15 Android js和原生交互

2019-05-15  本文已影响0人  菜神一把梭

Android js和原生交互
简单的demo

package com.xindeco.swingu_h5;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.Toast;

import com.xindeco.reader.common.Action;
import com.xindeco.reader.common.ReaderListener;
import com.xindeco.reader.common.Tag;
import com.xindeco.reader.swingu.SwingUReader;

public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
        mWebView = findViewById(R.id.web_view);
        mWebView.loadUrl("file:///android_asset/test.html");
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new JsInteration( new CallBack(){

                          @Override    
                           void  callBack(Object o){

                 }
            }
), "android");

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.equals("https://www.baidu.com/")) {
                    Toast.makeText(MainActivity.this, "就是要拦你", Toast.LENGTH_SHORT).show();
                    return true;
                } else {
                    mWebView.loadUrl(url);
                    return true;
                }
            }
        });

        findViewById(R.id.call_js).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final EditText input = findViewById(R.id.input);
                String content = input.getText().toString().trim();
                if (!TextUtils.isEmpty(content)) {
                    // 调用js方法,更新页面
//                    mWebView.loadUrl("javascript:change(\"" + content + "\")"); // 没带返回值的调用方式
                    mWebView.evaluateJavascript("javascript:change(\"" + content + "\")", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            input.setText(value);
                        }
                    });
                }
            }
        });
    }
   interface CallBack{
        void callBack(Object o);
}

    public class JsInteration {
        Callback callBack;
       
        public JsInteration(CallBack callback){
             this.callBack = callback;
}
        @JavascriptInterface
        public String toast(String msg) {
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            return "我是java的返回值";
        }
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="我要改变网页的内容"/>

    <Button
        android:id="@+id/call_js"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是原生的button啦"/>

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

HTML页面,把该页面放置在assets文件夹下

<html>
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="content-type">
        <title>js和原生交互</title>
    </head>

    <script type="text/javascript">
        <!--该方法调用原生的toast方法-->
        function toast(){
            var s = document.getElementById("input_toast").value;
            var result = window.android.toast(s);
            document.getElementById("input_toast").value=result;
        }

        <!--该方法被原生调用-->
        function change(content){
            document.getElementById("input_toast").value=content;
            return "我是js的返回值";
        }
    </script>

    <body>
        <p>
            <input type="text" id="input_toast"/>
        </p>
        <p>
            <input type="button" id="toast" value="toast" onclick="toast()"/>
        </p>
        <a href="https://www.taobao.com/">跳转淘宝,不拦你</a>
        <br>
        <a href="https://www.baidu.com/">跳转百度,别拦我</a>
    </body>
</html>

记得添加<uses-permission android:name="android.permission.INTERNET"/>权限才能访问网络

原文:https://blog.csdn.net/mqdxiaoxiao/article/details/81414935
版权声明:本文为博主原创文章,转载请附上博文链接!

上一篇下一篇

猜你喜欢

热点阅读