即使在应用程序被用户杀死后广播接收器也能工作 [英] Broadcast receiver working even after app is killed by user

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

问题描述

我有一个 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);
    }
}

}

问题是,当我手动终止我的应用程序并关闭网络(飞行模式)时,对话活动会启动.这怎么可能?我的广播接收器在后台还活着吗?

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 类中有一个函数名为 registerActivityLifecycleCallbacks(),您可以实时查看您的 Activity 生命周期回调.

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天全站免登陆