Markdown版本筆記 | 我的GitHub首頁 | 我的博客 | 我的微信 | 我的郵箱 |
---|---|---|---|---|
MyAndroidBlogs | baiqiantao | baiqiantao | bqt20094 | baiqiantao@sina.com |
目錄
EventBus
一句話描述:調用【register】方法后,EventBus會把當前類中【onEvent開頭的方法】,存入一個【單例】內部維持着一個【map】中,KEY就是【方法中的參數】,Value就是此【onEvent開頭的方法】;而后在post的時候,EventBus就會根據我們傳入的參數的類型去map中查找匹配的方法(可能有很多個),然后逐個【反射】調用這些方法。
收不到消息的原因
- 方法名不對(必須以onEvent開頭)
- 參數不對(參數只能有一個,且不能是基本類型)
- 可能沒有注冊。發送不需要注冊,接收需要注冊。父類如果注冊的話,子類調用super方法后不能再注冊,否則異常退出
- 注冊的位置可能不對(試一下改為在onCreate方法中注冊,在onDestroy中1取消)
- 可能需要加注解(在發送和接收的方法上加上@Subscribe注解)
- 可能你的onEvent方法運行時有錯誤(比如空指針),此時EventBus不會提示任何異常,這會讓你誤以為是沒有回調到
- 如果在BActivity中發了一條消息,AActivity中收到消息后時不能顯示吐司的
注冊 register
簡單說,EventBus.getDefault().register(this)
所做的事情就是:在當前類中遍歷所有的方法,找到onEvent
開頭的然后進行存儲。
EventBus.getDefault()其實就是個單例,register公布給我們使用的有4個,本質上調用的是同一個:
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:優先級,優先級越高,在調用的時候會越先調用
findSubscriberMethods
首先會調用findSubscriberMethods方法,實際是去遍歷該類內部所有方法
,然后根據methodName去匹配,匹配成功的就封裝成SubscriberMethod
對象,最后存儲到一個List
並返回。
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.")) {
// 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.getMethods();//去得到所有的方法
for (Method method : methods) {//開始遍歷每一個方法,去匹配封裝
String methodName = method.getName();
if (methodName.startsWith(eventMethodName)) {//分別判斷了是否以onEvent開頭,是否是public且非static和abstract方法,是否是一個參數。如果都符合,才進入封裝的部分。
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是個枚舉類型
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
subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType));//將method, threadMode, eventType傳入構造SubscriberMethod對象,添加到List
}
}
} else if (!skipMethodVerificationForClasses.containsKey(clazz)) {
Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "." + methodName);
}
}
}
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;
}
}
suscribe 方法
然后for循環掃描到的方法,然后調用suscribe方法
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
subscribed = true;
Class<?> eventType = subscriberMethod.eventType; //eventType是我們方法參數的Class,是Map的key
//根據subscriberMethod.eventType,去subscriptionsByEventType查找一個CopyOnWriteArrayList<Subscription> ,如果沒有則創建。
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); // Map的value,這里的subscriptionsByEventType是個Map,這個Map其實就是EventBus存儲方法的地方
Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);//Map的value中保存的是Subscription
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);
}
}
}
// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
// subscriberMethod.method.setAccessible(true);
int size = subscriptions.size();
for (int i = 0; i <= size; i++) { //按照優先級添加newSubscription,優先級越高,會插到在當前List的前面。
if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
subscriptions.add(i, newSubscription);
break;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); //根據subscriber存儲它所有的eventType
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<Class<?>>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
if (sticky) { //判斷sticky;如果為true,從stickyEvents中根據eventType去查找有沒有stickyEvent,如果有則立即發布去執行
Object stickyEvent;
synchronized (stickyEvents) {
stickyEvent = stickyEvents.get(eventType);
}
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());
}
}
}
你只要記得一件事:掃描了所有的方法,把匹配的方法最終保存在subscriptionsByEventType(Map,key:eventType ; value:CopyOnWriteArrayList<Subscription> )
中;
eventType是我們方法參數的Class,Subscription中則保存着subscriber, subscriberMethod, priority;包含了執行改方法所需的一切。
發布 post
調用很簡單,一句話,你也可以叫發布,只要把這個param發布出去,EventBus會在它內部存儲的方法中,進行掃描,找到參數匹配的,就使用反射進行調用
。
/** 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) {//防止每次post都會去調用整個隊列
return;
} else {
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();//判斷當前是否是UI線程(我去,竟然是通過這種方式判斷的!)
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while (!eventQueue.isEmpty()) {//遍歷隊列中的所有的event,調用postSingleEvent方法。
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//得到event當前對象的Class,以及父類和接口的Class類型;主要用於匹配,比如你傳入Dog extends Animal,他會把Animal也裝到該List中。
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,到subscriptionsByEventType去查找subscriptions,register時我們就是把方法存在了這個Map里
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));
}
}
}
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) { //根據threadMode去判斷應該在哪個線程去執行該方法
case PostThread:
invokeSubscriber(subscription, event); //直接【反射】調用;也就是說在當前的線程直接調用該方法
break;
case MainThread:
if (isMainThread) {//如果是UI線程,則直接調用
invokeSubscriber(subscription, event);
} else {//否則把當前的方法加入到隊列,然后直接通過【handler】去發送一個消息,並在handler的handleMessage中去執行我們的方法
mainThreadPoster.enqueue(subscription, event);
}
break;
case BackgroundThread:
if (isMainThread) {//如果是UI線程,則將任務加入到后台的一個【隊列】,最終由Eventbus中的一個【線程池】去調用executorService = Executors.newCachedThreadPool();
backgroundPoster.enqueue(subscription, event);
} else {//如果當前非UI線程,則直接調用
invokeSubscriber(subscription, event);
}
break;
case Async: //將任務加入到后台的一個【隊列】,最終由Eventbus中的一個【線程池】去調用;線程池與BackgroundThread用的是【同一個】
asyncPoster.enqueue(subscription, event); //BackgroundThread中的任務,【一個接着一個去調用】,中間使用了一個布爾型變量進行的控制。Async則會【動態控制並發】
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}
粘性事件 sticky
介紹了register和post;大家獲取還能想到一個詞sticky,在register中,如果sticky為true,會去stickyEvents去查找事件,然后立即去post;
那么這個stickyEvents何時進行保存事件呢?
其實evevntbus中,除了post發布事件,還有一個方法也可以:
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
// Should be posted after it is putted, in case the subscriber wants to remove immediately
post(event);
}
和post功能類似,但是會把方法存儲到stickyEvents
中去;
大家再去看看EventBus中所有的public方法,無非都是一些狀態判斷,獲取事件,移除事件的方法;沒什么好介紹的,基本見名知意。
2016-9-7