交互方式总结
-
Android调用JS方法两种方式
- 通过WebView的loadUrl()方式;
- 通过WebView的evaluateJavascript()方式;
-
JS调用Android的三种方式
- 通过WebView的addJavascriptInterface()进行对象的映射
- 通过 WebViewClient 的shouldOverrideUrlLoading ()方法回调拦截 url
- 通过 WebChromeClient 的onJsAlert()、onJsConfirm()、onJsPrompt()方法回调拦截JS对话框alert()、confirm()、prompt() 消息
Android调用JS方法的两种方法具体分析
通过WebView的loadUrl()方式
1.方便演示用本地的html文件来做演示
- 需要加载的本地js.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carson_Ho</title>
<script>
// Android需要调用的方法
function callJS(){
alert("Android调用了JS的callJS方法");
}
function callAndroid(){
test.hello("js调用了Android中的hello方法");
}
function callAndroidofOverrideloadurl(){
document.location = "js://webview?arg1=111&arg2=222";
}
function returnResult(result){
alert("android return result:"+result);
}
function clickprompt(){
var result=prompt("js://demo?arg1=111&arg2=222");
alert("demo:" + result);
}
</script>
</head>
<body>
<button type="button" id="button1" onclick="callAndroid()">点击按钮调用callAndroid函数</button>
<button type="button" id="button2" onclick="callAndroidofOverrideloadurl()">点击按钮调用callAndroid函数通过overrideloadurl</button>
<button type="button" id="button3" onclick="clickprompt()">通过prompt调用Android代码</button>
</body>
</html>
- Android端的代码如下所示
package com.example.webview;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
WebView mWebView;
Button callJSButton;
Button returnResultJs;
int version = Build.VERSION.SDK_INT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
returnResultJs = (Button) findViewById(R.id.return_result);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new AndroidtoJs(MainActivity.this),"test");
mWebView.loadUrl("file:///android_asset/js.html");
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if(uri.getScheme().equals("js")){
if(uri.getAuthority().equals("webview")){
HashMap<String, String> params = new HashMap<>();
Set<String> collection = uri.getQueryParameterNames();
String arg1 = collection.toString();
}
}
return super.shouldOverrideUrlLoading(view, url);
}
});
returnResultJs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int result = 100;
mWebView.loadUrl("javascript:returnResult(" +"\"" + result + "\"" + ")");
// int version = Build.VERSION.SDK_INT;
// if(version <19){
// mWebView.loadUrl("javascript:returnResult(" + "faffdsfsfsafdasdfds" + ")");
// }else{
// mWebView.evaluateJavascript("javascript:returnResult(" + "faffdsfsfsafdasdfds" + ")", new ValueCallback<String>() {
// @Override
// public void onReceiveValue(String value) {
//
// }
// });
// }
}
});
callJSButton = (Button) findViewById(R.id.call_js);
callJSButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWebView.post(new Runnable() {
@Override
public void run() {
int version = Build.VERSION.SDK_INT;
if(version <19){
mWebView.loadUrl("javascript:callJS()");
}else{
mWebView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
}
});
}
}
});
}
});
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("MY WEBVIEW ALERT");
builder.setMessage(message);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setCancelable(false);
builder.create().show();
return true;
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
Uri uri = Uri.parse(message);
if ( uri.getScheme().equals("js")) {
// 如果 authority = 预先约定协议里的 webview,即代表都符合约定的协议
// 所以拦截url,下面JS开始调用Android需要的方法
if (uri.getAuthority().equals("demo")) {
//
// 执行JS所需要调用的逻辑
System.out.println("js调用了Android的方法");
// 可以在协议上带有参数并传递到Android上
HashMap<String, String> params = new HashMap<>();
Set<String> collection = uri.getQueryParameterNames();
//参数result:代表消息框的返回值(输入值)
result.confirm("js调用了Android的方法成功啦");
}
return true;
}
return super.onJsPrompt(view, url, message, defaultValue, result);
}
});
}
}