和通过数据进行交互类似,监听回调模式除去了数据作为中间层,而直接在客户端中向框架传入监听,框架处理完事件后,通过回调通知客户端。
监听集合
通过一个SparseArray来存储监听
private SparseArray<OnNavigationStateChangeListener> mOnNavigationStateChangeListenerGroup = new SparseArray<OnNavigationStateChangeListener>();
客户端传入监听
doTask会触发具体的业务,然后通过回调回传给客户端
public void startNavigation(float endX, float endY, float endAngle, OnNavigationStateChangeListener mOnNavigationStateChangeListener) {
registerOnNavigationStateChangeListener(mOnNavigationStateChangeListener, true);
doTask();
}
存储注册的监听
public void registerOnNavigationStateChangeListener(OnNavigationStateChangeListener mOnNavigationStateChangeListener, boolean isNeedClean) {
if (mOnNavigationStateChangeListener != null) {
mOnNavigationStateChangeListenerGroup.append(mOnNavigationStateChangeListenerGroup.size(), mOnNavigationStateChangeListener);
}
}
回传客户端
//在特定的位置 调用集合中的监听 将结果回传客户端
for (int i = 0; i < navigationStateChangeListenerSize; i++) {
OnNavigationStateChangeListener mOnNavigationStateChangeListener = mOnNavigationStateChangeListenerGroup.valueAt(i);
if (mOnNavigationStateChangeListener != null)
mOnNavigationStateChangeListener.onNavigationStart();
}
取消注册的监听
/**
* 取消注册导航下位机命令
*/
public void unRegisterOnNavigationStateChangeListener(OnNavigationStateChangeListener mOnNavigationStateChangeListener) {
int size = mOnNavigationStateChangeListenerGroup.size();
for (int i = 0; i < size; i++) {
OnNavigationStateChangeListener onNavigationStateChangeListener = mOnNavigationStateChangeListenerGroup.valueAt(i);
if (onNavigationStateChangeListener.equals(mOnNavigationStateChangeListener)) {
mOnNavigationStateChangeListenerGroup.removeAt(i);
break;
}
}
}
网友评论