前一段时间碰到一个这样的需求,监听开机广播,后给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.