Android

1. Build objects to interact with

TestObject
public static class TestObject {
    private final WeakReference<Activity> wfActivity;
    public TestObject(Activity ac) {
        this.wfActivity = new WeakReference<>(ac);
    }
    
    // Handle the HTML button trigger event
    @JavascriptInterface
    public void login(String uid) {
        if(wfActivity.get() ! =null) {}}@JavascriptInterface
    public void loginOut(a) {}}Copy the code

2. WebViewSet up theWebViewClient

mWebView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        return super.shouldOverrideUrlLoading(view, request);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return super.shouldOverrideUrlLoading(view, url);
    }
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }
    @Override
    public void onPageFinished(WebView view, String url) {
    	// Pass the data to HTML
        final UserInfo bean = DataSourceManager.getUserInfoBen();
        if(bean ! =null) {
            final String token = ACache.get(context).getAsString(Constants.TOKEN);
            mWebView.evaluateJavascript("javascript:getUserInfo('" + bean.user_id + "', '" + bean.avatar + "', '" + token + "')".new ValueC
                @Override
                public void onReceiveValue(String value) {
                    //Log.e("123", "onReceiveValue getUserInfo : " + value);}}); }super.onPageFinished(view, url);
    }
    @Override
    public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
        super.doUpdateVisitedHistory(view, url, isReload); }}); mWebView.addJavascriptInterface(new TestObject(mMainActivity), "testObject");
mWebView.loadUrl("https://xxx.net/xxx/xxx");
Copy the code

Html

<html lang="zh-cn">
<head>
    <script>
	// H5 receives user information from the mobile terminal
        function getUserInfo(uid,pwd,avatar){
           return "User Information :"+ uid+""+pwd +""+avatar;
        }
	// H5 receives the mobile terminal exit action
        function exitUser(uid){
           return "Exit account:"+ uid;
        }
    
    </script>
</head>
<body bgcolor="#BCBCBC">
    <p>
        <button type="button" onclick="testObject.login(uid);">H5 Sends the user information to the mobile terminal. The mobile terminal logs in using the corresponding login method</button>
    </p>
    <p>
        <button type="button" onclick="testObject.loginOut(uid);">HTML user exit operation, mobile processing loginOut method</button>
    </p>
</body>
</html>
Copy the code