Avoid memory leaks with Anonymous Class Handler Timer Task Thread
suggest changeIn 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() {
@Override
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?
- Dont do any long operating with
Anonymous Classor we need aStatic classfor it and passWeakReferenceinto it (such as activity, view…).Threadis the same withAnonymous Class. - Cancel the
Handler,Timerwhen activity is destroyed.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents