Avoid memory leaks with Anonymous Class Handler Timer Task Thread
suggest changeIn 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?
- Do not do long-running work in an anonymous class. Use a static class and pass a
WeakReferenceto the activity or view. A non-staticThreadhas the same problem as an anonymous class. - Keep the
Handlerand theRunnable, and callremoveCallbacksfromonDestroy. Cancel aTimerthe same way. The snippet above cannot be cancelled, because it does not keep those references.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents