Search code examples
javaandroidandroid-studioservicebroadcastreceiver

Broadcast receiver working even after app is killed by user


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?


Solution

  • 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.