WebView封装

1. setting设置

WebSettings settings = mWebView.getSettings();

        if (mUrl.startsWith("file://")) {
            settings.setAllowFileAccess(true);
            settings.setJavaScriptEnabled(false);
        } else {
            settings.setAllowFileAccess(false);
            settings.setJavaScriptEnabled(true);
        }
        settings.setAllowFileAccessFromFileURLs(false);
        settings.setAllowUniversalAccessFromFileURLs(false);

        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);

        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setAppCacheEnabled(false);

        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }

        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setScrollbarFadingEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

        //String agent = settings.getUserAgentString() + "; name: " + AppUtils.getAppName(this) + "v" + AppUtils.getVersionName(this);
        //settings.setUserAgentString(settings.getUserAgentString() + "; ****");// 追加自定义标示

        if (mUrl.startsWith("lexuegaokao")) {
            String version = "", client = "";
            try {
                version = URLEncoder.encode(AppUtils.getVersionName(this), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            try {
                client = URLEncoder.encode(Config.APP_HEADER_CLIENT, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            settings.setUserAgentString(AppUtils.getUserAgent() + " " + "lexueApp/" + version + " (Android;" + client + ")");
        }

        mWebView.addJavascriptInterface(new DebugJsInterface(), "justTest");

 

2. 监听

// WebView进度监听
        mWebView.setWebViewClient(new WebViewClient() {

            @SuppressLint("SetJavaScriptEnabled")
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Uri uri = request.getUrl();
                    String host = uri.getHost();
                    String scheme = uri.getScheme();
                    //String method = request.getMethod();
                    //Map map = request.getRequestHeaders();
                    Log.d("ttttt", host + ", " + scheme);

                    if ("file".equals(scheme)) {
                        view.getSettings().setJavaScriptEnabled(false);
                    } else {
                        view.getSettings().setJavaScriptEnabled(true);
                    }
                    // view.loadUrl(request.getUrl().getPath());
                    jumpUrl(uri);
                }
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                mProgressBar.setVisibility(View.VISIBLE);
                mRlReload.setVisibility(View.GONE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                mProgressBar.setVisibility(View.GONE);

                String title = view.getTitle();
                if (!TextUtils.isEmpty(title)) {
                    mHeadBar.setTitle(title);
                }

                // 对于未加载图片的,后加载图片
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (request.isForMainFrame()) {
                        mRlReload.setVisibility(View.VISIBLE);
                    }
                } else {
                    mRlReload.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                ToastManager.getInstance().showToastCenter(getThisActivity(), "http加载失败");
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //接受所有网站的证书
                handler.proceed();
            }
        });

        // 网址进度监听
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (!TextUtils.isEmpty(title)) {
                    mHeadBar.setTitle(title);
                }
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress >= 100) {
                    mProgressBar.setVisibility(View.GONE);
                } else {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                // 网页弹出提示框时触发此方法
                ToastManager.getInstance().showToastCenter(getThisActivity(), "Js弹窗");
                result.cancel();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                // 网页弹出确认框时触发此方法
                result.confirm();
                return true;
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                // 网页弹出输入框时触发此方法
                result.confirm("8848");
                return true;
            }
        });

3. 页面内点击事件重定向

/**
     * 重定向
     *
     * @param uri uri
     */
    private void jumpUrl(Uri uri) {
        if (uri == null) return;

        String page = uri.getQueryParameter("page");
        if (page != null) {
            Intent intent = null;
            switch (page) {
                case "order":
                    intent = new Intent(this, SplashActivity.class);
                    break;
                case "index":
                    intent = new Intent(this, MainActivity.class);
                    break;
                case "login":
                    intent = new Intent(this, DebugWebViewActivity.class);
                    break;
                default:
                    intent = new Intent(this, AppDebugActivity.class);
                    break;
            }
            if (intent != null) {
                startActivity(intent);
            }
        } else {
            Intent intent = new Intent(this, AppDebugActivity.class);
            startActivity(intent);
        }
    }

4. 生命周期处理

@Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
        mWebView.resumeTimers();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
        mWebView.pauseTimers();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearCache(true);
            mWebView.clearHistory();
            mWebView.clearFormData();

            mWebView.removeJavascriptInterface("justTest");

            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.stopLoading();
            mWebView.setWebViewClient(null);
            mWebView.setWebChromeClient(null);

            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }

5. 返回键处理

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

 

你可能感兴趣的:(android,webview,android)