即使应用被用户杀死,广播接收器仍能正常工作
我有一个 BroadcastReceiver
,它检查静态声明为的网络连接:
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);
}
}
}
问题在于,当我手动终止我的应用程序并关闭网络(飞行模式)时,启动了Dialogue活动.这怎么可能?我的广播接收器在后台还活着吗?
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?
问题:
应用程序被杀死后,我是否可以注销我的广播接收器?也许在Android的应用程序单例类中?
is there a way for me to unregister my broadcast receiver once the application is killed? maybe in the application singleton class of Android?
如果在Application类中不可能,我是否必须在 onStop()
的所有位置手动注销它?并在每个活动中在 onStart()
中注册它?
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 类是最好的解决方案. Application
类中有一个名为
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.