Android中LocalBroadcastManager的使用

LocalBroadcastManager用于在应用内部发送广播,相比全局广播更安全高效。本文介绍了其优势、使用方式及注意事项。

先聊聊LocalBroadcastManager有啥用:

 1.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).广播只会在你的应用内发送,所以无需担心数据泄露,更加安全。
 2).其他应用无法发广播给你的应用,所以也不用担心你的应用有别人可以利用的安全漏洞
 3).相比较全局广播,它不需要发送给整个系统,所以更加高效。


使用的方式

广播注册:

1 LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
2 IntentFilter filter = new IntentFilter();
3 filter.addAction(ACTION);
4 myBroadcastReciver = new MyBroadcastReciver();
5 localBroadcastManager.registerReceiver(myBroadcastReciver, filter);

广播发送

1 Intent intent = new Intent();
2 intent.setAction(SaleLeftFragment.ACTION);
3 intent.putExtra(TAG, data);
4 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、付费专栏及课程。

余额充值