webview内存泄漏处理

内存泄漏检测工具:Leakcanary

在项目的开发过程中,发现使用webview访问网页后,在onDestory()中调用webview.destory(),webview=null后竟然还会有内存泄漏,然后开始查看日志,如下图:

 

图1由于使用回调,在onDestory()中mWebListener=null就解决了。图2就不知道什么问题了,在网上查找到几个方法:

1、进程

为加载WebView的界面开启新进程,在该页面退出之后关闭这个进程。这个方法试了一下,内存泄漏问题是解决了,但是

Application会初始化2次,导致webview页面启动慢。

2、别人说是有用,不过我怎么试都没有用,以为是加了回调方法的问题,不过去除回调后还是无效,只能弃用。

@Override
protected void onDestroy() {
    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();

    }
    super.on Destroy();
}

 3、代码中创建webview(亲测有用)

布局中使用

<FrameLayout
    android:id="@+id/webview_contain"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

然后在代码中把创建的webview添加到FrameLayout中(也可使用其他可addView的布局)

mWebContainer.addView(webView);

最后

@Override
protected void onDestroy() {
    if (webView != null) {
        webView.removeAllViews();
        webView.destroy();
        webView = null;
        mWebContainer.removeView(webView);
    }
    super.onDestroy();
}

猜你喜欢

转载自blog.csdn.net/CHEN_ZL0125/article/details/99589515