美文网首页android开发
Android Webview 一些积累

Android Webview 一些积累

作者: suniney | 来源:发表于2018-08-27 14:10 被阅读181次

1、Android Webview onPageFinished()加载两次解决办法
在onPageFinished()中进行了一些操作,个别地址会出现加载多次的问题,先解决方法如下

 private boolean isLoading;
 webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                isLoading = true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (isLoading) {
                    isLoading = false;
                    //做些处理
                    return;
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return false;
            }
        });

2、webview长截图

public static Bitmap capture(WebView webView) {
        Picture picture = webView.capturePicture();
        int width = picture.getWidth();
        int height = picture.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        picture.draw(canvas);
        return bitmap;
    }

public void goScreenShotAction() {
                Bitmap longImage = capture(myWebView);
                try {
                    File file = new File(Environment.getExternalStorageDirectory().toString() + Constants.DOWNIMAGES);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    String fileName = file.getAbsolutePath() + "/screenshot" + System.currentTimeMillis() + ".png";
                    FileOutputStream fos = new FileOutputStream(fileName);
                    //压缩bitmap到输出流中
                    longImage.compress(Bitmap.CompressFormat.JPEG, 70, fos);
                    fos.close();
                    Toast.makeText(CommonSearchResultActivity.this, "截屏已保存至SD卡XXX文件夹下", Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    Log.e("", e.getMessage());
                } finally {
                    if (longImage != null) {
                        longImage.recycle();
                    }

                }
            }

3、webview内存泄漏问题

(1)、尽量不在xml布局中 定义Webview,而是在文件中new出来

//传ApplicationContext可以防止webview对activity的引用而造成的内存泄漏;
mWebView=new WebView(getApplicationContext());
LinearLayout linearLayout  = findViewById(R.id.xxx);
linearLayout.addView(mWebView);

(2)、 从源码的角度解决内存泄漏

@Override
protected void onDestroy() {
    if( mWebView!=null) {
    
        ViewParent parent = mWebView.getParent();
        if (parent != null) {
            ((ViewGroup) parent).removeView(mWebView);
        }
        mWebView.stopLoading();
        // 退出时调用此方法,移除绑定的服务,否则某些特定系统会报错
        mWebView.getSettings().setJavaScriptEnabled(false);
        mWebView.clearHistory();
        mWebView.clearView();
        mWebView.removeAllViews();
        mWebView.destroy();

    }
    super.on Destroy();
}

4、404页面拦截处理
Android6.0以下判断404或者500:

 @Override
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);
        // android 6.0 以下通过title获取
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            if (title.contains("404") || title.contains("500") || title.contains("Error")) {
                view.loadUrl("about:blank");// 避免出现默认的错误界面
                view.loadUrl(mErrorUrl);
            }
        }
    }

Android6.0以上判断404或者500:

   @TargetApi(android.os.Build.VERSION_CODES.M)
    @Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);
        // 这个方法在6.0才出现
        int statusCode = errorResponse.getStatusCode();
        System.out.println("onReceivedHttpError code = " + statusCode);
        if (404 == statusCode || 500 == statusCode) {
            view.loadUrl("about:blank");// 避免出现默认的错误界面
            view.loadUrl(mErrorUrl);
        }
    }

判断断网和链接超时

   @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        // 断网或者网络连接超时
        if (errorCode == ERROR_HOST_LOOKUP || errorCode == ERROR_CONNECT || errorCode == ERROR_TIMEOUT) {
            view.loadUrl("about:blank"); // 避免出现默认的错误界面
            view.loadUrl(mErrorUrl);
        }
    }

相关文章

网友评论

    本文标题:Android Webview 一些积累

    本文链接:https://www.haomeiwen.com/subject/yrnziftx.html