Broadcast receiver working even after app is killed by user

纵然是瞬间 提交于 2021-02-18 15:30:11

问题


I have a BroadcastReceiver that checks for network connection declared statically as:

<receiver
            android:name=".core.util.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

Network change receiver does something like:

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

    String status = NetworkUtil.getConnectivityStatusString(context);

    if(status == "Not connected to Internet") {
        Intent i = new Intent(context, Dialog.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

}

The problem is that when I manually kill my app and turn off network (airplane mode), the Dialogue activity launches. How is this possible? Is my broadcast receiver still alive in the background?

Question:

is there a way for me to unregister my broadcast receiver once the application is killed? maybe in the application singleton class of Android?

If it is not possible in Application class, do I have to manually unregister it everywhere in onStop()? and register it in onStart() in every activity?


回答1:


You expect that registering and unregistering BroadcastReceiver on every activity。 I think the application class is the best solution。 there is a function in Application class which named registerActivityLifecycleCallbacks(), you can watch your activities lifecycle callback in real time.




回答2:


How is this possible?

You registered for the broadcast in the manifest. If a matching broadcast is sent out, your app will respond. If needed, Android will fork a process for you, if your app is not running at the time.

(at least until Android O is released, but that is a story for another time)

is there a way for me to unregister my broadcast receiver once the application is killed?

You need to decide the period of time you want to receive this broadcast:

  • If it is while some particular activity is in the foreground, use registerReceiver() instead of the manifest, registering for the broadcast in the activity's onStart() method and unregistering in onStop()

  • If it is while some particular service is running, use registerReceiver() in the service's onCreate() and unregisterReceiver() in onDestroy()



来源:https://stackoverflow.com/questions/43106086/broadcast-receiver-working-even-after-app-is-killed-by-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!