編輯:關於 Android 程式設計
上一篇帶大家初步了解了 EventBus 的使用方式,本篇深入原始碼。讀完應該能解答很多使用上的疑問:為什麼可以這樣做?為什麼那樣做不好?
一般使用 EventBus 的組件長這樣:
public class SampleComponent extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
public void onEventMainThread(param) { }
public void onEventPostThread(param) { }
public void onEventBackgroundThread(param) { }
public void onEventAsync(param) { }
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
大多數情況會在 onCreate 中註冊、在 onDestroy 中取消註冊。
問題一:那些以 onEvent 開頭的方法是幹什麼的?
先反問一句:你怎麼不問 register(this) 是幹什麼的?其實 register(this) 就是去當前類別遍歷所有方法,找出以 onEvent 開頭的並存起來。這樣就知道那些方法是幹什麼用的了。
問題二:onEvent 後面那些 MainThread 之類的標誌是什麼?
沒錯,onEvent 後面可以接四種後綴,也就是上面出現的那四個方法,它們決定了該方法最終在哪條執行緒、以何種方式運行。
那怎麼調用呢?
EventBus.getDefault().post(param);
只要把 param 發布出去,EventBus 會在內部儲存的方法中掃描,找到參數型別相符的,就用反射呼叫。
撇開專業術語,EventBus 做的事就是:內部存了一堆以 onEvent 開頭的方法,post 時根據傳入的參數找出匹配者並反射調用。而它內部是用 Map 儲存的,鍵就是參數的 Class 型別——知道這點,根據參數查找就不是難事了。
EventBus.getDefault() 是個單例,等同傳統的 getInstance:
/** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
用了雙重檢查鎖定,既避免並發問題,也避免每次都加鎖。
對外公開的 register 有四個:
public void register(Object subscriber) {
register(subscriber, DEFAULT_METHOD_NAME, false, 0);
}
public void register(Object subscriber, int priority) {
register(subscriber, DEFAULT_METHOD_NAME, false, priority);
}
public void registerSticky(Object subscriber) {
register(subscriber, DEFAULT_METHOD_NAME, true, 0);
}
public void registerSticky(Object subscriber, int priority) {
register(subscriber, DEFAULT_METHOD_NAME, true, priority);
}
本質上都呼叫同一個私有方法:
private synchronized void register(Object subscriber, String methodName,
boolean sticky, int priority) {
List<SubscriberMethod> subscriberMethods =
subscriberMethodFinder.findSubscriberMethods(
subscriber.getClass(), methodName);
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod, sticky, priority);
}
}
四個參數分別是:
· subscriber:要被掃描的類別物件,也就是常見的 this。
· methodName:寫死為 "onEvent",用來決定掃描什麼前綴的方法。
· sticky:後面解釋,暫時不用管。
· priority:優先級,數字越大越先被呼叫。
接著看掃描方法的實作:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass,
String eventMethodName) {
String key = subscriberClass.getName() + '.' + eventMethodName;
List<SubscriberMethod> subscriberMethods;
synchronized (methodCache) {
subscriberMethods = methodCache.get(key);
}
if (subscriberMethods != null) {
return subscriberMethods;
}
subscriberMethods = new ArrayList<SubscriberMethod>();
Class<?> clazz = subscriberClass;
HashSet<String> eventTypesFound = new HashSet<String>();
StringBuilder methodKeyBuilder = new StringBuilder();
while (clazz != null) {
String name = clazz.getName();
if (name.startsWith("java.") || name.startsWith("javax.")
|| name.startsWith("android.")) {
// 跳過系統類別,掃描它們只會拖慢效能
break;
}
// 從 EventBus 2.2 起,要求方法必須是 public
Method[] methods = clazz.getMethods();
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith(eventMethodName)) {
int modifiers = method.getModifiers();
if ((modifiers & Modifier.PUBLIC) != 0
&& (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 1) {
String modifierString =
methodName.substring(eventMethodName.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 {
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)) {
// 子類別中已找到的同名方法就不再重複加入
subscriberMethods.add(
new SubscriberMethod(method, threadMode, eventType));
}
}
}
}
}
clazz = clazz.getSuperclass();
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " has no public methods called " + eventMethodName);
} else {
synchronized (methodCache) {
methodCache.put(key, subscriberMethods);
}
return subscriberMethods;
}
}
代碼看起來長,核心不難:
· 先查 methodCache,命中就直接回傳(這是為什麼註冊很快)。
· clazz.getMethods() 取得所有 public 方法,然後逐一比對。
· 過濾條件是:以 onEvent 開頭、是 public 且非 static/abstract、且只有一個參數。
· 依方法後綴決定 threadMode,共四種枚舉值。
· 最後把 method、threadMode、eventType 封裝成 SubscriberMethod 加入清單。
· 注意 clazz = clazz.getSuperclass():掃描會一路往上到父類,直到碰到 java./javax./android. 開頭的系統類別才停止。
回到 register,接著對每個掃到的方法呼叫 subscribe:
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod,
boolean sticky, int priority) {
subscribed = true;
Class<?> eventType = subscriberMethod.eventType;
CopyOnWriteArrayList<Subscription> subscriptions =
subscriptionsByEventType.get(eventType);
Subscription newSubscription =
new Subscription(subscriber, subscriberMethod, priority);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<Subscription>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
for (Subscription subscription : subscriptions) {
if (subscription.equals(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass()
+ " already registered to event " + eventType);
}
}
}
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<Class<?>>();
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());
}
}
}
逐段說明:
· 4–17 行:依 subscriberMethod.eventType 從 subscriptionsByEventType 取出 CopyOnWriteArrayList<Subscription>,沒有就建立;同時把傳入參數封裝成 Subscription(subscriber, subscriberMethod, priority)。這個 subscriptionsByEventType 就是 EventBus 儲存方法的地方,key 是 eventType,value 是 Subscription 清單,務必記住。
· 22–28 行:把 newSubscription 依優先級插入,優先級越高越靠前,因此會越早被呼叫。
· 30–35 行:另外用 typesBySubscriber 記錄每個 subscriber 訂閱了哪些 eventType,主要供 isRegistered 判斷使用。
· 37–47 行:若 sticky 為 true,就從 stickyEvents 中依 eventType 查找有沒有對應事件,有的話立刻發布執行。stickyEvent 就是當初 post 時傳入的參數。
小結 register:它掃描了所有方法,把符合條件的存進 subscriptionsByEventType。eventType 是方法參數的 Class,而 Subscription 裡保存著 subscriber、subscriberMethod(含 method、threadMode、eventType)與 priority——執行該方法所需的一切都在裡面。
既然 register 把方法存進 subscriptionsByEventType,post 自然要去那裡取出來呼叫。
/** Posts the given event to the event bus. */
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
if (!postingState.isPosting) {
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
try {
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
}
}
}
currentPostingThreadState 是 ThreadLocal 型別,裡面存著 PostingThreadState,後者包含一個 eventQueue 與若干標誌位:
private final ThreadLocal<PostingThreadState> currentPostingThreadState =
new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
於是把傳入的 event 放進當前執行緒的 eventQueue 中。接著判斷是否為 UI 執行緒,然後遍歷佇列中的所有 event,逐一呼叫 postSingleEvent()。
這裡可能會有疑問:每次 post 都要處理整個佇列,會不會造成方法被重複呼叫?不會——postingState.isPosting 的判斷就是為了避免這種情況:若已在分發中,新的 post 只會把事件放進佇列,由進行中的迴圈一起消化。
接著看 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) {
Log.d(TAG, "No subscribers registered for event " + eventClass);
if (eventClass != NoSubscriberEvent.class
&& eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
2–3 行:findEventTypes() 會取得該物件所屬的 Class 及其所有父類與介面的 Class 清單,主要用於匹配——例如傳入 Dog,Animal 也會被放進清單中,因此訂閱父類型別的方法同樣會被觸發。
6–31 行:遍歷所有 Class,逐一到 subscriptionsByEventType 中查找 subscriptions,這正是 register 存放的地方。
12–30 行:對每個 subscription 呼叫 postToSubscription() 進行反射呼叫。若中途有訂閱者呼叫 EventBus.cancelEventDelivery(),aborted 會為 true 並中斷後續分發。
最後看它如何反射執行:
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);
}
}
第一步就是根據 threadMode 決定在哪條執行緒執行:
PostThread:
void invokeSubscriber(Subscription subscription, Object event) throws Error {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
}
直接反射調用,也就是在當前執行緒執行。
MainThread:當前若是 UI 執行緒就直接呼叫;否則交給 mainThreadPoster.enqueue(),它把任務放進佇列並透過 Handler 送出訊息,在 handleMessage 中執行。說白了就是靠 Handler 切回主線程。
BackgroundThread:當前若非 UI 執行緒就直接呼叫;若在 UI 執行緒,則把任務放進背景佇列,最終由 EventBus 內部的執行緒池(Executors.newCachedThreadPool())執行。
Async:不論當前在哪條執行緒,都把任務放進背景佇列,交給同一個執行緒池執行。
那 BackgroundThread 與 Async 差在哪?BackgroundThread 的任務一個接一個執行,中間用一個布林標誌控制串行;Async 則允許並發,會動態開多條執行緒同時跑。所以別在 Async 方法的實作裡假設執行緒安全。
register 中若 sticky 為 true,會去 stickyEvents 找事件並立即發布。那 stickyEvents 是誰寫入的呢?
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
// 應該在 put 之後再發布,以防訂閱者想立刻移除
post(event);
}
功能與 post 類似,但會把事件存進 stickyEvents。EventBus 其他 public 方法大多是狀態判斷、取得事件、移除事件之類,見名知意即可。
register 把當前類別中匹配的方法存進一個 Map;post 則根據實參去 Map 中查找並反射調用。分析這麼一大篇,一句話就能講完。
其實拋開「發布者、訂閱者、事件、總線」這些術語,EventBus 就是在一個單例內部維護一個 Map 存放一堆方法,post 不過是依參數查找方法再反射調用。理解這層之後,再去看它的細節——優先級排序、ThreadLocal 佇列、四種 ThreadMode 的切換、sticky 的補發機制——就會發現那些設計都是有理由的。
Android 性能優化與內存洩漏分析完全指南
性能問題一般可歸納為三類: 1. UI 卡頓與穩定性,這類問題用戶可直接感知,最為重要。 2. 內存問題,主要表現為內存洩漏。若存在洩漏,應用會不斷消耗內存,容易導致頻繁
Android 安全加密系列:消息摘要 Message Digest 完全指南
系列文章索引 Android 安全加密:對稱加密 Android 安全加密:非對稱加密 Android 安全加密:消息摘要 Message Digest Android
Android 使用 AlertDialog 實作消息彈窗
在 Android 應用中,當需要提醒使用者進行某項操作或確認某個決定時,常會使用對話框。AlertDialog 是最常見的選擇之一,可用來顯示標題、內容與多個操作按鈕。
Android ActionBar 進階應用:Action Provider、Tabs 與樣式
ActionBar 除了基本的動作按鈕,還可以透過 Action Provider、Tabs 與自訂樣式,打造更完整的導航體驗。以下整理進階用法。Action Provi