Webview内存泄露优化

在项目的开发过程中,发现在访问网页的时候,webview会有内存泄漏。

如何解决呢?

1.首先,正确的选择webView 生成:

生成WebView 有两种:代码动态生成和xml定义webView.

查找了很多资料,得出xml定义webView 容易造成内存泄漏。

1.避免在xml直接写webview控件,这样会引用activity,所以在xml写一个LinearLayout,然后 linearLayout.addView(webView);

webView的new有两中: new WebView(this) 和 new WebView(getApplicationContext());

第二种,发现会有些bug,我觉得还是用第一种。这样并没有完全解决内存泄漏问题.

看上网上不少资料,发现这篇文章对WebView内存泄漏说的较好。

原文地址:http://blog.csdn.net/xygy8860/article/details/53334476?utm_source=itdadao&utm_medium=referral

原文里说的webview引起的内存泄漏主要是因为org.chromium.android_webview.AwContents 类中注册了component callbacks,但是未正常反注册而导致的。

org.chromium.android_webview.AwContents 类中有这两个方法 onAttachedToWindow 和 onDetachedFromWindow;系统会在attach和detach处进行注册和反注册component callback;
在onDetachedFromWindow() 方法的第一行中:

if (isDestroyed()) return;, 

如果 isDestroyed() 返回 true 的话,那么后续的逻辑就不能正常走到,所以就不会执行unregister的操作;我们的activity退出的时候,都会主动调用 WebView.destroy() 方法,这会导致 isDestroyed() 返回 true;destroy()的执行时间又在onDetachedFromWindow之前,所以就会导致不能正常进行unregister()。
然后解决方法就是:让onDetachedFromWindow先走,在主动调用destroy()之前,把webview从它的parent上面移除掉。

在onDestory() 中 

if( mWebView!=null) {

        // 如果先调用destroy()方法,则会命中if (isDestroyed()) return;这一行代码,需要先onDetachedFromWindow(),再
        // destory()
        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();
        mWebView = null;
    }
    super.on Destroy();

补充 :查找了网上资料,new WebView(getApplicationContext()); 存在的bug:

1.原文:http://blog.csdn.net/yaphetzhao/article/details/48521581
        getApplicationContext()也是防止内存溢出,这种方法有一个问题。如果你需要在WebView中打开链接或者你打开的页面带有flash,获得你的WebView想弹出一个dialog,都会导致从ApplicationContext到ActivityContext的强制类型转换错误,从而导致你应用崩溃。这是因为在加载flash的时候,系统会首先把你的WebView作为父控件,然后在该控件上绘制flash,他想找一个Activity的Context来绘制他,但是你传入的是ApplicationContext。然后就崩溃了


2.原文:http://www.cnblogs.com/lostbird/p/5653601.html

        动态生成webview就能避免内存泄漏,可是getApplicationContext()会导致部分机型的webview里面点击超链接会出现异常,程序崩溃,暂时的解决办法是禁止点击,需要重写webview。

猜你喜欢

转载自blog.csdn.net/u012881042/article/details/79613803