編輯:關於 Android 程式設計
上一篇我們走過了 EventBus 的基本用法,這次深入源碼,看看「事件總線」四個字背後到底做了什麼。開始之前先補一塊前置知識。
定義:反射是指在運行時,對於任意一個類都能獲知其所有屬性與方法,對於任意一個對象都能調用其任意方法與屬性。這種動態獲取信息、動態調用對象方法的能力,就是反射機制。
核心類: java.lang.Class、java.lang.reflect.Constructor、Field、Method、Modifier。
常用方法:
getDeclaredMethods():獲取所有已聲明的方法getDeclaredMethod(名稱, 參數類型...):獲取指定方法getFields():返回所有公有屬性getDeclaredField(名稱):獲取指定屬性標準三步:拿到目標類的 Class 對象 → 拿到要調用的 Method → 調用 invoke()。
Class cls = Class.forName("chb.test.reflect.Student");
Method m = cls.getDeclaredMethod("toString", int.class, String.class);
m.invoke(cls.newInstance(), 20, "chb");
EventBus 的觀察者方法共有四種,都以 onEvent 開頭,差別在於運行線程:

兩個基礎概念:EventBus.post() 負責發布事件;上述四種方法負責接收事件。
static volatile EventBus defaultInstance;
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
典型的雙重校驗鎖單例。用 volatile 修飾是為了防止指令重排序導致的對象未完全初始化就被使用。
public void register(Object subscriber) {
Class subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods =
subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
findSubscriberMethods() 先查緩存——METHOD_CACHE 是一個以訂閱類為 key、方法列表為 value 的 ConcurrentHashMap。首次進入必然未命中,於是走反射路徑:
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);
}
反射實現的核心在 findUsingReflectionInSingleClass():
methods = findState.clazz.getDeclaredMethods();
for (Method method : methods) {
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0
&& (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation =
method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
ThreadMode threadMode = subscribeAnnotation.threadMode();
findState.subscriberMethods.add(new SubscriberMethod(
method, eventType, threadMode,
subscribeAnnotation.priority(),
subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification
&& method.isAnnotationPresent(Subscribe.class)) {
throw new EventBusException("@Subscribe method must have "
+ "exactly 1 parameter");
}
}
}
這裡有幾個值得注意的細節:用 getDeclaredMethods() 而非 getMethods(),是因為前者在 Activity 這類「胖子類」上明顯更快;回退邏輯會捕獲 NoClassDefFoundError 並降級到 getMethods();嚴格模式下會校驗方法必須 public、非靜態、非抽象,且只有一個參數。
private void subscribe(Object subscriber,
SubscriberMethod subscriberMethod,
boolean sticky, int priority) {
Class<?> eventType = subscriberMethod.eventType;
CopyOnWriteArrayList<Subscription> subscriptions =
subscriptionsByEventType.get(eventType);
Subscription newSubscription =
new Subscription(subscriber, subscriberMethod, priority);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
for (Subscription subscription : subscriptions) {
if (subscription.equals(newSubscription)) {
throw new EventBusException("Subscriber already registered");
}
}
}
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;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
if (sticky) {
Object stickyEvent;
synchronized (stickyEvents) {
stickyEvent = stickyEvents.get(eventType);
}
if (stickyEvent != null) {
postToSubscription(newSubscription, stickyEvent,
Looper.getMainLooper() == Looper.myLooper());
}
}
}
這段代碼維護了兩個雙向索引:subscriptionsByEventType(事件類型 → 訂閱列表,按 priority 插入)與 typesBySubscriber(訂閱者 → 事件類型列表)。有了這兩個映射,無論從事件找方法還是從訂閱者找事件,都是 O(1) 定位。用 CopyOnWriteArrayList 是因為註冊與分發往往發生在不同線程,寫時複製能避免加鎖。
register 三步總結:
@Subscribe 的方法;post(Object event) 本身邏輯很薄,主要負責維護 PostingThreadState,真正的判斷交給 postSingleEvent():
private void postSingleEvent(Object event,
PostingThreadState postingState) throws Error {
Class<? extends Object> eventClass = event.getClass();
List<Class<?>> eventTypes = findEventTypes(eventClass);
boolean subscriptionFound = false;
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(clazz);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
postToSubscription(subscription, event,
postingState.isMainThread);
aborted = postingState.canceled;
} finally {
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
break;
}
}
subscriptionFound = true;
}
}
if (!subscriptionFound) {
if (eventClass != NoSubscriberEvent.class
&& eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
值得注意的是 findEventTypes() 會把父類與接口對應的事件類型一併納入,這解釋了為什麼訂閱父類型也能收到子類事件。另外若無任何訂閱者,會補發一個 NoSubscriberEvent,方便統一監測「事件沒人接」的問題。
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");
}
}
這裡的 threadMode 正是註冊階段從 @Subscribe 註解中讀出的值,串起了整個鏈路。四種模式的分派邏輯:
mainThreadPoster 入隊,由內部 Handler 發消息到主線程執行。Executors.newCachedThreadPool() 這個線程池執行。BackgroundThread 與 Async 的區別在於並發策略:BackgroundThread 的任務串行執行,用一個布爾變量 handlerActive 控制同一時間只有一個任務在跑;Async 則允許動態並發。
把源碼看透之後,EventBus 並不神秘:register 通過反射掃描出當前對象中所有匹配的方法,把它們按事件類型存進幾個 Map;post 則依據事件實參的類型去 Map 裡查出訂閱列表,再按線程策略反射調用。
拋開「發布者、訂閱者、事件、總線」這套術語,本質就是:一個單例內部維護著若干 Map,存了一批方法引用;post 不過是按參數查表並反射執行。理解到這一層,你就能自己判斷它在什麼場景下合適、什麼場景下反而會成為維護負擔。
Volley 源碼入門(一):從 newRequestQueue 到快取與網路雙執行緒
做 Android 一年多下來,越發覺得網路請求是整個開發裡極重要的一塊。Volley 是 Google 官方帶的框架,於是決定好好啃一遍源碼,把它的邏輯理清楚。Voll
自定義衛星式菜單(弧形菜單)完整實作教學
衛星式菜單又叫弧形菜單:主按鈕固定在角落,點一下,子菜單項沿著一段圓弧依序散開,同時自轉進場。要做出來,主要得處理兩件事——動畫,以及一個自定義的 ViewGroup。
Android 開發技巧:打造仿微信的圖片裁剪控件
「拍照 → 裁剪」或「選圖 → 裁剪」幾乎是設定頭像、上傳圖片時的標準流程。本文記錄自己實作一個仿微信體驗的裁剪控件的過程與關鍵程式碼。 一、需求背景 需求都來自產品:
Eclipse 開發環境啟動報錯:This Android SDK requires Android Developer Toolkit version 23.0.0 or above 的解法
剛入門 Android 開發的朋友,在張羅 Eclipse、SDK 與 ADT 這套經典組合時,常常會在 SDK 線上安裝完成、重新開啟 Eclipse 的那一刻被一個警