前言
現在很多App里都內置了Web網頁(Hyprid App),比如說很多電商平台,淘寶、京東、聚划算等等,如下圖
京東首頁
那么這種該如何實現呢?其實這是Android里一個叫WebView的組件實現的。今天我將全面介紹WebView的常用用法。
目錄
文章目錄
1. 簡介
WebView是一個基於webkit引擎、展現web頁面的控件。
Android的Webview在低版本和高版本采用了不同的webkit版本內核,4.4后直接使用了Chrome。
2. 作用
顯示和渲染Web頁面
直接使用html文件(網絡上或本地assets中)作布局
可和JavaScript交互調用
WebView控件功能強大,除了具有一般View的屬性和設置外,還可以對url請求、頁面加載、渲染、頁面交互進行強大的處理。
3. 使用介紹
一般來說Webview可單獨使用,可聯合其子類一起使用,所以接下來,我會介紹:
Webview自身的常見方法;
Webview的最常用的子類
(WebSettings類、WebViewClient類、WebChromeClient類)
Android和Js的交互
3.1 Webview常用方法
3.1.1 加載url
加載方式根據資源分為三種
//方式1. 加載一個網頁:
webView.loadUrl("http://www.google.com/");
//方式2:加載apk包中的html頁面
webView.loadUrl("file:///android_asset/test.html");
//方式3:加載手機本地的html頁面
webView.loadUrl("content://com.android.htmlfileprovider/sdcard/test.html");
// 方式4: 加載 HTML 頁面的一小段內容
WebView.loadData(String data, String mimeType, String encoding)
// 參數說明:
// 參數1:需要截取展示的內容
// 內容里不能出現 ’#’, ‘%’, ‘\’ , ‘?’ 這四個字符,若出現了需用 %23, %25, %27, %3f 對應來替代,否則會出現異常
// 參數2:展示內容的類型
// 參數3:字節碼
3.1.1 WebView的狀態
//激活WebView為活躍狀態,能正常執行網頁的響應
webView.onResume() ;
//當頁面被失去焦點被切換到后台不可見狀態,需要執行onPause
//通過onPause動作通知內核暫停所有的動作,比如DOM的解析、plugin的執行、JavaScript執行。
webView.onPause();
//當應用程序(存在webview)被切換到后台時,這個方法不僅僅針對當前的webview而是全局的全應用程序的webview
//它會暫停所有webview的layout,parsing,javascripttimer。降低CPU功耗。
webView.pauseTimers()
//恢復pauseTimers狀態
webView.resumeTimers();
//銷毀Webview
//在關閉了Activity時,如果Webview的音樂或視頻,還在播放。就必須銷毀Webview
//但是注意:webview調用destory時,webview仍綁定在Activity上
//這是由於自定義webview構建時傳入了該Activity的context對象
//因此需要先從父容器中移除webview,然后再銷毀webview:
rootLayout.removeView(webView);
webView.destroy();
3.1.2 關於前進 / 后退網頁
//是否可以后退
Webview.canGoBack()
//后退網頁
Webview.goBack()
//是否可以前進
Webview.canGoForward()
//前進網頁
Webview.goForward()
//以當前的index為起始點前進或者后退到歷史記錄中指定的steps
//如果steps為負數則為后退,正數則為前進
Webview.goBackOrForward(intsteps)
常見用法:Back鍵控制網頁后退
問題:在不做任何處理前提下 ,瀏覽網頁時點擊系統的“Back”鍵,整個 Browser 會調用 finish()而結束自身
目標:點擊返回后,是網頁回退而不是推出瀏覽器
解決方案:在當前Activity中處理並消費掉該 Back 事件
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
3.1.3 清除緩存數據
//清除網頁訪問留下的緩存
//由於內核緩存是全局的因此這個方法不僅僅針對webview而是針對整個應用程序.
Webview.clearCache(true);
//清除當前webview訪問的歷史記錄
//只會webview訪問歷史記錄里的所有記錄除了當前訪問記錄
Webview.clearHistory();
//這個api僅僅清除自動完成填充的表單數據,並不會清除WebView存儲到本地的數據
Webview.clearFormData();
3.2 常用類
3.2.1 WebSettings類
作用:對WebView進行配置和管理
配置步驟 & 常見方法:
配置步驟1:添加訪問網絡權限(AndroidManifest.xml)
這是前提!這是前提!這是前提!
<uses-permission android:name="android.permission.INTERNET"/>
配置步驟2:生成一個WebView組件(有兩種方式)
//方式1:直接在在Activity中生成
WebView webView = new WebView(this)
//方法2:在Activity的layout文件里添加webview控件:
WebView webview = (WebView) findViewById(R.id.webView1);
配置步驟3:進行配置-利用WebSettings子類(常見方法)
//聲明WebSettings子類
WebSettings webSettings = webView.getSettings();
//如果訪問的頁面中要與Javascript交互,則webview必須設置支持Javascript
webSettings.setJavaScriptEnabled(true);
// 若加載的 html 里有JS 在執行動畫等操作,會造成資源浪費(CPU、電量)
// 在 onStop 和 onResume 里分別把 setJavaScriptEnabled() 給設置成 false 和 true 即可
//支持插件
webSettings.setPluginsEnabled(true);
//設置自適應屏幕,兩者合用
webSettings.setUseWideViewPort(true); //將圖片調整到適合webview的大小
webSettings.setLoadWithOverviewMode(true); // 縮放至屏幕的大小
//縮放操作
webSettings.setSupportZoom(true); //支持縮放,默認為true。是下面那個的前提。
webSettings.setBuiltInZoomControls(true); //設置內置的縮放控件。若為false,則該WebView不可縮放
webSettings.setDisplayZoomControls(false); //隱藏原生的縮放控件
//其他細節操作
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //關閉webview中緩存
webSettings.setAllowFileAccess(true); //設置可以訪問文件
webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通過JS打開新窗口
webSettings.setLoadsImagesAutomatically(true); //支持自動加載圖片
webSettings.setDefaultTextEncodingName("utf-8");//設置編碼格式
常見用法:設置WebView緩存
當加載 html 頁面時,WebView會在/data/data/包名目錄下生成 database 與 cache 兩個文件夾
請求的 URL記錄保存在 WebViewCache.db,而 URL的內容是保存在 WebViewCache 文件夾下
是否啟用緩存:
//優先使用緩存:
WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//緩存模式如下:
//LOAD_CACHE_ONLY: 不使用網絡,只讀取本地緩存數據
//LOAD_DEFAULT: (默認)根據cache-control決定是否從網絡上取數據。
//LOAD_NO_CACHE: 不使用緩存,只從網絡獲取數據.
//LOAD_CACHE_ELSE_NETWORK,只要本地有,無論是否過期,或者no-cache,都使用緩存中的數據。
//不使用緩存:
WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
結合使用(離線加載)
if (NetStatusUtil.isConnected(getApplicationContext())) {
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//根據cache-control決定是否從網絡上取數據。
} else {
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//沒網,則從本地獲取,即離線加載
}
webSettings.setDomStorageEnabled(true); // 開啟 DOM storage API 功能
webSettings.setDatabaseEnabled(true); //開啟 database storage API 功能
webSettings.setAppCacheEnabled(true);//開啟 Application Caches 功能
String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
webSettings.setAppCachePath(cacheDirPath); //設置 Application Caches 緩存目錄
注意: 每個 Application 只調用一次 WebSettings.setAppCachePath(),WebSettings.setAppCacheMaxSize()
3.2.2 WebViewClient類
作用:處理各種通知 & 請求事件
常見方法:
常見方法1:shouldOverrideUrlLoading()
作用:打開網頁時不調用系統瀏覽器, 而是在本WebView中顯示;在網頁上的所有加載都經過這個方法,這個函數我們可以做很多操作。
//步驟1. 定義Webview組件
Webview webview = (WebView) findViewById(R.id.webView1);
//步驟2. 選擇加載方式
//方式1. 加載一個網頁:
webView.loadUrl("http://www.google.com/");
//方式2:加載apk包中的html頁面
webView.loadUrl("file:///android_asset/test.html");
//方式3:加載手機本地的html頁面
webView.loadUrl("content://com.android.htmlfileprovider/sdcard/test.html");
//步驟3. 復寫shouldOverrideUrlLoading()方法,使得打開網頁時不調用系統瀏覽器, 而是在本WebView中顯示
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
常見方法2:onPageStarted()
作用:開始載入頁面調用的,我們可以設定一個loading的頁面,告訴用戶程序在等待網絡響應。
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//設定加載開始的操作
}
});
常見方法3:onPageFinished()
作用:在頁面加載結束時調用。我們可以關閉loading 條,切換程序動作。
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
//設定加載結束的操作
}
});
常見方法4:onLoadResource()
作用:在加載頁面資源時會調用,每一個資源(比如圖片)的加載都會調用一次。
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean onLoadResource(WebView view, String url) {
//設定加載資源的操作
}
});
常見方法5:onReceivedError()
作用:加載頁面的服務器出現錯誤時(如404)調用。
App里面使用webview控件的時候遇到了諸如404這類的錯誤的時候,若也顯示瀏覽器里面的那種錯誤提示頁面就顯得很丑陋了,那么這個時候我們的app就需要加載一個本地的錯誤提示頁面,即webview如何加載一個本地的頁面
//步驟1:寫一個html文件(error_handle.html),用於出錯時展示給用戶看的提示頁面
//步驟2:將該html文件放置到代碼根目錄的assets文件夾下
//步驟3:復寫WebViewClient的onRecievedError方法
//該方法傳回了錯誤碼,根據錯誤類型可以進行不同的錯誤分類處理
webView.setWebViewClient(new WebViewClient(){
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
switch(errorCode)
{
case HttpStatus.SC_NOT_FOUND:
view.loadUrl("file:///android_assets/error_handle.html");
break;
}
}
});
常見方法6:onReceivedSslError()
作用:處理https請求
webView默認是不處理https請求的,頁面顯示空白,需要進行如下設置:
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); //表示等待證書響應
// handler.cancel(); //表示掛起連接,為默認方式
// handler.handleMessage(null); //可做其他處理
}
});
3.2.3 WebChromeClient類
作用:輔助 WebView 處理 Javascript 的對話框,網站圖標,網站標題等等。
常見使用:
常見方法1: onProgressChanged()
作用:獲得網頁的加載進度並顯示
webview.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress < 100) {
String progress = newProgress + "%";
progress.setText(progress);
} else {
}
});
常見方法2: onReceivedTitle()
作用:獲取Web頁中的標題
每個網頁的頁面都有一個標題,比如www.baidu.com這個頁面的標題即“百度一下,你就知道”,那么如何知道當前webview正在加載的頁面的title並進行設置呢?
webview.setWebChromeClient(new WebChromeClient(){
@Override
public void onReceivedTitle(WebView view, String title) {
titleview.setText(title);
}
常見方法3: onJsAlert()
作用:支持javascript的警告框
一般情況下在 Android 中為 Toast,在文本里面加入\n就可以換行
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("JsAlert")
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setCancelable(false)
.show();
return true;
}
常見方法4: onJsConfirm()
作用:支持javascript的確認框
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("JsConfirm")
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.setCancelable(false)
.show();
// 返回布爾值:判斷點擊時確認還是取消
// true表示點擊了確認;false表示點擊了取消;
return true;
}
常見方法5: onJsPrompt()
作用:支持javascript輸入框
點擊確認返回輸入框中的值,點擊取消返回 null。
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
final EditText et = new EditText(MainActivity.this);
et.setText(defaultValue);
new AlertDialog.Builder(MainActivity.this)
.setTitle(message)
.setView(et)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm(et.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.setCancelable(false)
.show();
return true;
}
3.3 WebView與JavaScript的交互
具體請看我寫的文章:最全面 & 最詳細的 Android WebView與JS的交互方式 匯總
3.4 注意事項:如何避免WebView內存泄露?
3.4.1 不在xml中定義 Webview ,而是在需要的時候在Activity中創建,並且Context使用 getApplicationgContext()
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mWebView = new WebView(getApplicationContext());
mWebView.setLayoutParams(params);
mLayout.addView(mWebView);
3.4.2 在 Activity 銷毀( WebView )的時候,先讓 WebView 加載null內容,然后移除 WebView,再銷毀 WebView,最后置空。
@Override
protected void onDestroy() {
if (mWebView != null) {
mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
mWebView.clearHistory();
((ViewGroup) mWebView.getParent()).removeView(mWebView);
mWebView.destroy();
mWebView = null;
}
super.onDestroy();
}
4. 實例
目標:實現顯示“www.baidu.com”、獲取其標題、提示加載開始 & 結束和獲取加載進度
具體實現:
步驟1:添加訪問網絡權限
這是前提!這是前提!這是前提!
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
步驟2:主布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.carson_ho.webview_demo.MainActivity">
<!-- 獲取網站的標題-->
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<!--開始加載提示-->
<TextView
android:id="@+id/text_beginLoading"
android:layout_below="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<!--獲取加載進度-->
<TextView
android:layout_below="@+id/text_beginLoading"
android:id="@+id/text_Loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<!--結束加載提示-->
<TextView
android:layout_below="@+id/text_Loading"
android:id="@+id/text_endLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<!--顯示網頁區域-->
<WebView
android:id="@+id/webView1"
android:layout_below="@+id/text_endLoading"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp" />
</RelativeLayout>
步驟3:根據需要實現的功能從而使用相應的子類及其方法(注釋很清楚了)
MainActivity.java
package com.example.carson_ho.webview_demo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
WebView mWebview;
WebSettings mWebSettings;
TextView beginLoading,endLoading,loading,mtitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebview = (WebView) findViewById(R.id.webView1);
beginLoading = (TextView) findViewById(R.id.text_beginLoading);
endLoading = (TextView) findViewById(R.id.text_endLoading);
loading = (TextView) findViewById(R.id.text_Loading);
mtitle = (TextView) findViewById(R.id.title);
mWebSettings = mWebview.getSettings();
mWebview.loadUrl("http://www.baidu.com/");
//設置不用系統瀏覽器打開,直接顯示在當前Webview
mWebview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
//設置WebChromeClient類
mWebview.setWebChromeClient(new WebChromeClient() {
//獲取網站標題
@Override
public void onReceivedTitle(WebView view, String title) {
System.out.println("標題在這里");
mtitle.setText(title);
}
//獲取加載進度
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress < 100) {
String progress = newProgress + "%";
loading.setText(progress);
} else if (newProgress == 100) {
String progress = newProgress + "%";
loading.setText(progress);
}
}
});
//設置WebViewClient類
mWebview.setWebViewClient(new WebViewClient() {
//設置加載前的函數
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
System.out.println("開始加載了");
beginLoading.setText("開始加載了");
}
//設置結束加載函數
@Override
public void onPageFinished(WebView view, String url) {
endLoading.setText("結束加載了");
}
});
}
//點擊返回上一頁面而不是退出瀏覽器
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
mWebview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
//銷毀Webview
@Override
protected void onDestroy() {
if (mWebview != null) {
mWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
mWebview.clearHistory();
((ViewGroup) mWebview.getParent()).removeView(mWebview);
mWebview.destroy();
mWebview = null;
}
super.onDestroy();
}
}
作者:Carson_Ho
鏈接:http://www.jianshu.com/p/3c94ae673e2a
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。