英文原贴
Q:
I was using
Context.registerReceiver(), Context.sendBroadcast(Intent), and Context.unregisterReceiver()
but when I saw the classLocalBroadcastManager
, it hasregisterReceiver(), sendBroadcast(Intent), and unregisterReceiver()
like inContext
.
I’m confused. When should I use theLocalBroadcastManager
? are they same inContext
?
Regards,
Thanks…
A:
LocalBroadcastManager is as its name says, an implementation of the broadcast methods that are only available to your app. This has some benefits, with the biggest being safety, one less hole to watch out for. In terms of implementation, there are a few things to keep in mind:
- This class is from the Android Support Library
- The method calls have to be prefaced with
LocalBroadcastManager.getInstance([CONTEXT])
where[CONTEXT]
is a subclass of theContext
class, such asActivity
.- When you use this class, it is purely for your app. Using it to register receivers and make broadcasts that are system wide will fail.
So this class is not the same as Context, it is simply a very specific, app-only implementation of Context’s receiver/broadcast methods. You should use it when there is absolutely no point for your listener to listen on global (system-wide) broadcasts and when your broadcast does not need to target anything outside your app.
中文释义
A:
正如其名称所示,LocalBroadcastManager是一种仅适用于您的应用程序的广播方法的实现。
这有一些好处,最重要的是安全性,少一个值得关注的漏洞。 在实施方面,有几点需要注意:
- 这个类来自Android支持库
- 方法调用必须以
LocalBroadcastManager.getInstance([CONTEXT])
开头,其中[CONTEXT]
是Context
类的子类,例如Activity
。- 当你使用这个类时,它纯粹适用于您的应用程序。 使用它来注册接收器并进行系统范围的广播将会失败。
因此,这个类与Context不同,它只是Context的接收器/广播方法的一个非常特定的、仅用于应用程序的实现。如果您的接收器完全没有必要监听全局(系统范围)广播时,以及您的广播不需要针对应用程序之外的任何内容时,您应该使用它。
原文地址:stackoverflow
PS:本博文作用翻译记录,以便查阅。