即使应用被用户杀死,广播接收器仍能正常工作 [英] Broadcast receiver working even after app is killed by user

查看:65
本文介绍了即使应用被用户杀死,广播接收器仍能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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.

这篇关于即使应用被用户杀死,广播接收器仍能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆