Android的webView和h5+js交互

Android的webView和h5+js交互

现在开发越来越多的遇到Android本地代码和h5和js交互,于是写了个小demo记录一下,效果图如下:

这里写图片描述

上面图里里面的上面包括返回都是一个webView,底面的Android按钮是一个button。
布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ruicheng.javascript2android.MainActivity">

<WebView
    android:id="@+id/wb"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:text="android本地按钮"
    />
</RelativeLayout>

mainactivitty代码如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private WebView mWebView;
    private Button mButton;
    private WebAppInterface mAppInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.wb);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(this);
        mAppInterface = new WebAppInterface(this);
        initWeb();
    }

    private void initWeb() {
        mWebView.loadUrl("file:///android_asset/index.html");//加载本地的html

        WebSettings settings = mWebView.getSettings();//获取WebSettings对象,利用WebSettings配置WebView

        settings.setJavaScriptEnabled(true);//设置允许执行JS脚本

        mWebView.addJavascriptInterface(mAppInterface,"app");//添加HTML与AAndroid的通讯接口

    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.button){
            mAppInterface.showName("测试成功");
        }
    }

    class WebAppInterface{
        private Context context;

        public WebAppInterface(Context context) {
            this.context = context;
        }

        //-----------下面是JS调用安卓的的方法

        @JavascriptInterface
        public void sayHello(String name){
            if (name.equals("")){
                Toast.makeText(context,"还没点本地按钮", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context,name, Toast.LENGTH_SHORT).show();
            }

        }
        @JavascriptInterface
        public void back(){
            Toast.makeText(context,"点击了h5的返回按钮", Toast.LENGTH_SHORT).show();
        }

        //--------------下面是安卓调用js的的方法
        @JavascriptInterface
        public void showName(final String name){
            runOnUiThread(new Runnable() {//Android更新UI需要在主线程
                @Override
                public void run() {
                    mWebView.loadUrl("javascript:showName('"+name+"')");
                }
            });
        }

    }
}

上面的代码都有注释,总结一下就是:

1.注册一个和js交互的接口new WebAppInterface(this);

2.要设置webView的mWebView.getSettings()。settings.setJavaScriptEnabled(true),允许加载js脚本。

3.mWebView.addJavascriptInterface(mAppInterface,”app”),添加HTML与Android的通讯接口,app要和html里面调用的保持一致。

4.然后就可以在html写js方法调用或者在Android里面写方法调用js。

到现在为止我们就实现了Android和h5,js交互了 ##

下面是html,我放在了本地asset里面。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>HTML 测试</title>

    <style type="text/css">  
        *{  
            margin: 0;  
            padding: 0;  
        }  
        .title{  
            position: relative;  
            width: 100%;  
            height: 50px;  
            background-color: green;
        }  
        .back{  
            position: absolute;           
            font-size: 24px;  
            background-color:#f92;  
            width: 60px;  
            height: 50px;  
        }  
        .title h2{  
            position: absolute;  
            right: 30%;  
            height: 50px;  
            float: left;  
            line-height: 50px;  

        }  
        .content{  
            margin: 3px;  
        }  
        #textName{  
            display: block;  
            width: 100%;  
            height: 35px;  
        }  
        .button{  
            display: block;  
            width: 100%;  
            height: 35px;  
            font-size: 24px;  
            border: none;  
            background-color: red;
        }
    </style>

    <script type="text/javascript">

    function sayHello() {  
        var name = document.getElementById('textName').value;  
        app.sayHello(name);  
    }  

    function back(){  
        app.back();  
    }  

    function showName(name){  
        document.getElementById('textName').value = name;  
    }

    </script>

</head>
<body>
<div class="title">
    <input class="back" type="button" onclick="back()" value="返回">
    <h2>H5和js交互</h2>
</div>
<div class="content">
    <input id="textName" type="text">
    <button class="button" onclick="sayHello()">HTML按钮</button>
</div>
</body>
</html>  

Demo下载

猜你喜欢

转载自blog.csdn.net/gemgaozhen/article/details/54427958
今日推荐