LocalBroadcastManager 与 Context 的 registerReceiver / sendBroadcast / unregisterReceiver 方法的区别解析


英文原贴

Q:

I was using Context.registerReceiver(), Context.sendBroadcast(Intent), and Context.unregisterReceiver()
but when I saw the class LocalBroadcastManager, it has registerReceiver(), sendBroadcast(Intent), and unregisterReceiver()
like in Context.
I’m confused. When should I use the LocalBroadcastManager? are they same in Context?
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 the Context class, such as Activity.
  • 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:本博文作用翻译记录,以便查阅。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值