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
本文探讨了如何避免Handler在关联的线程停止时抛出错误,提供了解决方案,包括使用mainLooper与创建专用HandlerThread。重点介绍了两种修复方法:一是通过Handler.getMainLooper()确保与主线程关联,二是创建独立线程并管理其生命周期。
4万+






