源码阅读-EventBus


背景

EventBus作为一款事件发布的第三方开源框架,几乎是每个项目都会使用到,使用它可以对Fragment和Fragment之间 Activity和Activity之间,不同组件之间信息交互变得便捷,减少耦合性上有非常显著的效果,为了搞清楚EventBus 这个Android开发中国民级的开源组件源码,我们来看一下源码是怎么写的

title: 启动优化
date: 2022-01-30
categories: 性能优化
tags: Android开发


为什么要做启动优化

1、第一体验很重要

2、八秒定律:如果打开需要8秒钟那么用户就会放弃

冷启动是衡量的标准

冷启动流程
click->ipc-process.start->ActivityThread->bindApplication->LifeCycle->ViewRootImpl

优化方向

Application和Activity 生命周期方法是优化的方向 其他的地方其实无法干预

adb命令获取启动时间

adb shell am start -W packagename/首屏Activity

adb shell am start -W com.example.better/.MainActivity
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.better/.MainActivity }
Status: ok
Activity: com.example.better/.MainActivity
ThisTime: 364
TotalTime: 364
WaitTime: 374
Complete

WaitTime 表示AMS启动Activity的总耗时

TotalTime 表示所有Activity启动耗时

ThisTime 表示最后一个Activity启动耗时

手动打点

就是从开始时间到ui展示出来的时比如你从application 开始到View画出来时间

比如创建一个类来负责记录时间

class LauncherTimer {
    private static long sTime;
    public static void startRecord() {
        sTime = System.currentTimeMillis();
    }
    public static void endRecord() {
        long cost = System.currentTimeMillis() - sTime;
        Log.i("cost", "endRecord: " + cost);
    }
}

需要注意的是,应该是View绘制出来作为结束时间,比如可以监听某个View绘制的时候作为结束时间

findViewById(R.id.text).getViewTreeObserver().addOnPreDrawListener(() -> {
           LauncherTimer.endRecord();
           return true;
       });

工具选择

1、traceview

使用方式

Debug.startMethodTracing("app");

Debug.stopMethodTracing();



它会在应用的目录上生成一个xx.trace 文件 通过Studio打开后可以发现大概长这样

![trace](/images/trace.png)

上面滑动部分是你需要选中的时间范围

中间部分会列出所有线程,还有每个做了什么事情,也就是方法调用栈
点击方法可以知道每个方法的耗时
total就是这个方法的耗时,
children 就是子方法的耗时
self 就是自己花费了多长时间
知道了这些就可以进行性能优化

多关注TopDown就可以知道哪些方法耗时了


### 2、systemtrace

























## 基础使用

implementation 'org.greenrobot:eventbus:3.0.0'

在回调方法中加入注册和反注册功能,然后在方法中加入注解
@Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override protected void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onmessage(MyBusEvent event) { Toast.makeText(this, event, Toast.LENGTH_SHORT).show(); }


最后一步就是在任意地方发送一个广播



public void postEvent() { EventBus.getDefault().post(new MyBusEvent("hhh")); }



## 源码解析


我们先看第一句 EventBus.getDefault()到底做了什么
public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; }

非常明显是做了一个双层锁的单例模式我们来看一下new EventBus构造方法
public EventBus() { this(DEFAULT_BUILDER); }

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

调用了一个参数的构造方法传入了一个变量这这个变量就是它EventBusBuilder 所以其实是一个建造者模式,我们看一下EventBusBuilder和传参数的构造方法


EventBus(EventBusBuilder builder) { subscriptionsByEventType = new HashMap<>(); typesBySubscriber = new HashMap<>(); stickyEvents = new ConcurrentHashMap<>(); mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10); backgroundPoster = new BackgroundPoster(this); asyncPoster = new AsyncPoster(this); indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0; subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes, builder.strictMethodVerification, builder.ignoreGeneratedIndex); logSubscriberExceptions = builder.logSubscriberExceptions; logNoSubscriberMessages = builder.logNoSubscriberMessages; sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent; sendNoSubscriberEvent = builder.sendNoSubscriberEvent; throwSubscriberException = builder.throwSubscriberException; eventInheritance = builder.eventInheritance; executorService = builder.executorService; }

可以看到做了很多的初始化操作subscriptionsByEventType 这个是以发送的对象为key subscrption为value的一个hashmap typesBySubscriber这个是一个以subscrption为key发送对象为value的一个hashmap
stickyEvents 是一个粘性事件 map
HandlerPoster是一个继承Handler的调度器 我们有必要看一下这个类的代码


final class HandlerPoster extends Handler { private final PendingPostQueue queue; private final int maxMillisInsideHandleMessage; private final EventBus eventBus; private boolean handlerActive; HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) { super(looper); this.eventBus = eventBus; this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage; queue = new PendingPostQueue(); } void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); synchronized (this) { queue.enqueue(pendingPost); if (!handlerActive) { handlerActive = true; if (!sendMessage(obtainMessage())) { throw new EventBusException("Could not send handler message"); } } } } @Override public void handleMessage(Message msg) { boolean rescheduled = false; try { long started = SystemClock.uptimeMillis(); while (true) { PendingPost pendingPost = queue.poll(); if (pendingPost == null) { synchronized (this) { // Check again, this time in synchronized pendingPost = queue.poll(); if (pendingPost == null) { handlerActive = false; return; } } } eventBus.invokeSubscriber(pendingPost); long timeInMethod = SystemClock.uptimeMillis() - started; if (timeInMethod >= maxMillisInsideHandleMessage) { if (!sendMessage(obtainMessage())) { throw new EventBusException("Could not send handler message"); } rescheduled = true; return; } } } finally { handlerActive = rescheduled; } } }


我们可以看到PendingPostQueue是一个即将发送的消息队列,handlerActive是这个eventBus有没有运行起来,我们看一下他的handleMessage方法 ,其实就是从队列中拿到一个即将发送的消息,然后就是调用invokeSubscriber方法
void invokeSubscriber(PendingPost pendingPost) { Object event = pendingPost.event; Subscription subscription = pendingPost.subscription; PendingPost.releasePendingPost(pendingPost); if (subscription.active) { invokeSubscriber(subscription, event); } }

我们回到EventBus的一个参数的构造方法从HandlerPoster继续往下看下去,我们看到了BackgroundPoster这个分发器我们看一下源码


final class BackgroundPoster implements Runnable { private final PendingPostQueue queue; private final EventBus eventBus; private volatile boolean executorRunning; BackgroundPoster(EventBus eventBus) { this.eventBus = eventBus; queue = new PendingPostQueue(); } public void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); synchronized (this) { queue.enqueue(pendingPost); if (!executorRunning) { executorRunning = true; eventBus.getExecutorService().execute(this); } } } @Override public void run() { try { try { while (true) { PendingPost pendingPost = queue.poll(1000); if (pendingPost == null) { synchronized (this) { // Check again, this time in synchronized pendingPost = queue.poll(); if (pendingPost == null) { executorRunning = false; return; } } } eventBus.invokeSubscriber(pendingPost); } } catch (InterruptedException e) { Log.w("Event", Thread.currentThread().getName() + " was interruppted", e); } } finally { executorRunning = false; } } }


其实就是一个线程 我们看run方法,其实跟前面是的HandlerPoster类似就是将事件调用invokeSubscriber方法通过反射去执行,这里就不再多说了,我们继续看AsyncPoster 这个类,其实这个类跟上面的类似,只不过它是拿到一个进行反射调用











class AsyncPoster implements Runnable { private final PendingPostQueue queue; private final EventBus eventBus; AsyncPoster(EventBus eventBus) { this.eventBus = eventBus; queue = new PendingPostQueue(); } public void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); queue.enqueue(pendingPost); eventBus.getExecutorService().execute(this); } @Override public void run() { PendingPost pendingPost = queue.poll(); if(pendingPost == null) { throw new IllegalStateException("No pending post available"); } eventBus.invokeSubscriber(pendingPost); } }

我们继续看subscriberMethodFinder这个是一个方法找寻器,这个就是通过它来找寻有subscribe的方法,我们再后面再详细介绍这个类
后面像各种logSubscriberExceptions等异常 我们就不深入介绍了,我们主要介绍主流程,不考虑很多异常情况,我们走主流程
接下里我们先来看一下注解






@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface Subscribe { ThreadMode threadMode() default ThreadMode.POSTING; boolean sticky() default false; int priority() default 0; } public enum ThreadMode { POSTING, MAIN, BACKGROUND, ASYNC }


我们看到注解后面有线程类型 ,是否是粘性事件,优先级,我们来看一下ThreadMode的种类,有几种 POSTING是默认类型,MAIN是主线程类型BACKGROUND是起一个线程来发送事件 ASYNC是一个事件类型就是起一个线程来发送事件
我们接下来看完注解 我们看一下register这个方法传入当前对象,我们直接看源码








public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass(); List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }





我们看到它通过subscriberMethodFinder.findSubscriberMethods(subscriberClass);这个方法找到了一个方法集合我们看一下SubscriberMethod这个封装类先



public class SubscriberMethod { final Method method; final ThreadMode threadMode; final Class<?> eventType; final int priority; final boolean sticky; /** Used for efficient comparison */ String methodString; public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) { this.method = method; this.threadMode = threadMode; this.eventType = eventType; this.priority = priority; this.sticky = sticky; } }

其实就是把这个方法注解类型给封装起来包括优先级,是否粘性,线程模式,属于哪个类的
我们回到 subscriberMethodFinder.findSubscriberMethods(subscriberClass)这个方法是怎么找的



List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) { List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass); if (subscriberMethods != null) { return subscriberMethods; } if (ignoreGeneratedIndex) { subscriberMethods = findUsingReflection(subscriberClass); } else { 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; } }


先进行缓存的判断如果缓存有的话那么直接返回回去,如果缓存没有的话调用findUsingInfo方法去找我们跟到findUsingInfo中去看



private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) { FindState findState = prepareFindState(); findState.initForSubscriber(subscriberClass); while (findState.clazz != 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); }




我们先看一下FindState这个类 这个类里面有几个重要的列表和map有方法的集合,有方法为value 方法的参数对象为key的map 有方法为key订阅对象为value的map





final List<SubscriberMethod> subscriberMethods = new ArrayList<>(); final Map<Class, Object> anyMethodByEventType = new HashMap<>(); final Map<String, Class> subscriberClassByMethodKey = new HashMap<>(); final StringBuilder methodKeyBuilder = new StringBuilder(128);


我们回到前面prepareFindState这方法是从池子中看能不能找到一样的,可以就复用 不可以就创建一个然后调用initForSubscriber这个方法这个方法其实是一些简单赋值操作我们看源码




private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) { FindState findState = prepareFindState(); findState.initForSubscriber(subscriberClass); while (findState.clazz != 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); }



其实大部分的情况下都会走到findUsingReflectionInSingleClass这个方法,这个才是解析注解方法的核心,我们看一下源码




private void findUsingReflectionInSingleClass(FindState findState) { Method[] methods; try { // This is faster than getMethods, especially when subscribers are fat classes like Activities 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; } 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)) { 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"); } } }






首先通过findState的有一个订阅者的类反射拿到所有方法,对所有方法进行遍历,对每个方法进行遍历方法必须为PUBLIC,参数长度必须为1,然后必须有Subscribe这个注解获取方法的线程模式,是否是粘性事件,权重大小等 加入到findState的 subscriberMethods就是方法集合,最后返回方法集合,subscriberMethods这个类已经在上面详细讲解了,其实就是一个方法的封装,
我们回到EventBus 的register方法 其实我们上面就是做好找到所有的方法并且每个方法都封装好最后成为一个 List subscriberMethods这个方法列表我们回顾一下源码


public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass(); List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }


我们看一下 subscribe(subscriber, subscriberMethod);





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(); 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) { <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(); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } } else { Object stickyEvent = stickyEvents.get(eventType); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } }




final class Subscription { final Object subscriber; final SubscriberMethod subscriberMethod; }



我们先看一下Subscription 点击进去其实就是一个更大的封装类里面有每个一个订阅者 对应一个方法,我们接下里看下面代码


CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList<>(); subscriptionsByEventType.put(eventType, subscriptions);


我们先总结一下subscribe这个方法做了什么 (1)首先判断是否有注册过改事件了如果注册了就抛出异常,如果没有就是正常的,创建一个Subscription 其实这个类就是一个注册类对应一个方法的封装,然后创建一个列表 (2)按优先级加入subscriptionsByEventType 这个是一个已发出的参数类型为key subscriptions为value的map集合,然后将subscription根据优先级加入value中 (3)然后在添加到typesBySubscriber的value的list中这个是以Subscriber为key 方法的参数为value的map中 (4)分发粘性事件checkPostStickyEventToSubscription 我们简单看一下checkPostStickyEventToSubscription,其实他最后是调用postToSubscription方法通过不同的线程模式调用不同的分发器,不同的分发器我们等一下讲,这里我们只要知道粘性事件也是走到了这里就可以了
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) { 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()); } }


private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case POSTING: invokeSubscriber(subscription, event); break; case MAIN: if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(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); } }



最后我们注册好了之后,我们就要来最后一步发送事件了


public void postEvent() { EventBus.getDefault().post(new MyBusEvent("hhh")); }

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; if (postingState.canceled) { throw new EventBusException("Internal error. Abort state was not reset"); } try { while (!eventQueue.isEmpty()) { postSingleEvent(eventQueue.remove(0), postingState); } } finally { postingState.isPosting = false; postingState.isMainThread = false; } } }


我们先看一下PostingThreadState


final static class PostingThreadState { final List<Object> eventQueue = new ArrayList<Object>(); boolean isPosting; boolean isMainThread; Subscription subscription; Object event; boolean canceled; }



其实就是事件发送的一个封装类,包括是否正在发送,是否主线程是否取消等,然后调用postSingleEvent方法,我们看如何实现的





private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { 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); subscriptionFound |= postSingleEventForEventType(event, postingState, clazz); } } else { subscriptionFound = postSingleEventForEventType(event, postingState, eventClass); } if (!subscriptionFound) { if (logNoSubscriberMessages) { Log.d(TAG, "No subscribers registered for event " + eventClass); } if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) { post(new NoSubscriberEvent(this, event)); } } }


做了很多处理 我们直接看postSingleEventForEventType方法,它返回了subscriptionFound 如果这个发送信息失败的话,就会打印出来,没有这个监听者,我们看一下postSingleEventForEventType是如何发送的。






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 { 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; }


我们可以看到它通过post的事件类型去从subscriptionsByEventType这个map中找到subscriptions这个对象然后调动postToSubscription这个方法最后释放之类的就不讲了,我们直接看postToSubscription这个方法


private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case POSTING: invokeSubscriber(subscription, event); break; case MAIN: if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(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); } }



这个方法上面也有提到 我们详细展开讲解,根据方法的一个线程模式采用四种不同的方式如果方法注册使用主线程方式那么如果发送也在主线程那么直接使用invokeSubscriber,这个其实是使用反射机制调用

void invokeSubscriber(Subscription subscription, Object event) { try { subscription.subscriberMethod.method.invoke(subscription.subscriber, event); } catch (InvocationTargetException e) { handleSubscriberException(subscription, event, e.getCause()); } catch (IllegalAccessException e) { throw new IllegalStateException("Unexpected exception", e); } }


如果注册主线程但是发送广播是在子线程的话,那么使用 mainThreadPoster.enqueue(subscription, event);
mainThreadPoster这个类之前也有讲过 其实就是继承Runnable开启了一个线程我们回顾一下源码


final class HandlerPoster extends Handler { private final PendingPostQueue queue; private final int maxMillisInsideHandleMessage; private final EventBus eventBus; private boolean handlerActive; HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) { super(looper); this.eventBus = eventBus; this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage; queue = new PendingPostQueue(); } void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); synchronized (this) { queue.enqueue(pendingPost); if (!handlerActive) { handlerActive = true; if (!sendMessage(obtainMessage())) { throw new EventBusException("Could not send handler message"); } } } } @Override public void handleMessage(Message msg) { boolean rescheduled = false; try { long started = SystemClock.uptimeMillis(); while (true) { PendingPost pendingPost = queue.poll(); if (pendingPost == null) { synchronized (this) { // Check again, this time in synchronized pendingPost = queue.poll(); if (pendingPost == null) { handlerActive = false; return; } } } eventBus.invokeSubscriber(pendingPost); long timeInMethod = SystemClock.uptimeMillis() - started; if (timeInMethod >= maxMillisInsideHandleMessage) { if (!sendMessage(obtainMessage())) { throw new EventBusException("Could not send handler message"); } rescheduled = true; return; } } } finally { handlerActive = rescheduled; } } }





这里其实就是通过handler来调用 eventBus.invokeSubscriber(pendingPost);来执行反射操作,换汤不换药
如果你方法注册用BACKGROUND且发送在主线程那么就使用BackgroundPoster,它其实就是一个线程,run方法的意思就是死循环然后将消息队列里面的所有信息全部调用反射去执行
如果你方法注册使用ASYNC 那么就会使用 asyncPoster.enqueue(subscription, event);这个asyncPoster其实也是一个线程,只是它每次取队列的一个进行反射调用
我们最后看一下反注册方法unregister方法



public synchronized void unregister(Object subscriber) { List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber); if (subscribedTypes != null) { for (Class<?> eventType : subscribedTypes) { unsubscribeByEventType(subscriber, eventType); } typesBySubscriber.remove(subscriber); } else { Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass()); } } private void unsubscribeByEventType(Object subscriber, Class<?> eventType) { 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; subscriptions.remove(i); i--; size--; } } } } ``` 其实它很简单 就是将typesBySubscriber这个map中的对应key和value给删除掉 这样post方法就找不到这个 subscriptionsByEventType这个map也要删除掉对应的信息。 4.总结 看完了源码我们至少要懂得几个东西,一个是EventBus是靠两个关键的map来维护的,通过发送的事件类型来找到对应的方法来通过反射机制调用这个方法,这中间还穿插着很多知识点,像不同的线程采用不同的分发器,对方法的解析(反射拿到类所有方法进行遍历 )和封装等。

  TOC