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?
您希望在每个活动上注册和取消注册BroadcastReceiver
。我认为应用程序类是最好的解决方案Application
类中有一个名为registerActivityLifecycleCallbacks ()的函数,您可以实时查看您的活动生命周期回调。
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.