WebView memory leak

无人久伴 提交于 2020-01-05 02:34:48

问题


Sorry if this is some kind of duplicate question. I googled for about an hour but still have problems with the memory usage of the WebView component.

I'm starting an Activity (NewsDetail) from a ListActivity to display a specific news article. The HTML-Code of the article is added into the WebView which is included in the Activity layout. (it also loads 1 or 2 images via newsDetail.loadDataWithBaseURL())

I'm starting the article Activity via:

Intent i = new Intent(getApplicationContext(), NewsDetail.class);  
i.putExtra("position", position);
startActivity(i);

After reading this question, I changed my Layout so that I add the WebView programmatically:

newsDetail = new WebView(getApplicationContext());

In my onDestroy method is set:

public void onDestroy(){
    super.onDestroy();
    newsDetail.destroy();
    newsDetail = null;
    finish();
    System.gc();
}

After a while, the Garbage Collector reduce the amount of memory from about 4 MB to 2 MB. If I open/close several news articles it rises to a critical heap size. :/

As mentioned, after destroying the activity, there's a rest of 2 MB left to the activity (which doesn't exist if I completely remove the WebView from the code). So it seems to have sth to do with the WebView itself. The same problem is mentioned here.

I also set:

android:noHistory="true"

Has anyone of you an idea how to completely get rid of memory usage of the "NewsDetail" Activity after returning to my ListActivity? Would be glad to hear any ideas, this is driving me crazy. Is there a chart for Android phones providing more than 16 MB heap size?


回答1:


I think its a known bug. Please refer to this official http://code.google.com/p/android/issues/detail?id=2137

you can refer to this link to let one know that this is a known issue or such




回答2:


There is a mParent reference which points to the ViewGroup that contains the WebView and eventually to your Activity. WebView leaks anything it can get its hands on, so you have to remove it from the view hierarchy.

See my answer here:

Memory leak in WebView




回答3:


If your onDestroy is located in the newsDetail activity, it's kind of weird code. First you do super.onDestroy() which should do what you want so the object is flagged for GC. But in the line after you reference the same object. I'm no expert but that might cause troubles.

If the onDestroy method is inside your listActivity, it makes sense that it doesn't work because the method is never called as the listActivity stays open while other newsDetails are opened.



来源:https://stackoverflow.com/questions/5299693/webview-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!