前言
在你們使用很多App時,用過很多種電商平臺,唯品會,淘寶,京東等等,它們都內置了Web網頁(Hypri),
這是我在京東上發現裏面找的,在這裏我要說個小技巧,怎麼分辨一個App哪個是原生的還是h5做的,看看能不能長按點擊複製,這說明它是一個網頁,像這種該如何實現,Android裏有一個叫WebView的組件實現的
目錄
簡介
1.WebView是一個基於webkit引擎,展現web頁面的控件
2.作用 : 與JavaScript交互調用,還有可以直接使用html文件(網絡上或本地assets)作佈局
3.常用方法: 一般來說WebView可單獨使用,可配合子類一起使用,接下來我要介紹:
- Webview自身的常見方法;
- Webview的最常用的子類 (WebSettings類、WebViewClient類、WebChromeClient類)
- Android和Js的交互
常用方法
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();
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);
}
1.3 清除緩存數據
//清除網頁訪問留下的緩存
//由於內核緩存是全局的因此這個方法不僅僅針對webview而是針對整個應用程序.
Webview.clearCache(true);
//清除當前webview訪問的歷史記錄
//只會webview訪問歷史記錄裏的所有記錄除了當前訪問記錄
Webview.clearHistory();
//這個api僅僅清除自動完成填充的表單數據,並不會清除WebView存儲到本地的數據
Webview.clearFormData();
常用類
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);
//支持插件
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()
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); //可做其他處理
}
});
2.3WebChromeClient類
- 作用:輔助 WebView 處理 Javascript 的對話框,網站圖標,網站標題等等。
- 常見使用:
常見方法1):onReceivedSslError()
- 作用:獲得網頁的加載進度並顯示
webView默認是不處理https請求的,頁面顯示空白,需要進行如下設置:
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.1 WebView與JS的交互
具體請查看我寫的文章:博客地址
注意事項:如何避免WebView內存泄漏
第一種:不在xml中定義 Webview ,而是在需要的時候在Activity中創建,並且Context使用 getApplicationgContext()
inearLayout.LayoutParams params = new LinearLayout.LayoutParams
(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mWebView = new WebView(getApplicationContext());
mWebView.setLayoutParams(params);
mLayout.addView(mWebView);
第二種:在 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();
}
使用
接下來步入正題,實現顯示“www.baidu.com”,提示加載開始&結束和獲取加載進度,獲取其標題
步驟1:添加訪問網絡權限
步驟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"
tools:context=".MainActivity">
<!-- 獲取網站的標題-->
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="標題"
android:textSize="20sp" />
<!--進度條-->
<ProgressBar
android:id="@+id/pbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/title" />
<!--開始加載提示-->
<TextView
android:id="@+id/tv_beginLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/pbar"
android:text="" />
<!--獲取加載進度-->
<TextView
android:id="@+id/tv_Loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_beginLoading"
android:text="" />
<!--結束加載提示-->
<TextView
android:id="@+id/tv_endLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_Loading"
android:text="" />
<!--顯示網頁區域-->
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/tv_endLoading"
android:layout_marginTop="5dp" />
</RelativeLayout>
步驟3:根據需要實現的功能從而使用相應的子類及其方法
MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView mWebview;
WebSettings mWebSettings;
TextView beginLoading, endLoading, loading, mtitle;
ProgressBar pbar;
@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.tv_beginLoading);
endLoading = (TextView) findViewById(R.id.tv_endLoading);
loading = (TextView) findViewById(R.id.tv_Loading);
mtitle = (TextView) findViewById(R.id.title);
pbar = (ProgressBar) findViewById(R.id.pbar);
pbar.setMax(100);
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);
pbar.setVisibility(View.GONE);
beginLoading.setVisibility(View.GONE);
}
//設置進度條
pbar.setProgress(newProgress);
}
});
//設置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();
}
}
效果圖: