交互方式總結(jié)
-
Android調(diào)用JS方法兩種方式
- 通過WebView的loadUrl()方式;
- 通過WebView的evaluateJavascript()方式;
-
JS調(diào)用Android的三種方式
- 通過WebView的addJavascriptInterface()進行對象的映射
- 通過 WebViewClient 的shouldOverrideUrlLoading ()方法回調(diào)攔截 url
- 通過 WebChromeClient 的onJsAlert()、onJsConfirm()、onJsPrompt()方法回調(diào)攔截JS對話框alert()孕讳、confirm()丙笋、prompt() 消息
Android調(diào)用JS方法的兩種方法具體分析
通過WebView的loadUrl()方式
1.方便演示用本地的html文件來做演示
- 需要加載的本地js.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carson_Ho</title>
<script>
// Android需要調(diào)用的方法
function callJS(){
alert("Android調(diào)用了JS的callJS方法");
}
function callAndroid(){
test.hello("js調(diào)用了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()">點擊按鈕調(diào)用callAndroid函數(shù)</button>
<button type="button" id="button2" onclick="callAndroidofOverrideloadurl()">點擊按鈕調(diào)用callAndroid函數(shù)通過overrideloadurl</button>
<button type="button" id="button3" onclick="clickprompt()">通過prompt調(diào)用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 = 預(yù)先約定協(xié)議里的 webview缎罢,即代表都符合約定的協(xié)議
// 所以攔截url,下面JS開始調(diào)用Android需要的方法
if (uri.getAuthority().equals("demo")) {
//
// 執(zhí)行JS所需要調(diào)用的邏輯
System.out.println("js調(diào)用了Android的方法");
// 可以在協(xié)議上帶有參數(shù)并傳遞到Android上
HashMap<String, String> params = new HashMap<>();
Set<String> collection = uri.getQueryParameterNames();
//參數(shù)result:代表消息框的返回值(輸入值)
result.confirm("js調(diào)用了Android的方法成功啦");
}
return true;
}
return super.onJsPrompt(view, url, message, defaultValue, result);
}
});
}
}