1

我正在BroadcastReceiver将 Manifest 中定义的一些 s 迁移到LocalBroadcastManager.

这些BroadcastReceivers 不需要从其他应用程序调用。它们通过sendBroadcast()Activitys 调用以响应 UI 操作,或者从执行 HTTP 请求并在Intent.

我最近才发现LocalBroadcastManager并想优化我的代码。我没有做任何基准测试(我不确定如何做)。值得做还是过早的优化?s 被调用以响应用户操作,BroadcastReceiver因此迁移可能不值得。

应该在哪里registerReceiver注册?是Application正确的地方吗?

4

1 回答 1

1

registerReceiver注册应该在哪里完成?

它们应该由负责其工作的任何组件注册。

主要LocalBroadcastManager用于组件间通信。典型的例子是IntentService发送本地广播Intent,让任何感兴趣的活动知道发生了一些变化……当且仅当前台有这样的活动。在这种情况下,活动将在 中注册接收者onResume()并在 中取消注册该接收者onPause()

因此,让我们看一下您的两个简单描述的“用例”:

来自 Activity 以响应 UI 操作

删除sendBroadcast(). 删除BroadcastReceiver. 只需在这里完成工作,或者 fork anAsyncTask来完成工作,或者IntentService通过startService().

from a utility class that executes HTTP requests and delivers the responses in the Intent.

Either this "utility class" is being use by an activity (via an AsyncTask), an IntentService, or neither.

If the utility class is being used by an AsyncTask from an activity, dump the sendBroadcast(), dump the BroadcastReceiver, and simply do the work in the AsyncTask and/or activity.

If the utility class is being used by an IntentService, and you are trying to update the UI based upon that work, that's the pattern I outlined in my second paragraph of my answer.

于 2012-06-09T14:44:20.413 回答