【Android】WebView

AndroidManifest.xml

允许程序打开网络套接字
<uses-permission android:name="android.permission.INTERNET" />
网络状态
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
存储读写
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

WebViewActivity

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

public class WebViewActivity extends Activity {

    private WebView webView;
    private ProgressBar kfProgress; //进度条
    private static ProgressDialog proDialog; //加载提示框
    private long exitTime = 0; //时间
    private static String urlString = "http://www.hao123.com";
    private static String urlErrorString = "http://www.baudu.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        proDialog = android.app.ProgressDialog.show(this, "提示", "网页加载中");
        webViewInit(); //初始化web浏览器
    }

    private void webViewInit(){
        webView = (WebView) findViewById(R.id.kfWebView);
        kfProgress = (ProgressBar)findViewById(R.id.kfProgressBar);

        /*** 设置属性 ***/
        WebSettings settings = webView.getSettings();
        settings.setUseWideViewPort(true);//设定支持viewport
        settings.setLoadWithOverviewMode(true);//自适应屏幕
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        settings.setSupportZoom(true);//设定支持缩放
        settings.setDisplayZoomControls(false);//缩放控件隐藏
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setJavaScriptEnabled(true); //设置WebView属性,运行执行js脚本
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE); //不使用缓存,只从网络获取数据
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setAllowFileAccess(true); //设置可以访问文件

        webView.setWebViewClient(new WebViewClient() {
            //设置在webView点击打开的新网页在当前界面显示,而不跳转到新的浏览器中
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
            //错误处理
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                webView.loadUrl(urlErrorString);
            }
            //webView加载完成
            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
                if (proDialog != null){
                    proDialog.dismiss();
                    proDialog = null;
                }
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            //监听网页加载
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if(newProgress==100){
                    kfProgress.setVisibility(View.GONE);//加载完网页进度条消失
                }
                else{
                    kfProgress.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    kfProgress.setProgress(newProgress);//设置进度值
                }
            }
        });

        /*** 监听下载 ***/
        webView.setDownloadListener(new DownloadListener(){
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,String mimetype, long contentLength) {
                Toast.makeText(getApplicationContext(), "开始下载",
                        Toast.LENGTH_SHORT).show();
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                startActivity(intent);
            }
        });

        /*** JS交互 ***/
        webView.addJavascriptInterface(new JSBridge(),"JSObj");

        /*** 调用loadUrl方法为WebView加入链接 ***/
        webView.loadUrl(urlString);
    }

    /***
     * 当用户点击回退按钮
     */
    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            //判断网页是否能后退
            webView.goBack();
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出浏览器",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                super.onBackPressed();
            }
        }
    }

    /**
     * js交互类
     */
    public class JSBridge{
        @JavascriptInterface
        public void openApp(String message) {

        }
    }
}

activity_web_view.xml 布局

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_web_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebViewActivity"
    android:orientation="vertical">
<ProgressBar
    android:id="@+id/kfProgressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="3dip"
    android:progressDrawable="@drawable/pg"
    android:visibility="gone" />
<WebView
    android:id="@+id/kfWebView"
    android:layout_below="@id/kfProgressBar"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Layout>

pg.xml 进度条设置

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="2dp" />
            <gradient
                android:angle="270"
                android:centerColor="#E3E3E3"
                android:endColor="#E6E6E6"
                android:startColor="#C8C8C8" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="2dp" />
                <gradient
                    android:centerColor="#4AEA2F"
                    android:endColor="#31CE15"
                    android:startColor="#5FEC46" />
            </shape>
        </clip>
    </item>
</layer-list>

推荐阅读更多精彩内容