WebView doesn't seem to get destroyed after leaving activity?

Viewed 6519

I've got an activity with a webview. Looks like the webview does not get destroyed along with the activity. To demonstrate, I've created an html page which runs a timer that loads an image resource every few seconds. The script continues executing after the activity is destroyed:

public class MyWebViewActivity extends Activity {
  private WebView mWebView;

  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.the_layout);

    mWebView = (WebView)findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.setWebViewClient(new EmbeddedWebViewClient());
    mWebView.loadUrl("test url");
  }

  private class EmbeddedWebViewClient extends WebViewClient {
    @Override
    public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url);

        if (Config.DEBUG) { Log.v(TAG, "onLoadResource(): " + url); }
    }
  }
}

So the above just prints a log statement whenever onLoadResource() is called. Here's the javascript in the test html page:

<html>
  <head>
    <script type="text/javascript">

      function load() {
        setInterval("doit()", 3000);
      }

      function doit() {
        Image1 = new Image(150, 20);
        Image1.src = "abc_" + Math.floor(Math.random()*100) + ".png";
      }

    </script>
  </head>

  <body onload="load()">
  </body>
</html>

The above just creates an image resource on the timer interval to trigger the onLoadResource() method in EmbeddedWebViewClient().

So yeah I can see in LogCat that the messages keep printing after leaving the activity. Do we have to shut down the WebView somehow? Maybe this is the issue described here:

http://code.google.com/p/android/issues/detail?id=9375

if it's a known issue should it have been documented in the api docs?

Note: Running this on android 2.3.4, Nexus S.

Thanks

5 Answers

This solution worked for me:

In MyActivity.java file, I added:

@Override
protected void onDestroy() {
    webview.destroy();
    webview = null;
    super.onDestroy();
}
Related