android 中 java 和 javascript 通过webview 交互

jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here



    

hello world, we will change!

         

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++);
        }
    };
}


你可能感兴趣的:(Android)