NotifyManager
package com.zzr.test06.manager; import android.os.Handler; import android.os.Looper; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 更新管理 * Created by Y-bao on 2016/2/16 17:29. */ public class NotifyManager { private static Map<Object, List<OnUpdateListener>> mapMap = new ConcurrentHashMap<>(); public synchronized static void addUpdateListener(Object type, OnUpdateListener onUpdateListener) { List<OnUpdateListener> list; if (!mapMap.containsKey(type)) { list = Collections.synchronizedList(new ArrayList<OnUpdateListener>()); mapMap.put(type, list); } else { list = mapMap.get(type); } if (list.indexOf(onUpdateListener) < 0) { list.add(onUpdateListener); } } public synchronized static void removeUpdateListener(OnUpdateListener onUpdateListener) { for (Object type : mapMap.keySet()) { List<OnUpdateListener> list = mapMap.get(type); if (list == null) { continue; } list.remove(onUpdateListener); if (list.isEmpty()) { mapMap.remove(type); } } } public static void clearUpdateListener(Object type) { List<OnUpdateListener> list = mapMap.remove(type); if (list != null) { list.clear(); } } public static void clearUpdateListener() { for (Object type : mapMap.keySet()) { clearUpdateListener(type); } } public static void notifyUpdate(Object type, Object data) { List<OnUpdateListener> list = mapMap.get(type); if (list == null) { return; } for (OnUpdateListener key : list) { key.onUpdataed(data); } } public static void notifyUpdateToUI(final Object type, final Object data) { if (Looper.getMainLooper() == Looper.myLooper()) { notifyUpdate(type, data); return; } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { notifyUpdate(type, data); } }); } public interface OnUpdateListener { void onUpdataed(Object t); } } 要实时更新的界面:NotifyManager.addUpdateListener(TAG, numUpdateListener);NotifyManager.OnUpdateListener numUpdateListener = new NotifyManager.OnUpdateListener() { @Override public void onUpdataed(Object t) { tvDisplay.setText("num=" + t); } };通知更新的界面:class MyclickListener implements View.OnClickListener { @Override public void onClick(View v) { count++; tv.setText(String.valueOf(count)); NotifyManager.notifyUpdate(MainActivity.TAG, count); } }