AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent"/> <ProgressBar android:id="@+id/progressbar" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="3dip" android:max="100" android:progress="0" android:visibility="gone"/> </FrameLayout>
MainActivity.java
package cn.litry.win; import android.os.Build; import android.os.Bundle; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.graphics.Bitmap; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.webkit.JavascriptInterface; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.Toast; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MainActivity extends Activity { private WebView webView; private ProgressBar progressBar; private int exitNum =2; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("[T-WebView]", "onCreate"); requestWindowFeature(Window.FEATURE_NO_TITLE);// 不显示title setContentView(R.layout.activity_main); progressBar = (ProgressBar) findViewById(R.id.progressbar);// 进度条 webView = (WebView) findViewById(R.id.webview); // webView.loadUrl("file:///android_asset/test.html");//加载asset文件夹下html webView.loadUrl("http://baidu.com");// 加载url // 使用webview显示html代码 // webView.loadDataWithBaseURL(null,"<html><head><title> 欢迎您 </title></head>"<body><h2>使用webview显示 // html代码</h2></body></html>", "text/html" ,"utf-8", null); webView.addJavascriptInterface(this, "android");// 添加js监听 这样html就能调用客户端 webView.setWebChromeClient(webChromeClient); webView.setWebViewClient(webViewClient); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); // 允许使用js /** * LOAD_CACHE_ONLY: 不使用网络,只读取本地缓存数据 LOAD_DEFAULT: * (默认)根据cache-control决定是否从网络上取数据。 LOAD_NO_CACHE: 不使用缓存,只从网络获取数据. * LOAD_CACHE_ELSE_NETWORK,只要本地有,无论是否过期,或者no-cache,都使用缓存中的数据。 */ webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 不使用缓存,只从网络获取数据. // 支持屏幕缩放 webSettings.setSupportZoom(false); webSettings.setBuiltInZoomControls(false); // 不显示webview缩放按钮 // webSettings.setDisplayZoomControls(true); webSettings.setBuiltInZoomControls(false);// 设置出现缩放工具 webSettings.setUseWideViewPort(false);// 扩大比例的缩放 // webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);// // 自适应屏幕 // webSettings.setLoadWithOverviewMode(true); } // WebViewClient主要帮助WebView处理各种通知、请求事件 private WebViewClient webViewClient = new WebViewClient() { @Override public void onPageFinished(WebView view, String url) {// 页面加载完成 Log.i("[T-WebView]", "onPageFinished: " + url); progressBar.setVisibility(View.GONE); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {// 页面开始加载 Log.i("[T-WebView]", "onPageStarted: " + url); progressBar.setVisibility(View.VISIBLE); // Toast.makeText(MainActivity.this, url,Toast.LENGTH_LONG).show(); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.equals("http://www.google.com/")) { Log.i("[T-WebView]", "shouldOverrideUrlLoading: " + url); Toast.makeText(MainActivity.this, "拦截该url:" + url, Toast.LENGTH_SHORT) .show(); return true;// 表示我已经处理过了 } return super.shouldOverrideUrlLoading(view, url); } @SuppressWarnings("deprecation") @Override public void onReceivedError(WebView view, int errorCode, String description, String url) { super.onReceivedError(view, errorCode, description, url); Log.i("[T-WebView]", "onReceivedError: " + url); Toast.makeText(MainActivity.this, "Code:" + errorCode + " Url:" + url, Toast.LENGTH_SHORT).show(); webView.loadDataWithBaseURL(null, "<html><head><title>Error</title></head><body><h2>页面访问失败,点击<a href="" + url + "">这里</a>重新访问</h2></body></html>", "text/html", "utf-8", null); } }; // WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等 private WebChromeClient webChromeClient = new WebChromeClient() { // 不支持js的alert弹窗,需要自己监听然后通过dialog弹窗 @Override public boolean onJsAlert(WebView webView, String url, String message, JsResult result) { AlertDialog.Builder localBuilder = new AlertDialog.Builder( webView.getContext()); Log.i("[T-WebView]", "onJsAlert" + url); localBuilder.setMessage(message).setPositiveButton("确定", null); localBuilder.setCancelable(false); localBuilder.create().show(); // 注意: // 必须要这一句代码:result.confirm()表示: // 处理结果为确定状态同时唤醒WebCore线程 // 否则不能继续点击按钮 result.confirm(); return true; } // 获取网页标题 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); Log.i("[T-WebView]", "网页标题:" + title); } // 加载进度回调 @Override public void onProgressChanged(WebView view, int newProgress) { progressBar.setProgress(newProgress); } }; public boolean onKeyDown(int keyCode, KeyEvent event) { Log.i("[T-WebView]", "是否有上一个页面:" + webView.canGoBack()); if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {// 点击返回按钮的时候判断有没有上一页 webView.goBack(); // goBack()表示返回webView的上一页面 exitNum = 2; return true; } { exitNum -= 1; Toast.makeText(MainActivity.this, "再按一次返回键推出", Toast.LENGTH_SHORT) .show(); if (exitNum > 0) return false; } return super.onKeyDown(keyCode, event); } /** * JS调用android的方法 * * @param str * @return */ @JavascriptInterface // 仍然必不可少 public void getClient(String str) { Log.i("[T-WebView]", "html调用客户端:" + str); } protected void onDestroy() { super.onDestroy(); // 释放资源 webView.destroy(); webView = null; } }
参考 https://blog.csdn.net/lowprofile_coding/article/details/77928614