原生与H5交互介绍

转载请注明出处:https://blog.csdn.net/mr_leixiansheng/article/details/80997246

   

步骤如下:

1、允许webView加载JS

2、编写js接口类

3、webView添加js接口

代码如下:

布局:

<?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/web_view"
        android:layout_width="match_parent"
        android:layout_height="300dp"/>

    <TextView
        android:id="@+id/tv_reload"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#fbd22430"
        android:textSize="20sp"
        android:text="测试"/>

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

        <EditText
            android:id="@+id/edit_text"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btn_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发送至H5"/>

        <Button
            android:id="@+id/btn_send3"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="调用H5有参方法"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark">

        <Button
            android:id="@+id/btn_send2"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="调用H5无参方法"/>

        <Button
            android:id="@+id/btn_send4"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="5加5,返回到安卓"/>
    </LinearLayout>
</LinearLayout>

Main

package com.example.leixiansheng.webviewh5;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class MainActivity extends AppCompatActivity {

	private static final String TAG = "MainActivity";

	private WebView mWebView;
	private TextView mTvReload;
	private EditText mEditText;
	private Button mButton;
	private Button mButton2;
	private Button mButton3;
	private Button mButton4;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		EventBus.getDefault().register(this);
		initWidgets();		//初始化
		initEvent();
	}

	private void initEvent() {
		/**
		 * 安卓端向H5发送数据
		 *WebView.loadUrl("javascript:xxxxx")
		 */
		mButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String str = mEditText.getText().toString();
				//如果H5 remote()方法存在,调用H5 remote()方法
				mWebView.loadUrl("javascript:if(window.remote){window.remote('" + str + "')}");
				//调用H5有参无返回方法,没有进行方法是否存在的判断
//				mWebView.loadUrl("javascript:remote(\"" + str + "\")");	//用\" ....\" 转义传送字符
//				mWebView.loadUrl("javascript:remote('哈哈')");	//用‘str’ 传送字符
			}
		});

		mButton3.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String str = mEditText.getText().toString();
//				如果H5 remote()方法存在,调用H5 remote()方法
				mWebView.loadUrl("javascript:if(window.remote){window.remote('" + str + "')}");
				//调用H5有参无返回方法,没有进行方法是否存在的判断
//				mWebView.loadUrl("javascript:remote(\"" + str + "\")");	//用\" ....\" 转义传送字符
//				mWebView.loadUrl("javascript:remote('哈哈')");	//用‘str’ 传送字符
			}
		});

		mButton2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//调用H5无参无返回方法
				mWebView.loadUrl("javascript:show()");
			}
		});


		mButton4.setOnClickListener(new View.OnClickListener() {
			@RequiresApi(api = Build.VERSION_CODES.KITKAT)
			@Override
			public void onClick(final View v) {
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
					//Android调用有返回值js方法,安卓4.4以上才能用这个方法
					mWebView.evaluateJavascript("sum(5,5)", new ValueCallback<String>() {
						@Override
						public void onReceiveValue(String value) {
							Log.i(TAG, "js返回数据" + value);
							mTvReload.setText(value);
						}
					});
				} else {
					//安卓4.4以下用这个方法
					mWebView.loadUrl("javascript:sumBefore(10,10)");
				}

			}
		});
	}

	private void initWidgets() {
		mWebView = findViewById(R.id.web_view);
		mTvReload = findViewById(R.id.tv_reload);
		mEditText = findViewById(R.id.edit_text);
		mButton = findViewById(R.id.btn_send);
		mButton2 = findViewById(R.id.btn_send2);
		mButton3 = findViewById(R.id.btn_send3);
		mButton4 = findViewById(R.id.btn_send4);

		//设置WebView属性,能够执行Javascript接口
		mWebView.getSettings().setJavaScriptEnabled(true);

		//给webView添加Javascript接口
		mWebView.addJavascriptInterface(new ActivityJsInterface(),"webTest");


		//其他

		// WebView 加载assets目录下的html文件,一般是加载H5给的url
		mWebView.loadUrl("file:///android_asset/test.html");
	}

	/**
	 * H5 调用 安卓端:H5向安卓传递数据,然后安卓端更新数据
	 * @param event
	 */
	@Subscribe
	public void onEvent(final TestEvent event) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mTvReload.setText(event.str);
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}
}

JsBridge

package com.example.leixiansheng.webviewh5;

import android.util.Log;
import android.webkit.JavascriptInterface;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Leixiansheng on 2018/5/14.
 */

public class ActivityJsInterface {

	private static final String TAG = "ActivityJsInterface";

	/**
	 * 这里所有方法不在主线程执行
	 * @param str
	 */
	@JavascriptInterface
	public void setValue(String str) {
		EventBus.getDefault().post(new TestEvent(str));
	}

}

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebView</title>
    <style type="text/css">
        body{
            background: #cbcc1a
        }
    </style>
</head>
<body>
<h2>WebView</h2>
<div class="o">
    <span>请输入:</span>
    <input type="text" placeholder="输入文字" id="textVal">
    <button id="onClickbtn" onclick="clickFun()">点击发送</button>
</div>
<style>

</style>
<script type="text/javascript">
    function clickFun() {
        var value =document.getElementById('textVal').value
        window.webTest.setValue(value)
    }

    function remote(str) {
        document.getElementById('textVal').value=str;
    }

    function show() {
        document.getElementById('textVal').value="hello world";
    }

    function sum(a, b) {
        return a + b;
    }

     function sumBefore(m,n){
        var value = m+n;
        window.webTest.setValue(value);
    }

</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/mr_leixiansheng/article/details/80997246
今日推荐