WebView 使用簡介
一 WebView 相關的類
1. WebView
用來顯示網頁,使用必須時刻注意我們需要添加網絡權限
<uses-permission android:name="android.permission.INTERNET"/>
加載網頁:
webView.loadUrl("http://www.baidu.com/");
加載本地網頁, 網頁放在 assets/html 目錄下,
mWebView.loadUrl("file:///android_asset/html/hello.html");
2. WebSettings
對WebView進行配置和管理. WebView 在生成的時候默認生成WebSettings,通過 mWebView.getSettings 獲取WebSettings。
如果WebView 銷毀,這時候調用WebSettings 方法會出錯。
WebSettings webSettings = mWebView.getSettings();
// 允許javascript 調用
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
// WebView 默認視頻播放必須由用戶的手勢觸發,設置為false 可以在js中 設置進入網頁立即播放視頻
webSettings.setMediaPlaybackRequiresUserGesture(false);
3. WebViewClient
WebViewClient 處理WebView 各種通知 & 請求事件
直接通過WebView loadUrl 會跳轉到手機的瀏覽器, 如果需要WebView 本身顯示網頁,需要在WebViewClient 的
shouldOverrideUrlLoading 中攔截。
mWebView.setWebViewClient(new NmWebViewClient ());
private class NmWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
WebViewClient 的一些回調函數
- onPageStarted
- onPageFinished
- onLoadResource
- onReceivedError
- shouldOverrideUrlLoading
4. WebChromeClient
WebChromeClient 處理一些和Js 相關的回調
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.e("onConsoleMessage", consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
});
WebChromeClient 的一些主要回調方法
- onProgressChanged
- onConsoleMessage
- onReceivedTitle
- onJsAlert
- onJsConfirm
- onJsPrompt
- onJsTimeout
二 Android JS 相互調用
1. Android調用JS代碼的方法有2種:
- 通過WebView的loadUrl() 這種方式沒有返回值,需要Js 主動通知。
- 通過WebView的 public void evaluateJavascript(String script, ValueCallback<String> resultCallback), 有返回值,但是只能在4.4 版本以上使用
調用Js的代碼 script 格式為: javascript:function('args')
@OnClick(R.id.iv_call_js)
void onAndroidCallJsClick(){
mWebView.post(new Runnable() {
@Override
public void run() {
mWebView.loadUrl("javascript:javaCallJsWith('JavascriptInterface Javascript')");
}
});
}
@OnClick(R.id.iv_evaluate)
void onAndroidCallJsParamClick(){
mWebView.evaluateJavascript("javascript:javaCallJsEvaluate('Evaluate Javascript')", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
Toast.makeText(WebViewActivity.this, value, Toast.LENGTH_LONG).show();
}
});
}
2. 對于JS調用Android代碼的方法有3種:
- 通過WebView的addJavascriptInterface()進行對象映射
- 通過 WebViewClient 的shouldOverrideUrlLoading ()方法回調攔截 url
- 通過 WebChromeClient 的onJsAlert()、onJsConfirm()、onJsPrompt()方法回調攔截JS對話框alert()、confirm()、prompt() 消息
//對應js中的test 對象
mWebView.addJavascriptInterface(WebViewActivity.this, "test");
@JavascriptInterface
public void hello( ){
Log.e("WebView","hello");
Toast.makeText(this, "Js Call android", Toast.LENGTH_LONG).show();
}
@JavascriptInterface
public void hello(String msg){
Log.e("WebView","hello");
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
// WebViewClient 攔截URL
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if ( uri.getScheme().equals("js")) {
Toast.makeText(WebViewActivity.this, url, Toast.LENGTH_LONG).show();
} else {
view.loadUrl(url);
}
return true;
}
// WebChromeClient 攔截
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder b = new AlertDialog.Builder(WebViewActivity.this);
b.setTitle("Alert");
b.setMessage(message);
b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
b.setCancelable(false);
b.create().show();
return true;
}
網頁 hello.html 代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>louie.wang</title>
<script type="text/javascript">
function javaCallJsWith(arg){
document.getElementById("content").innerHTML = (arg);
}
function javaCallJsEvaluate(arg){
document.getElementById("content").innerHTML = (arg);
return "Return Result Very Good!!!"
}
</script>
<script>
function callAndroid(){
test.hello();
}
function callAndroidWith(){
test.hello("js帶參數調用android中的代碼");
}
function callAndroidByUrl(){
/*約定的url協議為:js://webview?arg1=111&arg2=222*/
document.location = "js://webview?arg1=111&arg2=222";
}
function clickPrompt(){
var result = prompt("js://demo?arg1=111&arg2=222");
alert("demo " + result);
}
</script>
</head>
<body>
<h1>It works!</h1>
<br/>
<button type="button" id="button1" onclick="callAndroid()">js調用android中的代碼</button>
<br/>
<button type="button" id="button2" onclick="callAndroidWith()">js帶參數調用android中的代碼</button>
<br/>
<button type="button" id="button3" onclick="callAndroidByUrl()">js通過URL調用Android代碼</button>
<br/>
<button type="button" id="button4" onclick="clickPrompt()">js通過onJsAlert調用Android代碼</button>
<br/>
<h1><div id="content">Hello World</div></h1>
</body>
</html>
三 WebView Debug
在 Android 4.4 (KitKat) 或更高版本中,使用 DevTools 可以在原生 Android 應用中調試 WebView 內容。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) {
mWebView.setWebContentsDebuggingEnabled(true);
}
}
WebChromeClient 的onConsoleMessage 回調函數 可以打印出 Js 的Consol.log
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.e("onConsoleMessage", consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
});
WebView 內存泄漏
WebView 在Android 一些版本上存在內存泄漏。在8.0 版本測試沒有發現這個問題。
可以參考下面的一些文章。
- http://leehong2005.com/2016/08/19/webview-memory-leak/
- http://linghaolu.github.io/webview/memory/leak/2015/07/16/android-5.1-webview-memory-leak.html
- https://dev.qq.com/topic/59267f94eb3f11cc2e12f503