application 进程被系统杀死后,为何不能接受broadcast?

想监听手机网络变化,已在AndroidManifest中注册<intent-filter>,

<receiver android:name=".receiver.NetworkStateReceiver">
            <intent-filter>
                <action android:name="android.net.wifi.STATE_CHANGE"/>
            </intent-filter>
</receiver>

但是在android studio中可以看到,应用进程在后台被系统自动终结后,就再也不能收到网络变化的广播了,这是怎么回事?

阅读 10.5k
2 个回答

我针对三个action做了测试:

android.net.wifi.WIFI_STATE_CHANGED
android.net.wifi.STATE_CHANGED
android.net.wifi.supplicant.CONNECTION_CHANGE

其中前2个很诡异,有时候甚至收不到,即使app仍在前台。有时候甚至一次收到好几个:

10-28 01:07:50.379: I/StartupReceiver(28646): Received broadcast intent: android.net.wifi.STATE_CHANGE
10-28 01:07:50.969: I/StartupReceiver(28646): Received broadcast intent: android.net.wifi.STATE_CHANGE
10-28 01:07:51.044: I/StartupReceiver(28646): Received broadcast intent: android.net.wifi.STATE_CHANGE

只有第3个很正常,手机上的wifi图标亮、灭的同时,就可以在logcat中看到我在onReceive中打印的消息,杀掉后仍可以收到。

这是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.

这个回答建议用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的这个文档,有说明

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.

1 篇内容引用
推荐问题
宣传栏