标签:
1,分析androidEventbus的注册源代码:
EventBus.getDefault().register(this);
public static EventBus getDefault() { if (sDefaultBus == null) { synchronized (EventBus.class) { if (sDefaultBus == null) { sDefaultBus = new EventBus(); } } } return sDefaultBus; }
1 public void register(Object subscriber) { 2 if (subscriber == null) { 3 return; 4 } 5 synchronized (this) { 6 mMethodHunter.findSubcribeMethods(subscriber); 7 } 8 }
1 /** 2 * the subscriber method hunter, find all of the subscriber‘s methods 3 * annotated with @Subcriber 4 */ 5 SubsciberMethodHunter mMethodHunter =newSubsciberMethodHunter(mSubcriberMap);
1 public void findSubcribeMethods(Object subscriber) { 2 if (mSubcriberMap == null) { 3 throw new NullPointerException("the mSubcriberMap is null. "); 4 } 5 Class<?> clazz = subscriber.getClass(); 6 // 查找类中符合要求的注册方法,直到Object类 7 while (clazz != null && !isSystemCalss(clazz.getName())) { 8 final Method[] allMethods = clazz.getDeclaredMethods(); 9 for (int i = 0; i < allMethods.length; i++) { 10 Method method = allMethods[i]; 11 // 根据注解来解析函数 12 Subscriber annotation = method.getAnnotation(Subscriber.class); 13 if (annotation != null) { 14 // 获取方法参数 15 Class<?>[] paramsTypeClass = method.getParameterTypes(); 16 // 订阅函数只支持一个参数 17 if (paramsTypeClass != null && paramsTypeClass.length == 1) { 18 Class<?> paramType = convertType(paramsTypeClass[0]); 19 EventType eventType = new EventType(paramType, annotation.tag()); 20 TargetMethod subscribeMethod = new TargetMethod(method, eventType, 21 annotation.mode()); 22 subscibe(eventType, subscribeMethod, subscriber); 23 } 24 } 25 } // end for 26 // 获取父类,以继续查找父类中符合要求的方法 27 clazz = clazz.getSuperclass(); 28 } 29 }
/** * the event bus‘s subscriber‘s map */ Map<EventType, CopyOnWriteArrayList<Subscription>> mSubcriberMap;
1 /** 2 * 按照EventType存储订阅者列表,这里的EventType就是事件类型,一个事件对应0到多个订阅者. 3 * 4 * @param event 事件 5 * @param method 订阅方法对象 6 * @param subscriber 订阅者 7 */ 8 private void subscibe(EventType event, TargetMethod method, Object subscriber) { 9 CopyOnWriteArrayList<Subscription> subscriptionLists = mSubcriberMap.get(event); 10 if (subscriptionLists == null) { 11 subscriptionLists = new CopyOnWriteArrayList<Subscription>(); 12 } 13 Subscription newSubscription = new Subscription(subscriber, method); 14 if (subscriptionLists.contains(newSubscription)) { 15 return; 16 } 17 subscriptionLists.add(newSubscription); 18 // 将事件类型key和订阅者信息存储到map中 19 mSubcriberMap.put(event, subscriptionLists); 20 }
标签:
原文地址:http://www.cnblogs.com/androidsuperman/p/4679447.html