这是stackoverflow上的一个回答:android.net.wifi.STATE_CHANGE: not triggered on Wifi disconnect
In android's API it says that it's not a good idea to check STATE_CHANGE for network connectivity and instead you should use SUPPLICANT_CONNECTION_CHANGE_ACTION. this will notice an establishment to a wifi network, and the disconnection of a wifi network.
Note that the system adds FLAG_EXCLUDE_STOPPED_PACKAGES to all broadcast intents. It does this to prevent broadcasts from background services from inadvertently or unnecessarily launching components of stoppped applications. A background service or application can override this behavior by adding the FLAG_INCLUDE_STOPPED_PACKAGES flag to broadcast intents that should be allowed to activate stopped applications.
我针对三个action做了测试:
其中前2个很诡异,有时候甚至收不到,即使app仍在前台。有时候甚至一次收到好几个:
只有第3个很正常,手机上的wifi图标亮、灭的同时,就可以在logcat中看到我在
onReceive中打印的消息,杀掉后仍可以收到。这是stackoverflow上的一个回答:android.net.wifi.STATE_CHANGE: not triggered on Wifi disconnect
这个回答建议用
SUPPLICANT_CONNECTION_CHANGE_ACTION代替STATE_CHANGE,来检查wifi的连接状态。不过这个回答也没有给出收不到broadcast的解释。自android 3.1开始,系统自动给所有intent添加了FLAG_EXCLUDE_STOPPED_PACKAGES,导致app处于停止状态就不能收到广播。要想处于停止状态的app收到广播,需要添加FLAG_INCLUDE_STOPPED_PACKAGES这个标记。这样的话,停止的app应该是收不到系统广播了。
另外,我是在alarmmanager中发送延时广播,在测试中发现,不仅需要添加FLAG_INCLUDE_STOPPED_PACKAGES,在构建intent的时候还需要添加receiver的类名才能接受到广播。
看google的这个文档,有说明