当前位置: 代码迷 >> Android >> BroadcastReceiver的生命周期有关问题
  详细解决方案

BroadcastReceiver的生命周期有关问题

热度:79   发布时间:2016-05-01 13:25:15.0
BroadcastReceiver的生命周期问题
1、动态注册与静态注册的区别?静态注册是常驻内存的意思吗?
2、内存不足时,BroadcastReceiver会被系统回收掉吗?如何避免?

------解决方案--------------------
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 the NotificationManager 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.


You can find the answer from http://developer.android.com and find it by yourself.
and ultrapro's answer is not right.
  相关解决方案