Handler收不到消息分析

本文探讨了在开机广播中向Handler发送消息后无法接收到的问题。原因是BroadcastReceiver生命周期短暂,一旦onReceive()方法执行完毕,应用进程可能被系统回收。解决方法包括使用AlarmManager替代或配合Service保持进程活跃。

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

前一段时间碰到一个这样的需求,监听开机广播,后给Handler发送一个延迟15s后收到的消息。当时接到这个需求的时候很简单。直接在开机广播中给Handler发送一个message嘛。写完代码测试的时候发现这个message没有收到,通过日志发现这个消息确实发出去了,当时想了很久没想到。仔细分析了下日志后发现

应用进程被系统干掉了...干掉了.

猜想可能是在发出消息后一段时间,应用没有执行任务,导致系统认为此进程为空闲进程,进行会回收此进程。

查询了官方文档后验证了我的想法

Receiver Lifecycle

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.

This has important repercussions to what you can do in an onReceive(Context, Intent) implementation: anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

In particular, you may not show a dialog or bind to a service from within a BroadcastReceiver. For the former, you should instead use theNotificationManager API. For the latter, you can use Context.startService() to send a command to the service.

Process Lifecycle

A process that is currently executing a BroadcastReceiver (that is, currently running the code in its onReceive(Context, Intent) method) is considered to be a foreground process and will be kept running by the system except under cases of extreme memory pressure.

Once you return from onReceive(), the BroadcastReceiver is no longer active, and its hosting process is only as important as any other application components that are running in it. This is especially important because if that process was only hosting the BroadcastReceiver (a common case for applications that the user has never or not recently interacted with), then upon returning from onReceive() the system will consider its process to be empty and aggressively kill it so that resources are available for other more important processes.

This means that for longer-running operations you will often use a Service in conjunction with a BroadcastReceiver to keep the containing process active for the entire time of your operation.

文档建议不要在onreceive中做耗时操作,因为这个方法返回后就代表这个广播对象is no longer active。推荐使用notificationManager或者service来处理耗时认为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值