android 在基類activity中註冊BroadcastReceiver,子activity類實現響應

來源:互聯網
上載者:User

android app 一般都會定義自己的BaseActivity, 如果各子Activity都需要接收廣播但對廣播的處理又不同時,可以考慮在BaseActivity中註冊BroadcastReceiver,而在子類中實現各自的響應邏輯,現將代碼架構羅列如下:

1.定義自己的activity基類

public class BaseActivity extends FragmentActivity {private static final String TAG = "BaseActivity";private BroadcastReceiver mReceiver;private IntentFilter mIntentFilter;        // 用來記錄需要處理的action和響應函數private Map<String, List<OnActionResponse>> mCallbacks;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mIntentFilter = new IntentFilter();mReceiver = new CommonReceiver();mCallbacks = new HashMap<String, List<OnActionResponse>>();}@Overrideprotected void onPause() {unregisterReceiver(mReceiver);super.onPause();}@Overrideprotected void onResume() {registerReceiver(mReceiver, mIntentFilter);super.onResume();}            //子類調用該方法,註冊所要處理的廣播action/** * if subclass need response BroadcastReceiver, need invoke this method to * add can Receive Action *  * @param intent * @param callback */public void addCanReceiveAction(Intent intent, OnActionResponse callback) {final String action = intent.getAction();if (!mIntentFilter.hasAction(action)) {mIntentFilter.addAction(action);registerReceiver(mReceiver, mIntentFilter);}if (!mCallbacks.containsKey(action)) {mCallbacks.put(action, Collections.synchronizedList(new ArrayList<OnActionResponse>()));}mCallbacks.get(action).add(callback);intent.putExtra(Constants.EXTRA_ACTION_CALLBACK_HASH_CODE, callback.hashCode());}private class CommonReceiver extends BroadcastReceiver {                                // 子類收到廣播後的邏輯@Overridepublic void onReceive(Context context, Intent intent) {Log.d(TAG, "CommonReceiver receiver intent:" + intent.getAction());final String action = intent.getAction();if (mCallbacks != null && mCallbacks.containsKey(action)) {int hashCode = intent.getIntExtra(Constants.EXTRA_ACTION_CALLBACK_HASH_CODE, -1);List<OnActionResponse> list = mCallbacks.get(action);if (list != null) {int index = -1;int count = list.size();for (int i = 0; i < count; i++) {if (hashCode == list.get(i).hashCode()) {index = i;break;}}if (index >= 0) {list.get(index).onResponse(intent);} else {list.get(count - 1).onResponse(intent);}if (list.isEmpty()) {mCallbacks.remove(action);}}}}}                //子類具體實現處理邏輯protected interface OnActionResponse {void onResponse(Intent intent);}}

 2.在子類中的使用

2.1 首先需要繼承基類

public class A extends BaseActivity

 2.2 子類的onCreate中添加要處理的action,例如:addBrodcastAction是為了統一管理該activity可以處理的action

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);                。。。。。。addBrodcastAction();                。。。。。。}

 2.3 實現addBrodcastAction

      private void addBrodcastAction() {// add Action1addCanReceiveAction(new Intent(Action1), new OnActionResponse() {@Overridepublic void onResponse(Intent intent) {//處理action1});// add Action2addCanReceiveAction(new Intent(Action2), new OnActionResponse() {@Overridepublic void onResponse(Intent intent) {//處理action2});}

 這種結構的利弊,歡迎大家的評論。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.