目錄
概念
EventBus:是一個Android事件發(fā)布/訂閱框架,通過解耦發(fā)布者與訂閱者的方式,大大的簡化了Activity與Activity,Activity與Fragment,F(xiàn)ragment與Fragment等之間的數(shù)據(jù)傳遞爆土,從而使得代碼更簡潔明了咬最。
使用
1布朦,配置
- 打開App的build.gradle搂捧,在dependencies中添加最新的EventBus依賴:
3.0以下版本的AndroidStudio : compile 'org.greenrobot:eventbus:3.1.1'
3.0及以上版本的AndroidStudio : implementation 'org.greenrobot:eventbus:3.1.1'>- 索引加速模式(在AndroidStudio3.1.3上配置成功扮宠,在2.2.2版本上使用網(wǎng)上的兩種方案均無MyEventBusIndex文件生成) 抛虫。成功配置的步驟如下(針對AndroidStudio3.1.3)
1松靡,在app的build.gradle文件的dependencies中添加:
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1'
2,在app的build.gradle文件的defaultConfig中添加:(com.learn.study:當(dāng)前的包名建椰,可以自己配置)
javaCompileOptions {
annotationProcessorOptions {
arguments = [ eventBusIndex : 'com.learn.study.MyEventBusIndex' ]
}
}
3雕欺,rebuiid項目后在app的build/generated/source/apt/debug中找到:MyEventBusIndex文件
2,注冊與注銷
//注冊(一般在Activity或Fragment的onCreate中進(jìn)行)
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
//注銷(一般是在Activity或Fragment的onDestory中進(jìn)行)
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
//補(bǔ)充(如果使用了索引加速):在Application中配置:
EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
3棉姐,接收事件
//3.0以后方法名可以任意屠列,但必須加上@Subscribe的標(biāo)識,同時設(shè)置參數(shù)為:
threadMode:當(dāng)前接收事件的執(zhí)行線程
sticky:是否接收粘性事件伞矩;
priority:設(shè)置優(yōu)先級
方法的參數(shù)與發(fā)送的數(shù)據(jù)類型一致笛洛,必須為對象類型,如:必須使用Integer而不能使用int
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 0)
public void getMainData(Integer number) {
Log.d(TAG, "ThreadMode : getMainData: " + number + " ;; " + Thread.currentThread().getName());
}
四種線程模型(ThreadMode:定義線程類型的枚舉類)說明:
- POSTING : 在當(dāng)前發(fā)送的線程中執(zhí)行(不用切換線程乃坤,最輕量級)
- MAIN:在主線程中執(zhí)行
- MAIN_ORDERED:在主線程中執(zhí)行苛让,但事件始終排隊等候確保調(diào)用為非阻塞(不常用)
- BACKGROUND:后臺線程,當(dāng)在UI線程時中發(fā)布時才會新建一個后臺線程執(zhí)行
- ASYNC:交給線程池來管理侥袜,直接通過asyncPoster調(diào)度蝌诡。
4,發(fā)送事件
//發(fā)送普通事件
EventBus.getDefault().post(10);
//發(fā)送粘性事件
EventBus.getDefault().postSticky(20);
5枫吧,注意事項
1浦旱,有注冊必須有注銷,保證一一對應(yīng)九杂,同時調(diào)用的生命周期方法也對應(yīng)
2颁湖,注冊頁面必須有接收方法宣蠕,主要是需要識別到有Subscribe的注解,發(fā)送界面不需要注冊甥捺。
3抢蚀,同一個事件可以定義多個接收,參數(shù)必須是對象類型镰禾。如:發(fā)送的是int但接收參數(shù)必須為Interger
4皿曲,使用普通的post發(fā)送事件時,必須先注冊才能收到吴侦。而postSticky可以在發(fā)送后注冊也能收到
//1屋休,驗證普通事件與粘性事件的發(fā)送與注冊順序
private void testEventBus() {
EventBus.getDefault().postSticky(20);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 0)
public void getMainData(Integer number) {
Log.d(TAG, "ThreadMode : getMainData: " + number + " ;; " + Thread.currentThread().getName());
}
//打印結(jié)果:(即事件能夠收到并處理)
10-24 21:13:52.574 5913-5913/com.learn.study D/MainActivity: ThreadMode : getMainData: 20 ;; main
private void testEventBus() {
EventBus.getDefault().post(10);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 0)
public void getMainData(Integer number) {
Log.d(TAG, "ThreadMode : getMainData: " + number + " ;; " + Thread.currentThread().getName());
}
//無打印,即事件未接收
//2,驗證線程模型
@Subscribe(threadMode = ThreadMode.MAIN)
public void getMainData(Integer number) {
Log.d(TAG, "ThreadMode : getMainData: " + number + " ;; " + Thread.currentThread().getName());
}
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void getThreadData(Integer number) {
Log.d(TAG, "ThreadMode : getThreadData: " + number + " ;; " + Thread.currentThread().getName());
}
@Subscribe(threadMode = ThreadMode.POSTING)
public void getPostData(Integer number) {
Log.d(TAG, "ThreadMode : getPostData: " + number + " ;; " + Thread.currentThread().getName());
}
@Subscribe(threadMode = ThreadMode.ASYNC)
public void getAsyncData(Integer number) {
Log.d(TAG, "ThreadMode : getAsyncData: " + number + " ;; " + Thread.currentThread().getName());
}
EventBus.getDefault().post(10);
Log.d("MainActivity", "ThreadMode : sendData :" + Thread.currentThread().getName());
//在主線程中發(fā)送結(jié)果打颖溉汀:
10-24 21:28:19.490 6837-6837/com.learn.study D/MainActivity: ThreadMode : getMainData: 10 ;; main
ThreadMode : getPostData: 10 ;; main
10-24 21:28:19.491 6837-7309/com.learn.study D/MainActivity: ThreadMode : getThreadData: 10 ;; pool-1-thread-1
10-24 21:28:19.491 6837-6837/com.learn.study D/MainActivity: ThreadMode : sendData :main
10-24 21:28:19.491 6837-7310/com.learn.study D/MainActivity: ThreadMode : getAsyncData: 10 ;; pool-1-thread-2
//在子線程中發(fā)送結(jié)果打咏僬痢:
10-24 21:33:22.969 7800-7859/com.learn.study D/MainActivity: ThreadMode : getThreadData: 10 ;; Thread-4
ThreadMode : getPostData: 10 ;; Thread-4
10-24 21:33:22.970 7800-7860/com.learn.study D/MainActivity: ThreadMode : getAsyncData: 10 ;; pool-1-thread-1
10-24 21:33:22.970 7800-7859/com.learn.study D/MainActivity: ThreadMode : sendData :Thread-4
10-24 21:33:23.028 7800-7800/com.learn.study D/MainActivity: ThreadMode : getMainData: 10 ;; main
//3,驗證接收事件的優(yōu)先級(相同的線程中才存在優(yōu)先級問題织堂,同時攔截才有效果)
10-24 22:04:43.762 10532-10596/com.learn.study D/MainActivity: ThreadMode : getThreadData: 10 ;; Thread-4;; 優(yōu)先級:6
ThreadMode : getPostData: 10 ;; Thread-4;; 優(yōu)先級:3
10-24 22:04:43.763 10532-10596/com.learn.study D/MainActivity: ThreadMode : sendData :Thread-4
10-24 22:04:43.763 10532-10597/com.learn.study D/MainActivity: ThreadMode : getAsyncData: 10 ;; pool-1-thread-1;; 優(yōu)先級:0
10-24 22:04:43.810 10532-10532/com.learn.study D/MainActivity: ThreadMode : getMainData: 10 ;; main;; 優(yōu)先級:10
ThreadMode : getMain1Data: 10 ;; main;; 優(yōu)先級:7
原理(針對3.1.1版本的源碼)
1叠艳,注冊的流程
//1,使用雙重校驗的單例創(chuàng)建對象:EventBus.getDefault()
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
//2,register()調(diào)用注冊的方法
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
//查找當(dāng)前注冊類所有的接收方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
//具體實現(xiàn)查找接收方法:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//1,從Map集合METHOD_CACHE(鍵:注冊的類class對象易阳,值:當(dāng)前注冊類里面的接收方法)中查找方法附较,如果查詢到方法則直接返回方法集合List,否則重新獲取
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) {
//2闽烙,忽視索引加速的方式翅睛,直接使用反射的方式獲取的注冊類下的所有接受方法:最后還是調(diào)用findUsingReflectionInSingleClass()方法
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//3,獲取到注冊類里面的接收方法
subscriberMethods = findUsingInfo(subscriberClass);
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//1黑竞,這里存在一個查找狀態(tài)池:FIND_STATE_POOL捕发,大小為4,減少對象的創(chuàng)建很魂。
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//2扎酷,查找注冊類的接受方法,如果添加了索引加速遏匆,而返回接受方法法挨,否則返回null
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
//未添加索引加速時使用反射獲取接受方法
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
//使用索引加速獲取方法
private SubscriberInfo getSubscriberInfo(FindState findState) {
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
if (subscriberInfoIndexes != null) {
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
//使用了索引加速則info返回索引的接收方法,否則返回null
return info;
}
}
}
return null;
}
//使用反射獲取接收方法
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
//1,使用反射先獲取到注冊類里面的所有方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
//2,遍歷所有方法,找到接收事件的方法
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) {
//3,通過獲取方法上的注解Subscribe來區(qū)分接收事件的方法.
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
ThreadMode threadMode = subscribeAnnotation.threadMode();
//4,將接收事件的方法信息添加到查詢狀態(tài)的對象中
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException("@Subscribe method " + methodName +
"must have exactly 1 parameter but has " + parameterTypes.length);
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(methodName +
" is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}
//查找完成接收事件的方法后,調(diào)用subscribe(),將注冊類,接收方法,接收事件的類型等添加到對應(yīng)的Map集合中進(jìn)行保存,避免相應(yīng)信息每次獲取
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
int size = subscriptions.size();
//根據(jù)接收事件的優(yōu)先級,將訂閱事件存放到subscriptionsByEventType集合中
for (int i = 0; i <= size; i++) {
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.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 (subscriberMethod.sticky) {
if (eventInheritance) {
// Existing sticky events of all subclasses of eventType have to be considered.
// Note: Iterating over all events may be inefficient with lots of sticky events,
// thus data structure should be changed to allow a more efficient lookup
// (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
for (Map.Entry<Class<?>, Object> entry : entries) {
Class<?> candidateEventType = entry.getKey();
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
//后續(xù)調(diào)用跟普通事件相同的流程.
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
2,注銷流程
EventBus.getDefault().unregister(this);
//1,與注冊相同,使用單例獲取到EventBus對象.
public synchronized void unregister(Object subscriber) {
//typesBySubscriber這是一個Map集合,鍵為:注冊的類,值為當(dāng)前類中處理的事件類型集合
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
//從存放注冊類與事件類型的對照集合中移除注冊類,這樣也可以防止對象引用無法釋放.
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//subscriptionsByEventType這也是一個Map集合,鍵:事件類型,值:事件類型對應(yīng)的接收方法.
//Subscription:將注冊類與接收方法封裝為了一個數(shù)據(jù)結(jié)構(gòu)
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
//移除事件類型對應(yīng)的方法
subscriptions.remove(i);
i--;
size--;
}
}
}
}
3幅聘,發(fā)布事件
//發(fā)送粘性事件
public void postSticky(Object event) {
synchronized (stickyEvents) {
//將粘性事件存入stickyEvents集合中,鍵為:事件類型,值:事件的具體值
stickyEvents.put(event.getClass(), event);
}
// Should be posted after it is putted, in case the subscriber wants to remove immediately
post(event);
}
//發(fā)送普通事件
public void post(Object event) {
//使用ThreadLocal存放當(dāng)前線程狀態(tài)對象:PostingThreadState
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
//1,將事件加入到事件集合中
eventQueue.add(event);
if (!postingState.isPosting) {
postingState.isMainThread = isMainThread();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while (!eventQueue.isEmpty()) {
//2,事件處理的方法
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//3,獲取事件類型的class對象,如:int 10 ,最終獲取的是:java.lang.Integer
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) {
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
//4,發(fā)布事件調(diào)用方法:postSingleEventForEventType()
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
if (!subscriptionFound) {
if (logNoSubscriberMessages) {
logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
//5,根據(jù)不同的線程模型來處理發(fā)布的事件
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;
}
//根據(jù)接收處理事件的線程模型不同,分別在對應(yīng)的線程中處理事件.
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case POSTING: //在當(dāng)前發(fā)布的線程中處理
invokeSubscriber(subscription, event);
break;
case MAIN: //在主線程中處理事件
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
case MAIN_ORDERED:
if (mainThreadPoster != null) {
mainThreadPoster.enqueue(subscription, event);
} else {
// temporary: technically not correct as poster not decoupled from subscriber
invokeSubscriber(subscription, event);
}
break;
case BACKGROUND:
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);
}
}
void invokeSubscriber(Subscription subscription, Object event) {
try {
//6,最終調(diào)用method的invoke方法來處理
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
4凡纳,索引加速的原理
在編譯期生成類用來記錄所有的接收事件方法,將運行期的反射提前到編譯期帝蒿,避免了運行期使用反射增加的性能開銷荐糜。編譯期生成的類如下:
public class MyEventBusIndex implements SubscriberInfoIndex {
//用來存放所有的接收事件方法,避免后面需要通過反射獲取,減小運行的性能開銷
private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;
static {
SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();
putIndex(new SimpleSubscriberInfo(MainActivity.class, true, new SubscriberMethodInfo[] {
new SubscriberMethodInfo("getMainData", Integer.class, ThreadMode.MAIN, 10, false),
new SubscriberMethodInfo("getMain2Data", Integer.class, ThreadMode.MAIN, 7, false),
new SubscriberMethodInfo("getThreadData", Integer.class, ThreadMode.BACKGROUND, 6, false),
new SubscriberMethodInfo("getPostData", Integer.class, ThreadMode.POSTING, 3, false),
new SubscriberMethodInfo("getAsyncData", Integer.class, ThreadMode.ASYNC),
}));
}
private static void putIndex(SubscriberInfo info) {
SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
}
@Override
public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
if (info != null) {
return info;
} else {
return null;
}
}
}