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.