问题
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'sonStart()
method and unregistering inonStop()
If it is while some particular service is running, use
registerReceiver()
in the service'sonCreate()
andunregisterReceiver()
inonDestroy()
来源:https://stackoverflow.com/questions/43106086/broadcast-receiver-working-even-after-app-is-killed-by-user