Android的 - 什么时候注册/注销广播接收一个活动产生的?什么时候、Android

2023-09-12 01:50:56 作者:怪你过分美丽i

我有一个需要在活动的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

为了清楚起见,这是的code我用

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 s是对当前活动使用的事件,在某种程度上,通知事件的用户。如果的onPause()已被调用,则活动不再在前台,并因此着更新的用户

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 onPause() 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.

像康斯坦丁说,的onDestroy()不能保证被调用,您可以继续接收广播很长一段时间,当活动已不再是开放的。

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.