Avoid memory leaks with Anonymous Class Handler Timer Task Thread

suggest change

In Android, developers often use an anonymous class, such as a Runnable, at least once in a project. A non-static anonymous class keeps a reference to its outer class (the activity). If the task runs for a long time, the activity cannot be collected until the task ends. This example posts work with a Handler and an anonymous Runnable. The activity leaks if you leave it before the Runnable runs.

new Handler().postDelayed(new Runnable() {
      @Override
      public void run() {
          // do abc long 5s or so
      }
  }, 10000); // run "do abc" after 10s. A Timer or a Thread has the same problem.

How do we solve it?

  1. Do not do long-running work in an anonymous class. Use a static class and pass a WeakReference to the activity or view. A non-static Thread has the same problem as an anonymous class.
  2. Keep the Handler and the Runnable, and call removeCallbacks from onDestroy. Cancel a Timer the same way. The snippet above cannot be cancelled, because it does not keep those references.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents