Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

11
  • 8
    @Reek No, GC should take care of it. But you need to take care of the runnable posted for delayed execution. In the example above the runnable used is an inner class instance so holds an implicit reference to the containing class (which might be an activity). The runnable will stay in the handler's associated looper's message queue until its next execution time which may be after the context is invalid and might leak the containing class instance. You can clear such references by using mHandler.removeCallbacks(runnableCode) at the appropriate time (e.g. onStop() for an activity). Commented May 23, 2017 at 6:36
  • 11
    Best way of presenting references ever!!! (see here, here, here, here, here, and here). Commented Jan 24, 2018 at 23:21
  • and what if I want to use that inside a ViewModel? isn't against the ideal of not having android things there? Commented Mar 6, 2019 at 15:04
  • @desgraci, I haven't used a ViewModel, but from the documentation I only see that it says the ViewModel shouldn't access the view hierarchy or contain a reference to the Activity or Fragment. I don't see anything forbidding having "Android things" in general. Commented Mar 6, 2019 at 16:28
  • As of today those references are to me outdated and not informative enough to be taken into consideration. Those 4 listed drawbacks are only real if you programm your code badly. TimerTasks are still a very good choice if you want to periodically run something in the background and eventually run something on the UIThread if some condition applies. Commented Oct 15, 2019 at 15:26