android 中 java 和 javascript 通过webview 交互

jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    var count = 0;
    // 在java中调用wv.loadUrl("javascript:testJS()");执行此方法
    function testJS() {
        document.getElementById("test").innerHTML = "hello world" + count++;
    }
    function testJava() {
        window.oldfeel.apiJava(); // 调用java中的apiJava()方法
    }
</script>
</head>
<body>
    <h1>hello world, we will change!</h1>
    <button onclick="testJava()">button</button>
    <div id="test"></div>
</body>
</html>

Java代码:

package com.example.test_android;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
 
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
 
    private WebView wv;
    private Button btn;
    private int count;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv = (WebView) findViewById(R.id.webView);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.addJavascriptInterface(this, "oldfeel");
        wv.loadUrl("http://192.168.0.228:8080/web/index.jsp");
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                apiJS();
            }
        });
    }
 
    public void apiJS() {
        wv.loadUrl("javascript:testJS()"); // 调用js中的testJS()方法
    }
 
    // 在js中调用window.oldfeel.apiJava()执行此方法
    public void apiJava() {
        // btn.setText("java" + count++); // 直接执行此代码的话view不刷新,要调用handler才会刷新
        handler.post(runnable);
    }
 
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
 
        @Override
        public void run() {
            btn.setText("java" + count++);
        }
    };
}


你可能感兴趣的:(JavaScript,android,webView)