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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mIntentFilter = new IntentFilter(); mReceiver = new CommonReceiver(); mCallbacks = new HashMap<String, List<OnActionResponse>>(); } @Override protected void onPause() { unregisterReceiver(mReceiver); super.onPause(); } @Override protected 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 { // 子类收到广播后的逻辑 @Override public 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
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 。。。。。。 addBrodcastAction(); 。。。。。。 }
2.3 实现addBrodcastAction
private void addBrodcastAction() { // add Action1 addCanReceiveAction(new Intent(Action1), new OnActionResponse() { @Override public void onResponse(Intent intent) { //处理action1 }); // add Action2 addCanReceiveAction(new Intent(Action2), new OnActionResponse() { @Override public void onResponse(Intent intent) { //处理action2 }); }
这种结构的利弊,欢迎大家的评论。。。