1、内存泄漏的原因
2、如何避免
- 方式一:不在
xml
中定义 Webview
,这样会引用 Activity
,而是在需要的时候在 Activity
中创建,并且使用 getApplicationgContext()
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
mWebView = new WebView(getApplicationContext());
mWebView.setLayoutParams(params);
mLayout.addView(mWebView);
- 方式二:
Activity
关闭时需要手动释放 Webview
内存 - 在
Activity
销毁(WebView)的时候,先让 Webview
加载 null 内容,然后移除 Webview
,再销毁 Webview
,最后置空。
@Override
protected void onDestroy() {
if (mWebView != null) {
mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
mWebView.clearHistory();
((ViewGroup) mWebView.getParent()).removeView(mWebView);
mWebView.destroy();
mWebView = null;
}
super.onDestroy();
}
- 方式三:在承载
WebView
的 Activity
中,单开一个进程去处理。但是这里要牵扯到进程之间的通信。
3、参考资料