为了了解JS与Android之间是如何通信的,所以简单的撸了如下代码:

使用Android Studio初始化一个项目,项目主要文件如下

MainActivity.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.example.aurora.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;


public class MainActivity extends AppCompatActivity {

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

final WebView webView = (WebView) findViewById(R.id.webview);

// 点击button触发JS内定义的callJs方法
Button button = (Button) findViewById(R.id.callJs);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
webView.loadUrl(("javascript: callJs('Hello JS')"));
}
});

// 设置webView可以执行JS
webView.getSettings().setJavaScriptEnabled(true);
//设置webView可以弹框
webView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message,final JsResult result){
return super.onJsAlert(view,url,message,result);
}
});

class JsObject {
@JavascriptInterface
// 定义sayHello方法
public void sayHello(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
// 将Java对象注入JS上下文中,名称为"example"
webView.addJavascriptInterface(new JsObject(), "example");
webView.loadUrl("file:///android_asset/example.html");
}
}

activity_main.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8" ?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Call JS"
android:id="@+id/callJs"
/>
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>

example.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<body>
<h1 id="hello">Call Android</h1>
</body>
<script>
// JS调用sayHello方法
document.querySelector('#hello').addEventListener('click',() => {
example.sayHello('hello android')
},false)

// 待Java调用的方法
const callJs = (msg) => {
alert(msg)
}
</script>
</html>

总而言之,Java可以通过webView.loadUrl(javascript: xxxxxx)来触发JS中定义的方法
同时,Java可以通过webView.addJavascriptInterface方法将Java对象注入JS上下文中,从而让JS可以直接调用在Java中定义的方法