Handler programming issues
The
Handler
class is truly fundamental to the Android platform and is used widely throughout, but there are plenty of ways we can get ourselves into trouble if we aren't careful.
Leaking implicit references
The biggest worry when using Handler
within an Activity
is resource leakage which, just as with AsyncTask
, is very easy to do. Here's one of our earlier examples:
final Runnable runnable = new Runnable(){ public void run() { // … do some work } }; handler.postDelayed(runnable, TimeUnit.SECONDS.toMillis(10));
By declaring an anonymous inner Runnable
inside an activity, we have made an implicit reference to that containing Activity
instance. We've then posted the Runnable
to a handler and told it to execute in 10 seconds time.
If the Activity
finishes before the 10 seconds are up, it cannot yet be garbage collected because the implicit reference in our Runnable
means that the Activity
is still reachable by live objects.
So, although it makes for a concise...