H5 Web网页通过JS(JavaScript)脚本调用Android本地原生方法函数

版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/86004046

H5 Web网页通过JS(JavaScript)脚本调用Android本地原生方法函数

假设现在Android原生代码中有一个本地函数:androidNativeSayHello(),打算提供给外部H5页面使用。
第一步,在Android原生代码中准备好提供给H5网页调用的本地原生函数:

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

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

        mWebView = findViewById(R.id.webview);

        mWebView.loadUrl("file:///android_asset/web.html");

        WebSettings mWebSettings = mWebView.getSettings();

        //启用JavaScript。
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setUseWideViewPort(true);

        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        mWebView.addJavascriptInterface(new MyJavaScriptInterface(this), "MyJSInterface");
    }

    private class MyJavaScriptInterface {
        private Context mContext;

        public MyJavaScriptInterface(Context context) {
            mContext = context;
        }

        //添加JS注解@JavascriptInterface。该Android原生的本地方法,供H5 Web网页调用。
        //该函数的访问属性必须是public。
        @JavascriptInterface
        public void androidNativeSayHello() {
            System.out.println("android native say 'hello , world !'");
        }
    }
}

注意此时在给WebView增加JS接口时候(addJavascriptInterface),定义的名字‘MyJSInterface’,该名字‘MyJSInterface’是H5 Web网页中的JS代码调用的‘句柄’。

第二步,直接在H5的JS中调用。
根据在Android原生代码中定义的句柄‘MyJSInterface’’直接调用Android原生的本地函数:

<html>
<body>

<script>
function showMsg()
{
    MyJSInterface.androidNativeSayHello();
}

</script>

<form>
    <input type="button"
           value="H5 Web网页调用Android原生本地方法"
           onclick="showMsg()"/>
</form>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/86004046