android tutorial - Avoid memory leaks with anonymous class handler timer task thread in android | Developer android - android app development - android studio - android app developement
Avoid memory leaks with anonymous class handler timer task thread in android
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.
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.