среда, 4 декабря 2013 г.

WebView cause memory leak.


WebView problems description:

1. WebView cause memory leak in Android core and high CPU usage if Javascript enabled.

Bug reports on Android bug tracker

How to reproduce?

  • Create test project with WebView
  • Load some URL few times with WebView.loadUrl()
  • see memory leak
Same problem here with example application

Full Solution - not found.

It's official bug.

Solution (not solution, but works)

Disable javascript support at all
webView.setJavaScriptEnabled(false)

Partial solution 1

call the onPause / onResume on the webview to reduce CPU usage
  • CPU usage decreased
  • Memory leak present
code:
Class.forName("android.webkit.WebView").getMethod("onPause", (Class[]) null).invoke(webView, (Object[]) null);
[Detail on Android bug tracker][link 3]

Partial solution 2

  • loadDataWithBaseURL
WebView.loadDataWithBaseURL(url,data,"text/html","UTF-8",url);
Fine for static page, but not for site in Internet.

Partial solution 3

Disable all...
 mWebView.getSettings().setAppCacheEnabled(false);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setDatabaseEnabled(false);
mWebView.getSettings().setDomStorageEnabled(false);
mWebView.getSettings().setGeolocationEnabled(false);
mWebView.getSettings().setPluginsEnabled(false);
mWebView.getSettings().setSaveFormData(false);
mWebView.getSettings().setSavePassword(false);
clean up, destroy, create new WebView
 mWebView.removeAllViews();
mWebView.destroyDrawingCache();
mWebView.clearCache(true);
mWebView.clearHistory();
mWebView.freeMemory();
mWebView.destroy();
mWebView = null;
Memory leak present

2. OutOfMemoryException

See problem 1 and http://stackoverflow.com/questions/6497780/webview-outofmemoryexception

3. WebView causes memory leak - leaks the parent Activity

Starting an activity with a WebView, then destroying that activity (hitting back) and getting a heap dump shows that there are uncleaned up references that cause the activity to stay in memory (leak).
I use a WebView to display some internet content on one of our app's Activities. The problem is that when the user switches out of this activity, WebView's threads keep running!