sending message to a Handler on a dead thread

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值