Each Handler
has a Looper
, and a Looper
is associated with a Thread
(usually a HandlerThread
). The general problem is when a Handler
becomes associated with thread that stops running. If someone tries to use the Handler
, it will fail with the message "sending message to a Handler on a dead thread".
If you just do new Handler()
it becomes associated with the current thread (rather, it becomes associated with the Looper
associated w/ the current thread). If you do this on a thread that that stops (such as the worker thread for an IntentService
) you'll have the issue. The problem of course isn't limited to this root cause, it can happen in any number of ways.
Any easy fix is to construct your Handler
like,
Handler h = new Handler(Looper.getMainLooper());
This associates the Handler
with the main looper, or the main application thread which will never die (good for things like callbacks, but not for any blocking work obviously). Another more complex fix is to create a dedicated thread for the Handler
,
HandlerThread ht = new HandlerThread(getClass().getName());
ht.start();
Handler handler = new Handler(ht.getLooper());
Note that you need to explicitly quit()
the HandlerThread
when you are done with the associated Handler
.
Follow