Android中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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章