您的位置:首页 > 移动开发 > Android开发

Android中LocalBroadcastManager的使用

2015-07-17 11:23 591 查看
先聊聊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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: