1.定义callback类:
public abstract class AppCallback {
public abstract void startCallback();
}
2.在触发callback函数的地方定义:
private static AppCallback mClearAll = null;
并且定义注册和移除callback的方法:
public static void registerCallback(AppCallback callback, int callBackId) {
if (callBackId == AppConstants.ID_CALL_BACK_OK) {
mFilterOk = callback;
} else if (callBackId == AppConstants.ID_CALL_BACK_CANCEL) {
mFilterCancel = callback;
} else if (callBackId == AppConstants.ID_CALL_CLEAR) {
mClearAll = callback;
}
}
public static void removeCallback(AppCallback callback) { mClearAll = null; mFilterOk = null; mFilterCancel = null; } 触发事件中调用callback函数: if (mClearAll != null) { mClearAll.startCallback(); } 3.callback内的事务处理(一般和第二步不在一个类(activity)里面,否则也不用使用callback): 首先在onResume中注册callback: public void onResume() { mShaker.resume(); ResultPageOption.registerCallback(updateWithFilter, AppConstants.ID_CALL_BACK_OK); ResultPageOption.registerCallback(updateWithFilter, AppConstants.ID_CALL_CLEAR); ResultPageOption.registerCallback(filterCancel, AppConstants.ID_CALL_BACK_CANCEL); super.onResume(); } 然后再onDestroy中销毁callback: public void onDestroy() { super.onDestroy(); ResultPageOption.removeCallback(updateWithFilter); } 最后实现callback内要做什么: private AppCallback updateWithFilter = new AppCallback(){ @Override public void startCallback() { clearAll();//要做的事 } };