BroadcastReceiver在调用onReceive时候才会有效,一旦这个函数返回后,即可仍为是停止,而且只有在下一次监听后才重新被调用,因此在该类中保存的变量信息只能在本次调用中被使用,不会保存到下一次调用。所以,想要在该类中保存变量,只能通过其他方式进行。
下面是BroadcastReceiver的生命周期的说明:
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.