最近在開發平闆項目,完全是fragmentactivity+fragment的結構。看起來似乎簡單,但是和以前不同的是,業務邏輯非常複雜,多處的非正常跳轉,
fragment之間的資料交換,一處更新多處更新等操作,有時玩起來都心塞。項目背景介紹完畢。
現在有這樣一個場景,項目需求是,背景可配置功能,也就是說app端所有的功能都是背景配置上去的動态生成,對應的功能界面如下圖。

左邊是功能索引,根據背景配置動态生成,右邊每個功能對應的界面。已經實作的是左邊使用fragment,右邊也是fragment,
點選不同的功能号切換到不同的功能界面。現在在1.1fragment中,有一個按鈕點選需要實作
1)跳轉到功能号為2的功能界面,
2)同時左邊的功能号對應的也需要切換過來。
需求1)通過回調可以實作,而需求2)簡單點實作是通過發從程式内廣播實作。
下面主要介紹下程式内廣播。 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).相比較全局廣播,它不需要發送給整個系統,是以更加高效。
2. 使用方式
廣播注冊:
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);否則您接收不到廣播,不要怪政府哈。
謝謝。上面的需求實作也歡迎各位童鞋多給意見和建議。