android - 何时注册/取消注册在 Activity 中创建的广播接收器?

标签 android broadcastreceiver

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

为清楚起见,这是我使用的代码 fragment

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);
    }

我已经读到, Activity 的 onPause/onResume 和 onStart/onStop 事件也应该注册和取消注册广播接收器。

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

最佳答案

您应该注册和注销您的接收器 onStart()onStop()

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

如果您想在后台接收广播事件,您应该考虑使用 here 所示的服务.

正如 Konstantin 所说,onDestroy() 不能保证被调用,当 Activity 不再打开时,您可以继续接收广播很长一段时间。

关于android - 何时注册/取消注册在 Activity 中创建的广播接收器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7887169/

相关文章:

android - 新手 : How to change tab font size?

Android 将 <String> 设置为数组

android - Android BroadcastReceiver和后台Activity的最佳实践是什么?

Android 将数据从 Activity 传递到 BroadcastReceiver 显示 null

android - 暂停或停止 fragment 后未显示键盘

android - Linux中拦截文件打开事件

android - 没有shell cp命令复制系统文件

android - Android SDK 管理器中损坏的内置工具(缺少 aapt.exe)

java - 带有 BroadcastReceiver 的 AsyncTask 中的 onPostExecute 抛出空指针异常

java - 如何提取动态广播的 Intent