关于WebView的基本知识可以参考:点击打开链接
WebSettings
管理WebView的状态。
WebView创建时,将会有一个默认的设置。
通过WebView.getSettings()获取。
如果WebView销毁后WebSettings的方法调用将发生异常。
WebSettings的一些设置:
WebSettings mWebViewSettings = mWebView.getSettings();
mWebViewSettings.setJavaScriptEnabled(true);//设置能够执行js脚本
mWebViewSettings.setSupportZoom(true);
mWebViewSettings.setBuiltInZoomControls(true);//支持缩放
// mWebViewSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//优先使用缓存
mWebViewSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存
WebViewClient
帮助WebView处理各种通知、请求事件。
主要的几个方法:
1.在webview中点击跳转url会调用此方法
如果想要自己处理此次跳转,可以返回true。
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
2. 页面开始加载时调用
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
3.页面加载结束
public void onPageFinished(WebView view, String url) {
}
4.页面加载失败,不推荐使用
@Deprecated
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
}
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (request.isForMainFrame()) {
onReceivedError(view,
error.getErrorCode(), error.getDescription().toString(),
request.getUrl().toString());
}
}
WebChromeClient
辅助WebView处理Js的对话框,网站图标,网站title。
主要的几个方法:
1.页面加载进度
public void onProgressChanged(WebView view, int newProgress) {}
2.网页的title
public void onReceivedTitle(WebView view, String title) {}
需要对回退键进行一些处理:
/**
* 默认点回退键,会退出Activity,需监听按键操作,使回退在WebView内发生
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == event.KEYCODE_BACK && mWebView.canGoBack()){
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
loadUrl
1.加载网址:mWebView.loadUrl("http://www.baidu.com");
2.加载javascript:loadUrl("javascript:wave()");
3.加载js获取网页元素,并传递给客户端
//获取title1的内容,并返回给客户端
html1 = "javascript:window.test.callPhone(document.getElementById('title1').innerHTML);";
//后取meta信息,并传递给客户端
html1 = "javascript:window.test.callPhone(document.getElementsByTagName('meta')[0].getAttribute('content'));";
mWebView.loadUrl(html1);
loadData
1.加载html
String html = "加载data数据
";
mWebView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
2.
mWebView.loadData(html1, "text/html", "utf-8");
addJavascriptInterface
此方法用来添加javascript接口,通过name,javascript可以调用object的一些方法(方法需要添加:@JavascriptInterface,并且不能为private)。
public void addJavascriptInterface(Object object, String name) {
checkThread();
mProvider.addJavascriptInterface(object, name);
}
javascript调用java方法的实现:
1.定义一个类,方法需要@javascriptInterface
public class JsFunction {
private Activity ac;
public JsFunction(Activity ac){
this.ac = ac;
}
@JavascriptInterface
protected void showToast(){
Toast.makeText(ac, "通过JS调用了Android方法", Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public void callPhone(String phone){
Toast.makeText(ac, "js传递给android:" + phone, Toast.LENGTH_SHORT).show();
}
}
mWebView.addJavascriptInterface(new JsFunction(this), "test");
点击调用android方法
--------------Demo---------------------
1.main目录下创建assets目录,assets中创建jsdemo.html文件
点击调用android方法
点击调用js方法
点击调用android方法2
package com.test.git.webviewdemo;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private WebView mWebView;
private static final String TAG = "MainActivity";
private View bt_load_web;
private View bt_load_data;
private View bt_load_js;
private ProgressBar mProgressBar;
private View bt_load_call;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView)findViewById(R.id.mWebView);
bt_load_web = findViewById(R.id.bt_load_web);
bt_load_data = findViewById(R.id.bt_load_data);
bt_load_js = findViewById(R.id.bt_load_js);
bt_load_call = findViewById(R.id.bt_load_call);
mProgressBar = (ProgressBar)findViewById(R.id.mProgressBar);
bt_load_web.setOnClickListener(this);
bt_load_data.setOnClickListener(this);
bt_load_js.setOnClickListener(this);
bt_load_call.setOnClickListener(this);
CookieManager cm = CookieManager.getInstance();
cm.removeAllCookie();
cm.removeSessionCookie();
initWeb();
String url = "https://www.baidu.com";
loadUrl(url);
String cookie = cm.getCookie(url);
Log.i(TAG, "cookie:" + cookie);
cm.setCookie(url, "cookie");
cookie = cm.getCookie(url);
Log.i(TAG, "cookie:" + cookie);
}
private void addJsInterface() {
mWebView.addJavascriptInterface(new JsFunction(this), "test");
loadUrl("file:///android_asset/jsdemo.html");
}
private void loadUrl(String url) {
mWebView.loadUrl(url);
}
//初始化webview
private void initWeb() {
WebSettings mWebViewSettings = mWebView.getSettings();
mWebViewSettings.setJavaScriptEnabled(true);//设置能够执行js脚本
mWebViewSettings.setSupportZoom(true);
mWebViewSettings.setBuiltInZoomControls(true);//支持缩放
// mWebViewSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//优先使用缓存
mWebViewSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存
/**
* WebViewClient帮助WebView处理各种通知,请求事件
*/
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "shouldOverrideUrlLoading: " + url);
//截取url,如果是tel则拨打电话
if (url.contains("tel_")) {
String phone = url.split("_")[1];
if (!TextUtils.isEmpty(phone)) {
Uri uri = Uri.parse("tel:" + phone);
Intent intent = new Intent(Intent.ACTION_DIAL, uri);
startActivity(intent);
}
return true;
}
if(url.contains("call")){
Toast.makeText(MainActivity.this, "call", Toast.LENGTH_SHORT).show();
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Log.i(TAG, "onReceivedError: " + error);
mProgressBar.setVisibility(View.GONE);
super.onReceivedError(view, request, error);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.i(TAG, "onReceivedError: errorCode:" + errorCode + " description:" + description + " failingUrl:" + failingUrl);
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i(TAG, "onPageStarted: " + url);
mProgressBar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "onPageFinished: " + url);
mProgressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
});
/**
* WebChromeClient辅助WebView处理Javascript的对话框,网站图标,网站title
*/
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
Log.i(TAG, "onProgressChanged: " + newProgress);
super.onProgressChanged(view, newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
Log.i(TAG, "onReceivedTitle: " + title);
super.onReceivedTitle(view, title);
}
@Override
public void onReceivedIcon(WebView view, Bitmap icon) {
Log.i(TAG, "onReceivedIcon: ");
super.onReceivedIcon(view, icon);
}
@Override
public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
Log.i(TAG, "onReceivedTouchIconUrl: " + url);
super.onReceivedTouchIconUrl(view, url, precomposed);
}
});
}
/**
* 默认点回退键,会退出Activity,需监听按键操作,使回退在WebView内发生
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == event.KEYCODE_BACK && mWebView.canGoBack()){
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.bt_load_web:
addJsInterface();
break;
case R.id.bt_load_data:
String html = "加载data数据
";
mWebView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
break;
case R.id.bt_load_js:
// loadUrl("javascript:wave()");
String html1 = "";
// mWebView.loadDataWithBaseURL(null, html1, "text/html", "utf-8", null);
//获取title1的内容,并返回给客户端
html1 = "javascript:window.test.callPhone(document.getElementById('title1').innerHTML);";
//后取meta信息,并传递给客户端
html1 = "javascript:window.test.callPhone(document.getElementsByTagName('meta')[0].getAttribute('content'));";
mWebView.loadUrl(html1);
// mWebView.loadData(html1, "text/html", "utf-8");
break;
case R.id.bt_load_call:
// loadUrl("http://www.baidu.com/tel_123456");
loadUrl("http://www.baidu.com/call");
break;
}
}
}