何时注册/注销活动中创建的广播接收器? [英] When to Register/Unregister Broadcast Receivers created in an activity?

查看:76
本文介绍了何时注册/注销活动中创建的广播接收器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在活动的onCreate事件中创建自定义广播接收器,显然我需要在活动的onDestroy事件中取消注册广播接收器

I have a need to create a custom broadcast receiver in the onCreate event of an activity and obviously I need to unRegister the broadcast receiver in the onDestroy event of the activity

为清楚起见,这是我使用的代码的一个片段

For clarity this is a snippet of the code I use

public class AnActivity extends Activity {
    private ResponseReceiver receiver;

    public class ResponseReceiver extends BroadcastReceiver {
           public static final String ACTION_RESP =
              "mypackagename.intent.action.MESSAGE_PROCESSED";

           @Override
            public void onReceive(Context context, Intent intent) {
// TODO Start a dialogue if message indicates successfully posted to server
            }
    }   

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new ResponseReceiver();
        registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

我已经阅读到该活动的onPause/onResume和onStart/onStop事件也应该注册和注销广播接收器.

I have read that onPause/onResume and onStart/onStop events for the activity should also register and unregister the broadcast receiver.

我真的很想了解什么是最佳实践,以及为什么.

I'm really wanting to understand what is considered to be the best practice for this and why.

推荐答案

您应该注册和取消注册接收者onStart()onStop().

You should register and unregister your receivers onStart() and onStop().

活动注册BroadcastReceiver的唯一原因是在当前活动上以某种方式使用事件,以将事件通知用户.如果已调用onStop(),则Activity不再在前台,因此无法更新用户.

The only reason an Activity would register BroadcastReceivers is to use the events in some way on the current activity, to inform the User of an event. If onStop() has been called, then the Activity is no longer in the foreground, and therefore cant update the User.

如果您想在后台接收广播事件,则应考虑使用指示的服务

If you want to receive broadcast events in the background you should consider using a service as indicated here.

就像康斯坦丁(Konstantin)所说,不能保证呼叫onDestroy(),并且当Activity不再打开时,您可以长时间接收广播.

Like Konstantin says, onDestroy() is not guaranteed to be called, and you could continue receiving broadcasts for a long time, when the Activity is no longer open.

这篇关于何时注册/注销活动中创建的广播接收器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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