sending message to a Handler on a dead thread

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.

Share

Follow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值