Android Memory Leaks edit

Avoid memory leaks with Anonymous Class Handler Timer Task Thread

In android, every developer uses Anonymous Class (Runnable) at least once in a project. Any Anonymous Class has a reference to its parent (activity). If we perform a long-running task, the parent activity will not be destroyed until the task is ended. Example uses handler and Anonymous Runnable class. The memory will be leak when we quit the activity before the Runnable is finished.

new Handler().postDelayed(new Runnable() {
      public void run() {
          // do abc long 5s or so
  }, 10000); // run "do abc" after 10s. It same as timer, thread...

How do we solve it?

  1. Dont do any long operating with Anonymous Class or we need a Static class for it and pass WeakReference into it (such as activity, view…). Thread is the same with Anonymous Class.
  2. Cancel the Handler, Timer when activity is destroyed.

Feedback about page:

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

Table Of Contents
64 Menu
69 Memory Leaks
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close