Android Webview工具类

public class BaseWebView extends WebView {
    protected static boolean DISABLE_SSL_CHECK_FOR_TESTING = false;
    private LoadingDialog mLoadingDialog;
    private boolean mShowLoading;
    private ResultResolve mResultResolve;
    private String mTitle;



    public BaseWebView(Context context) {
        super(context);
        initSetting();
        initWebViewClient();
        initWebChromeClient();

    }

    public BaseWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initSetting();
        initWebViewClient();
        initWebChromeClient();

    }

    public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initSetting();
        initWebViewClient();
        initWebChromeClient();

    }

    private void initSetting() {
        //声明WebSettings子类
        WebSettings webSettings = this.getSettings();
        //如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
       //设置自适应屏幕,两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
       //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
    }


    private void initWebViewClient() {
        this.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.i("webview url = "+url);

                if(url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                      //  mShowLoading = false;
                        getContext().startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(getContext())
                                .setMessage("未检测到支付宝客户端,请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        getContext().startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                }else if(url.startsWith("weixin:") ){

                    try {
                       // mShowLoading = false;
                        getContext().startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(getContext())
                                .setMessage("未检测到微信客户端,请安装后重试。").setNegativeButton("确定", null).show();
                    }
                    return true;
                }else if(url.startsWith("mc-sdk:")){
                    if(mResultResolve != null){
                        mResultResolve.handle(url);
                    }


                }else if(url.contains("wx.tenpay.com")){
                    LogUtil.i("外部浏览器:"+url);
                    return super.shouldOverrideUrlLoading(view, url);

                }else{
                    //内部浏览器打开网页
                    //mShowLoading = true;
                    view.loadUrl(url);

                }



                return true;
            }
			//网页开始加载
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if(mShowLoading){
                    LoadingDialog.Builder builder = new LoadingDialog.Builder(getContext());
                    mLoadingDialog = builder.create();
                    mLoadingDialog.show();
                }

            }
			//网页加载完毕
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if(mLoadingDialog !=null && mLoadingDialog.isShowing()){
                    mLoadingDialog.dismiss();
                }

            }
			//https验证错误,还继续加载网页
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                if(mLoadingDialog !=null && mLoadingDialog.isShowing()){
                    mLoadingDialog.dismiss();
                }
                if (DISABLE_SSL_CHECK_FOR_TESTING) {
                    handler.cancel();
                } else {
                    handler.proceed();
                }
            }
        });
    }


    private void initWebChromeClient() {
        this.setWebChromeClient(new WebChromeClient(){
			//获取网页标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mTitle = title;
                LogUtil.i("webview title = "+title);
                EventBus.getDefault().post(new TitleEvent(mTitle));

            }
			//获取网页加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });


    }

    public boolean isShowLoading() {
        return mShowLoading;
    }

    public void setShowLoading(boolean mShowLoading) {
        this.mShowLoading = mShowLoading;
    }

    public String getTitle() {
        return mTitle;
    }

    public void setTitle(String mTitle) {
        this.mTitle = mTitle;
    }

    public ResultResolve getResultResolve() {
        return mResultResolve;
    }

    public void setResultResolve(ResultResolve resultResolve) {
        this.mResultResolve = resultResolve;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && this.canGoBack()) {
            this.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public interface ResultResolve{
        void handle(String url);

    }

    public void onDestory(){
		//清除网页缓存
        this.clearHistory();
        this.clearCache(true);
        this.loadUrl("about:blank");
        this.pauseTimers();
        this.stopLoading();
        this.destroy();

    }


}
发布了36 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43278826/article/details/88656215
今日推荐