Android WebView how to avoid memory leaks

Android WebView how to avoid memory leaks

  • What is a memory leak
    memory leak popular talk is that you create an object, but did not destroy him at the right time, he has spent the presence of memory space in memory.
  • Why WebView memory leak
    some threads inside the webView hold activity objects, resulting in activity can not be released. Then a memory leak.
  • How to solve
    a context not initialized in the layout directly webview, but when you need to dynamically create webview in Activity, and the use Application when creating the webview.

1. Code to create WebView

If it is created by findViewById Xml () loaded webView will always exist, so we can not be destroyed because of the creation webView code in the code as follows

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //创建一个LayoutParams宽高设定为全屏
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        //创建WebView
        mWebView = new WebView(getApplicationContext());
        //设置WebView的宽高
        mWebView.setLayoutParams(layoutParams);
        //把webView添加到容器中
        mLayout.addView(mWebView);
    }

2. Destruction code WebView

We webView to create in code is to facilitate generally destroyed after the code in the Activity be destroyed when the first load WebView Null, and then removed again destroyed webView webView, the last blank, as follows

@Override
protected void onDestroy() {
    if (mWebView != null) {
        //加载null内容
        mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
        //清除历史记录
        mWebView.clearHistory();
        //移除WebView
        ((ViewGroup) mWebView.getParent()).removeView(mWebView);
        //销毁VebView
        mWebView.destroy();
        //WebView置为null
        mWebView = null;
    }
     super.onDestroy();
}

Reference: how to avoid Android WebView memory leak
How to avoid memory leaks webview
Android Development Experience: A memory leak webview

Published 216 original articles · won praise 91 · Views 250,000 +

Guess you like

Origin blog.csdn.net/yu75567218/article/details/102663571