Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

EventBus 源碼分析

編輯:關於 Android 程式設計

先上 GitHub 地址:eventbus

Eventbus 是什麼,能做什麼

Eventbus 是 Android 中的事件總線框架,用於在 App 內不同模塊之間傳遞消息。簡單地說,就是某個地方發送一個「廣播」,在注冊了該廣播的地方就能收到它(在對應的函數中被回調)。

怎麼使用?

1. 創建一個類,這個類對應一類事件(相當於廣播中意圖過濾器裡的條件):

 class MyEvent{} // 代表一類事件。 即一類的廣播。

2. 在需要接收事件的類中進行注冊(對應地,要在該類銷毀時進行注銷):

 EventBus.getDefault().register(this);// 注冊該類為接受者 EventBus.getDefault().unregister(this);// 注銷該類。

3. 在注冊的類中,添加對應的接收事件函數,例如:

 public void onEvent(MyEvent event) { // TODO 在接收到該事件時,我們要進行的相應處理。 }

4. 發送一個事件,也可以理解為發送一個廣播:

 EventBus.getDefault().post(new MyEvent());// 發送的MyEvent對象,會被注冊了該事件的方法中得到回調。

簡單的用法就是這些。下面我們從它暴露給我們的接口出發,一步步看源碼。

EventBus 源碼解析

先看 getDefault 方法:

 // 這裡可以看到一個典型的創建的單例 public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; }

這是一個典型的雙重檢查鎖單例。再看 EventBus 的構造函數:

 EventBus(EventBusBuilder builder) { subscriptionsByEventType = new HashMap, CopyOnWriteArrayList>();// key 為所有Event的class,value為 注冊了該event的所有類。 typesBySubscriber = new HashMap

接著看 register(Object subscriber) 方法,它會調用一個內部方法:

 //subscriber 為注冊的類,sticky 是否是粘性事件,priority為優先級 ,會影響存入map的順序,進而影響回調的順序。 private synchronized void register(Object subscriber, boolean sticky, int priority) { List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass()); for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod, sticky, priority); } }

首先,它調用了 SubscriberMethodFinder 的 findSubscriberMethods 方法。這個方法做的事情,就是把訂閱了事件的類中所有 onEvent 回調函數返回出來。

 List findSubscriberMethods(Class subscriberClass) { String key = subscriberClass.getName(); List subscriberMethods; synchronized (methodCache) { subscriberMethods = methodCache.get(key);// methodCache 為一個static變量,注冊的類為key,以該類中所有注冊函數的list為value,相當於一級緩存。將所有的注冊類中的注冊方法保存下來。避免多次遍歷類中方法的操作。 } if (subscriberMethods != null) { return subscriberMethods; // 如果已經處理過該類,直接使用緩存下來的數據返回。 } subscriberMethods = new ArrayList(); Class clazz = subscriberClass; HashSet eventTypesFound = new HashSet(); // 保存已經添加的方法和該方法的參數拼接的字符串,用於防止重復添加。 StringBuilder methodKeyBuilder = new StringBuilder(); while (clazz != null) { // 循環遍歷該類,以及其父類 String name = clazz.getName(); //忽略掉系統中的類 if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) { // Skip system classes, this just degrades performance break; } // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again) Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { String methodName = method.getName(); if (methodName.startsWith(ON_EVENT_METHOD_NAME)) { // 以OnEvent開始的方法 int modifiers = method.getModifiers(); if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { //訪問修飾符判斷 public且非Ignone方法 Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) {// 只有一個參數的方法 String modifierString = methodName.substring(ON_EVENT_METHOD_NAME.length()); ThreadMode threadMode; if (modifierString.length() == 0) { threadMode = ThreadMode.PostThread; } else if (modifierString.equals("MainThread")) { threadMode = ThreadMode.MainThread; } else if (modifierString.equals("BackgroundThread")) { threadMode = ThreadMode.BackgroundThread; } else if (modifierString.equals("Async")) { threadMode = ThreadMode.Async; } else { if (skipMethodVerificationForClasses.containsKey(clazz)) { continue; } else { throw new EventBusException("Illegal onEvent method, check for typos: " + method); } } Class eventType = parameterTypes[0]; methodKeyBuilder.setLength(0); methodKeyBuilder.append(methodName); methodKeyBuilder.append('>').append(eventType.getName()); String methodKey = methodKeyBuilder.toString(); if (eventTypesFound.add(methodKey)) { // Only add if not already found in a sub class SubscriberMethod類為封裝了一個類中接收函數信息的封裝類。其中包含了方法method、該方法需要回調的線程threadmode、對應的事件類型eventtype。 subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType)); } } } else if (!skipMethodVerificationForClasses.containsKey(clazz)) { Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "." + methodName); } } } clazz = clazz.getSuperclass(); // 獲取父類的class,繼續循環 } if (subscriberMethods.isEmpty()) { throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called " + ON_EVENT_METHOD_NAME); } else { synchronized (methodCache) { methodCache.put(key, subscriberMethods);//將該類中的所有對應的響應方法的集合緩存下來。 } return subscriberMethods; } }

其中 SubscriberMethod 類封裝了一個類中接收函數的信息,包含方法 method、該方法需要回調的線程 threadMode、對應的事件類型 eventType。有了這個方法集合後,接著遍歷集合,調用 subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) 方法。它的主要功能,是把 EventBus 構造函數中創建的 subscriptionsByEventType、typesBySubscriber 和 stickyEvents 這三個集合填充上對應數據。

 private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) { Class eventType = subscriberMethod.eventType; // 事件的對應的class CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType); // 先從集合中獲取以前保存的。 Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);// subscription 類為對接受事件的類的包裝類,裡面包含 subscribe r 就是我們register(Object o)時傳入的this。一般就是activity或fragment。subscribermethod 就是該類中的onevent方法的封裝,priority if (subscriptions == null) {//如果為空,代表第一次處理該event。創建list,並且將list添加到subscriptionsByEventType中。 subscriptions = new CopyOnWriteArrayList(); subscriptionsByEventType.put(eventType, subscriptions); } else { if (subscriptions.contains(newSubscription)) { throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType); } } // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again) //將newSubscription按照優先級添加到中。 int size = subscriptions.size(); for (int i = 0; i <= size; i++) { if (i == size || newSubscription.priority > subscriptions.get(i).priority) { subscriptions.add(i, newSubscription); break; } }// 到此,subscriptionsByEventType這個集合填充完畢。 List> subscribedEvents = typesBySubscriber.get(subscriber);//同樣的,先將這個類中之前event.class的集合取出。 if (subscribedEvents == null) { // 如果為空,代表是第一次,創建list集合,並且將其放到typesBySubscriber這個map中 subscribedEvents = new ArrayList>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType);// 將event加到剛才創建的list中。 if (sticky) { // 是否是粘性事件。如果不是的話,register方法到此就結束了。如果是注冊的是粘性事件監聽,就會在注冊的時候,執行以下代碼。 Object stickyEvent; synchronized (stickyEvents) { stickyEvent = stickyEvents.get(eventType); // 該集合中的stickyEvent是在postSticky(Object o)的時候,添加到集合中的。所以所謂的粘性事件就是在這類 注冊粘性事件監聽之前,就已經被post過的事件,在注冊的時候會被直接調用,並將之前的Object作為參數傳入。 } if (stickyEvent != null) { // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state) // --> Strange corner case, which we don't take care of here. postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper()); // 這裡是post粘性事件。該方法是post事件的核心方 法。之後在分析post模塊的時候,會繼續分析。 } } }

至此,我們走完了整個 register 流程。回顧一下,注冊最主要做的事情,就是把注冊的類(比如 Activity)中對應的 onEvent 回調函數(比如 onEvent(MyEvent myevent))及其參數,通過自定義的包裝類保存到相應集合中(subscriptionsByEventType、typesBySubscriber)。

post 事件的實現

接下來看看 post 一個事件是如何實現的:

 public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get();//獲得在和該線程有關的postingState對象。 List

先看 PostingThreadState 這個類,它是 EventBus 的內部類,主要保存事件的一些信息,就是一個 bean 對象。這裡需要特別關注 currentPostingThreadState 這個對象,它是 ThreadLocal 的實例。ThreadLocal 可以理解為一個在不同線程中保存數據的容器:比如你在主線程中添加一條數據,又在子線程中添加一條數據,那麼在主線程中 get 時拿到的是你在主線程保存的數據,在子線程中 get 時拿到的則是你在子線程保存的數據。至於具體實現,用到了一些很巧妙的算法,有興趣的同學可以自己深入研究。

再看 postSingleEvent(Object event, PostingThreadState postingState) 方法:

 private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { Class eventClass = event.getClass(); // event對應的class boolean subscriptionFound = false; if (eventInheritance) { // 代表是否將event的父類,也進行處理。 List> eventTypes = lookupAllEventTypes(eventClass); // 在該方法中,通過循環,將eventClass的所有父類找到並且返回出來。 int countTypes = eventTypes.size(); for (int h = 0; h < countTypes; h++) { Class clazz = eventTypes.get(h); subscriptionFound |= postSingleEventForEventType(event, postingState, clazz); } } else { subscriptionFound = postSingleEventForEventType(event, postingState, eventClass); } }

它會調用 postSingleEventForEventType 方法,返回的 boolean 代表是否存在對應的注冊者類:

 private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) { CopyOnWriteArrayList subscriptions; synchronized (this) { // 這裡我們看到,我們通過eventClass從subscriptionsByEventType中拿到我們之間在注冊的時候添加進去的該event的所對應的注冊者的集合。 subscriptions = subscriptionsByEventType.get(eventClass); } if (subscriptions != null && !subscriptions.isEmpty()) { for (Subscription subscription : subscriptions) {// 遍歷該event 所有的注冊者 postingState.event = event; postingState.subscription = subscription; boolean aborted = false; // 將信息保存到postingState對象中 try { postToSubscription(subscription, event, postingState.isMainThread); aborted = postingState.canceled; } finally { postingState.event = null; postingState.subscription = null; postingState.canceled = false; } if (aborted) { break; } } return true; } return false; }

接著調用 postToSubscription 方法。這個方法之前也遇到過——在 register 時,對於粘性事件我們調用它。現在就來看看它到底做了什麼:

 private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case PostThread: invokeSubscriber(subscription, event); break; case MainThread: if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(subscription, event); } break; case BackgroundThread: if (isMainThread) { backgroundPoster.enqueue(subscription, event); } else { invokeSubscriber(subscription, event); } break; case Async: asyncPoster.enqueue(subscription, event); break; default: throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode); } }

可以看到,它主要通過區分 subscription.subscriberMethod.threadMode 的類型,以及當前方法所處的線程(也就是 post 方法調用時的線程),來調用不同方法。這裡主要有四種方式:一種是 invokeSubscriber(subscription, event)(其實最終調用的都是這個方法,只是在後三種中是在不同線程中調用而已),代表在當前線程中調用;第二種 mainThreadPoster.enqueue(subscription, event),在主線程中調用;第三種 backgroundPoster.enqueue(subscription, event),會在子線程中調用,而且該線程維護了一個隊列,依次處理所有加入的數據;第四種 asyncPoster.enqueue(subscription, event),會開辟新的子線程在其中執行。

正如前面所說,最終調用的都是 invokeSubscriber(Subscription subscription, Object event) 這個方法,只是通過在不同線程中調用,來實現不同線程的回調:

 void invokeSubscriber(Subscription subscription, Object event) { subscription.subscriberMethod.method.invoke(subscription.subscriber, event); // 實現功能的就是該方法,通過反射調用該方法。 ....... }

那如何在不同線程中調用這個方法呢?如果還記得的話,我們在 EventBus 的構造函數中曾經創建過 mainThreadPoster、backgroundPoster、asyncPoster 三個對象,它們分別對應不同線程。

先看 mainThreadPoster,它其實就是一個 Handler,而且是主線程中的 Handler,所以其 handleMessage 方法會在主線程中執行。首先調用 enqueue(Subscription subscription, Object event) 方法。

先看 PendingPost 類,它也是一個封裝 event 和 subscription 的類,但不同的是,它包含一個 pendingPostPool 存儲集合,裡面添加的是之前創建過的 PendingPost 對象,作用是復用舊對象、減少對象創建的開銷:

 static void releasePendingPost(PendingPost pendingPost) { pendingPost.event = null; pendingPost.subscription = null; pendingPost.next = null; // 將使用完畢的PendingPost中的數據清空 synchronized (pendingPostPool) { // Don't let the pool grow indefinitely if (pendingPostPool.size() < 10000) { pendingPostPool.add(pendingPost); 添加到集合中 } } }

需要新的 PendingPost 對象時:

 static PendingPost obtainPendingPost(Subscription subscription, Object event) { synchronized (pendingPostPool) { int size = pendingPostPool.size(); if (size > 0) { //如果集合中有不用的PendingPost,將其取出,並且將對應的數據添加到其中。 PendingPost pendingPost = pendingPostPool.remove(size - 1); pendingPost.event = event; pendingPost.subscription = subscription; pendingPost.next = null; return pendingPost; } } return new PendingPost(event, subscription); }

回到 enqueue 方法:

 void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); // 獲得封裝了subscription和event的pendingpost對象 synchronized (this) { queue.enqueue(pendingPost); // 將其添加到自己定義的隊列中 if (!handlerActive) { handlerActive = true; if (!sendMessage(obtainMessage())) { // 調用sendmessage方法發送一個空消息,會調用handler的handlemessage方法中。 throw new EventBusException("Could not send handler message"); } } } }

然後來到 handleMessage 方法:

 public void handleMessage(Message msg) { boolean rescheduled = false; try { long started = SystemClock.uptimeMillis(); //獲取系統時間,相當於進入循環是的時間,因為我們看到下面是一個死循環,會用這個時間做一個限制。 while (true) { PendingPost pendingPost = queue.poll(); //從隊列中取出在enqueue中添加的數據。 if (pendingPost == null) { synchronized (this) { // Check again, this time in synchronized pendingPost = queue.poll(); if (pendingPost == null) { handlerActive = false; return; } } } // 以上部分是為了判斷隊列是否為空的考慮線程安全的方法。 eventBus.invokeSubscriber(pendingPost); // 這裡,就是實現真正功能的代碼。我們看到,它又回到了EventBus類中,只不過,它是在主線程中調用的。因為這是在主線程的handler的handlemessage方法中。 long timeInMethod = SystemClock.uptimeMillis() - started; //又獲取了一次系統時間,通過時間差,來控制循環。(當隊列中數據好多時,才會用到) if (timeInMethod >= maxMillisInsideHandleMessage) { if (!sendMessage(obtainMessage())) { //如果此次循環已經超過規定時間,發送一個消息,會重新調用handlemessage方法。 throw new EventBusException("Could not send handler message"); } rescheduled = true; return; } } } finally { handlerActive = rescheduled; } }

再回到 EventBus 看看 invokeSubscriber 方法:

 void invokeSubscriber(PendingPost pendingPost) { Object event = pendingPost.event; Subscription subscription = pendingPost.subscription; // 將封裝在PendingPost中的數據取出來。 PendingPost.releasePendingPost(pendingPost);// 會將PendingPost對象中的數據清空,放到其內部的集合中,以便將來再用。 if (subscription.active) { invokeSubscriber(subscription, event);// 該方法,以前已經分析過了,就是通過反射回調到相應的方法中,完成post的實現。 } }

至此,我們看完了在主線程中實現回調的過程。對於 BackgroundPoster 和 AsyncPoster,其實現是類似的,唯一的區別是它們實現了 Runnable 接口,運行在子線程中——同樣先把數據添加到一個隊列,再在其 run 方法中調用 eventBus.invokeSubscriber(pendingPost)。這兩者的區別在於:一個線程安全,一個線程不安全。

至此,post 方法也分析完畢了。至於 unregister() 方法,如果前面的內容都看懂了,那它就很好理解了——把之前 register 時保存到集合中的數據刪除掉即可,這裡就不再贅述。相信大家可以輕松看懂。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved