JavaScript调Java

时间:2024-01-19 09:42:02

1.映射Java对象到JavaScript对象上

MainActivity.java

package com.example.jsdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView; public class MainActivity extends AppCompatActivity {
private WebView wView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wView = (WebView) findViewById(R.id.wView);
wView.loadUrl("file:///android_asset/demo1.html");
WebSettings webSettings = wView.getSettings();
//①设置WebView允许调用js
webSettings.setJavaScriptEnabled(true);
webSettings.setDefaultTextEncodingName("UTF-8");
//②设置支持js调用java
wView.addJavascriptInterface(new AndroidAndJSInterface(),"Android"");
} class AndroidAndJSInterface{
@JavascriptInterface
public void showToast(){
Toast.makeText(MainActivity.this, "我被js调用了", Toast.LENGTH_SHORT).show();
}
}
}

注意:解决该WebView.addJavascriptInterface接口不起作用的两种办法

①针对版本改成16

②在JavaScript接口类的方法加上@JavascriptInterface注解

2.JavaScript调用Java对象示例

demo1.html

<input type="button" value="点击Android被调用" onclick="window.Android.showToast()" />