想监听手机网络变化,已在AndroidManifest中注册<intent-filter>,
<receiver android:name=".receiver.NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
但是在android studio中可以看到,应用进程在后台被系统自动终结后,就再也不能收到网络变化的广播了,这是怎么回事?
我针对三个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的这个文档,有说明