最近开始使用leakCanary为app进行内存泄露的检测
遇到了webview.mContext导致activity内存泄露
(不过在android 6.0的机子上没有遇到这样的问题)
经过搜索,在http://bugly.qq.com/bbs/forum.php?mod=viewthread&tid=516 里找到了原因
面对这样的问题,我们暂时可以通过在layout中放置webview的地方用framelayout代替
<FrameLayout
android:id="@+id/webview_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>再动态将新建的webview加进framelayout中
frameLayout = (FrameLayout) findViewById(R.id.webview_container);
webView = new WebView(getApplicationContext());
frameLayout.addView(webView);在activity onDestroy的时候将webview与activity解除关联,我们可以从文档看出原因
webview 的destroy文档
/**
* Destroys the internal state of this WebView. This method should be called
* after this WebView has been removed from the view system. No other
* methods may be called on this WebView after destroy.
*/
public void destroy() {
checkThread();
mProvider.destroy();
}mProvider(WebviewProvider)的destroy文档
/**
* See {@link WebView#destroy()}.
* As well as releasing the internal state and resources held by the implementation,
* the provider should null all references it holds on the WebView proxy class, and ensure
* no further method calls are made to it.
*/
public void destroy();
使用LeakCanary检测到WebView的mContext引起Activity内存泄露,该问题在Android 6.0设备上未出现。解决方案是用FrameLayout替换WebView在布局中的位置,然后动态添加WebView并调用其destroy方法来防止内存泄露。

3577

被折叠的 条评论
为什么被折叠?



