BroadcastReceiver的一些注意点
在Android的API中,对于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.
大概意思是说,一个BroadcastReceiver对象,只有在调用onReceive的期间是有效的。一旦该函数返回了,那么系统就会认为该对象不再活跃。
既然已经不活跃了,那么系统完全可以在onReceive中的异步操作完成前就杀掉他的进程。
这也就说明了,如果监听到了某事件,新开一个线程去完成某些事情是错误的做法,因为系统完全可以在异步操作完成之前杀掉他。
正确的做法应该是使用Context.startService()去发送一个命令给service,让service去做这件事情。