本文转载自http://blog.csdn.net/carson_ho/article/details/52693322
前言
目录
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 WebView的状态
webView.onResume() ;webView.onPause();webView.pauseTimers()webView.resumeTimers();rootLayout.removeView(webView); webView.destroy();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
3.1.2 关于前进 / 后退网页
Webview.canGoBack() Webview.goBack()Webview.canGoForward()Webview.goForward()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.clearCache(true);Webview.clearHistory();Webview.clearFormData();
3.2 常用类
3.2.1 WebSettings类
- 作用:对WebView进行配置和管理
- 配置步骤 & 常见方法:
配置步骤1:添加访问网络权限(AndroidManifest.xml)
这是前提!这是前提!这是前提!
<uses-permission android:name="android.permission.INTERNET"/>
配置步骤2:生成一个WebView组件(有两种方式)
WebView webView = new WebView(this)WebView webview = (WebView) findViewById(R.id.webView1);
配置步骤3:进行配置-利用WebSettings子类(常见方法)
WebSettings webSettings = webView.getSettings();webSettings.setJavaScriptEnabled(true); webSettings.setPluginsEnabled(true); webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); webSettings.setSupportZoom(true); webSettings.setBuiltInZoomControls(true); webSettings.setDisplayZoomControls(false); webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); webSettings.setAllowFileAccess(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); webSettings.setLoadsImagesAutomatically(true); webSettings.setDefaultTextEncodingName("utf-8");
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
常见用法:设置WebView缓存
- 当加载 html 页面时,WebView会在/data/data/包名目录下生成 database 与 cache 两个文件夹
- 请求的 URL记录保存在 WebViewCache.db,而 URL的内容是保存在 WebViewCache 文件夹下
- 是否启用缓存:
WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
if (NetStatusUtil.isConnected(getApplicationContext())) { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);} else { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);}webSettings.setDomStorageEnabled(true); webSettings.setDatabaseEnabled(true); webSettings.setAppCacheEnabled(true);String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;webSettings.setAppCachePath(cacheDirPath);
注意: 每个 Application 只调用一次 WebSettings.setAppCachePath(),WebSettings.setAppCacheMaxSize()
3.2.2 WebViewClient类
常见方法1:shouldOverrideUrlLoading()
- 作用:打开网页时不调用系统浏览器, 而是在本WebView中显示;在网页上的所有加载都经过这个方法,这个函数我们可以做很多操作。
Webview webview = (WebView) findViewById(R.id.webView1); webView.loadUrl("http://www.google.com/"); webView.loadUrl("file:///android_asset/test.html"); webView.loadUrl("content://com.android.htmlfileprovider/sdcard/test.html"); webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } });
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
常见方法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如何加载一个本地的页面
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()
webView默认是不处理https请求的,页面显示空白,需要进行如下设置:
webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } });
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.3 WebView与JS的交互
具体请看我写的文章 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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
步骤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/"); mWebview.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); 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); } } }); 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); } @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(); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
源代码:Carson_Ho的Github-WebviewDemo
5. 总结
- 本文主要对 Android Webview进行了全面介绍
- 关于WebView的系列文章希望对你有所帮助