LocalBroadcastManager 的使用

本文介绍了LocalBroadcastManager的基本概念及其在应用程序内部实现广播通信的优势。它不仅增强了应用安全性,还提高了效率,并提供了具体的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于网上的很多文章感觉介绍的并不好,LocalBroadcastManager和普通的Broadcast还是有一定区别的,下面的感觉总结的还不错,拿来记录一下

LocalBroadcastManager基本介绍 这个类是在v4包中的,谷歌官方的介绍是:

Helper to register for and send broadcasts of Intents to local objects within your process. This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent):

 You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.  It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.  It is more efficient than sending a global broadcast through the system.

1.本人献丑翻译下:
 能够完成在应用内的广播发送,而且比全局广播更具优势:
 1).广播只会在你的应用内发送,所以无需担心数据泄露,更加安全。
 2).其他应用无法发广播给你的应用,所以也不用担心你的应用有别人可以利用的安全漏洞
 3).相比较全局广播,它不需要发送给整个系统,所以更加高效。

2. 使用方式
广播注册:

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION);
myBroadcastReciver = new MyBroadcastReciver();
localBroadcastManager.registerReceiver(myBroadcastReciver, filter);


广播发送

Intent intent = new Intent();
intent.setAction(SaleLeftFragment.ACTION);
intent.putExtra(TAG, data);
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);


 

3.使用注意

在使用的时候,请关注以下几点:

1).LocalBroadcastManager注册广播只能通过代码注册的方式。

2).LocalBroadcastManager注册广播后,一定要记得取消监听。

3).重点的重点,使用LocalBroadcastManager注册的广播,您在发送广播的时候务必使用LocalBroadcastManager.sendBroadcast(intent);否则您接收不到广播,不要怪政府哈。

文章摘要转载自:http://www.cnblogs.com/xilinch/p/4238122.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值