Broadcast receiver working even after the application is killed by the user

I have BroadcastReceiver

one that tests the network connection, declared statically like:

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

      

The 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 the application and turn off the network (airplane mode), the Dialog operation starts. How is this possible? Is my broadcast receiver still live in the background?

Question:

Is there a way to unregister my broadcast receiver after the app is killed? maybe in a singleton app an android class?

If this is not possible in the Application class, do you need to manually override it everywhere in onStop()

? and register it onStart()

in every action?

+3


source to share


2 answers


You expect to register and unregister BroadcastReceiver

for every action. I think the application class is the best solution. there is a function in the class Application

called registerActivityLifecycleCallbacks (), you can view your activity lifecycle callback in real time.



+2


source


How is this possible?

You have registered to broadcast in the manifest. If a matching transmission is sent, your app will respond. If necessary, Android will fork the process for you if your application is down at the time.

(at least until the release of Android O, but that's history at a different time)



Is there a way to unregister my broadcast receiver after the app is killed?

You need to define the time period in which you want to receive this broadcast:

  • If a specific activity is in the foreground, use instead the registerReceiver()

    manifest registered for broadcast in the method onStart()

    and unregister inonStop()

  • If it is some specific service, use registerReceiver()

    in the service onCreate()

    and unregisterReceiver()

    inonDestroy()

+2


source







All Articles