标签:
compile 'org.greenrobot:eventbus:3.0.0' provided 'org.glassfish:javax.annotation:10.0-b28' //解决获取不到@Subscribe注解的问题
public class IntentServiceResult { int mResult; String mResultValue; IntentServiceResult(int resultCode, String resultValue) { mResult = resultCode; mResultValue = resultValue; } public int getResult() { return mResult; } public String getResultValue() { return mResultValue; } }
public class MainActivity extends AppCompatActivity { @Override protected void onPause() { super.onPause(); EventBus.getDefault().unregister(this); //注:为了后面分析的方便我们对进行注册的对象取名订阅者,如这里的MainActivity.this对象 } @Override protected void onResume() { super.onResume(); EventBus.getDefault().register(this); } }
EventBus.getDefault().post(new IntentServiceResult(24, "done!!"));
public class MainActivity extends AppCompatActivity { @Subscribe(threadMode = ThreadMode.MAIN) public void doThis(IntentServiceResult intentServiceResult) { Toast.makeText(this, intentServiceResult.getResultValue(), Toast.LENGTH_SHORT).show(); } }
/*****下面的数据在EventBus自身构造器中被创建*****/ private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; //以事件类型为key,该事件对应的Subscription集合为value;此处使用CopyOnWrite的好处在于它是线程安全的集合,同一时间只有一个线程可以修改该集合的数据! private final Map<Object, List<Class<?>>> typesBySubscriber; //以注册EventBus的对象(该对象会接收EventBus发来的事件)为key,该对象接收的事件类型为Value private final Map<Class<?>, Object> stickyEvents; //sticky在@Subscribe标注时设置(sticky=true), sticky默认是false;直译过来是粘性事件、说人话那就是该类事件会一直被EventBus所保存,除非用户手动删除!同时从Map<Class<?>, Object>可以看出任何类型的事件只会保存一个对应的实例! private final HandlerPoster mainThreadPoster; //对应ThreadMode.MAIN模式,是一个继承Handler的类 private final BackgroundPoster backgroundPoster; //对应ThreadMode.BACKGROUND模式,是一个实现了Runnable方法的类 private final AsyncPoster asyncPoster; //对应ThreadMode.ASYNC模式,是一个实现了Runnable方法的类 /*****下面的数据都是来自EventBusBuilder*****/ private final int indexCount; //一般情况为0,是EventBuilder.subscriberInfoIndexes.size()的值 private final SubscriberMethodFinder subscriberMethodFinder; //订阅方法查找器负责对目标对象中使用了@Subscribe进行标注的方法进行解析得到一个SubscriberMethod对象 private final boolean logSubscriberExceptions; //一般情况为true private final boolean logNoSubscriberMessages; //一般情况为true private final boolean sendSubscriberExceptionEvent; //一般情况为true private final boolean sendNoSubscriberEvent; //一般情况为true private final boolean throwSubscriberException; //一般情况为false private final boolean eventInheritance; //一般情况为true,事件是否具有传递性的标志位 private final ExecutorService executorService; //执行器,对应一个Executors.newCachedThreadPool()线程池 /*****下面的对象创建时初始化或者类加载时初始化*****/ static volatile EventBus defaultInstance; //单例 private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder(); //创建EventBus对象的Builder private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>(); //以事件类型为key,其对应的所以父类、实现的所有接口及接口父类为value private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() { @Override protected PostingThreadState initialValue() { return new PostingThreadState(); } }; //当前线程的PostingThreadState对象,之后通过get方法获取该对象
public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) {defaultInstance = new EventBus();} } } return defaultInstance; }
public EventBus() { this(DEFAULT_BUILDER); } 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; //一般情况为0 subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,builder.strictMethodVerification, builder.ignoreGeneratedIndex); //一般情况参数为null、false、false;该对象我们后面会介绍 logSubscriberExceptions = builder.logSubscriberExceptions; //一般情况为true logNoSubscriberMessages = builder.logNoSubscriberMessages; //一般情况为true sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent; //一般情况为true sendNoSubscriberEvent = builder.sendNoSubscriberEvent;//一般情况为true throwSubscriberException = builder.throwSubscriberException; //一般情况为false eventInheritance = builder.eventInheritance; //一般情况为true executorService = builder.executorService; //一个newCachedThreadPool() }
private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool(); List<SubscriberInfoIndex> subscriberInfoIndexes; boolean strictMethodVerification; boolean ignoreGeneratedIndex; boolean logSubscriberExceptions = true; boolean logNoSubscriberMessages = true; boolean sendSubscriberExceptionEvent = true; boolean sendNoSubscriberEvent = true; boolean throwSubscriberException; boolean eventInheritance = true; ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE; //总结:eventInheritance、logXX和sendXX全为true;其它全为false;
public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass(); List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); //note1 synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { //note2 subscribe(subscriber, subscriberMethod); } } }
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { Class<?> eventType = subscriberMethod.eventType; //note1 Subscription newSubscription = new Subscription(subscriber, subscriberMethod); //note2 CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); //note3 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(); //note4 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); //note5 if (subscribedEvents == null) { subscribedEvents = new ArrayList<>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); if (subscriberMethod.sticky) { //note6 if (eventInheritance) { Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet(); for (Map.Entry<Class<?>, Object> entry : entries) { Class<?> candidateEventType = entry.getKey(); if (eventType.isAssignableFrom(candidateEventType)) { //从stickyEvents获取对应的事件交给当前事件订阅者处理 Object stickyEvent = entry.getValue(); checkPostStickyEventToSubscription(newSubscription, stickyEvent); //该方法底层还是会执行postToSubscription方法 } } } else { Object stickyEvent = stickyEvents.get(eventType); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } }
public void postSticky(Object event) { synchronized (stickyEvents) { stickyEvents.put(event.getClass(), event); } post(event); }
public <T> T removeStickyEvent(Class<T> eventType) { synchronized (stickyEvents) { return eventType.cast(stickyEvents.remove(eventType)); } }
public synchronized void unregister(Object subscriber) { List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);//note1 if (subscribedTypes != null) { for (Class<?> eventType : subscribedTypes) { unsubscribeByEventType(subscriber, eventType); // } typesBySubscriber.remove(subscriber); //note3 } 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); //note1 if (subscriptions != null) { int size = subscriptions.size(); for (int i = 0; i < size; i++) { Subscription subscription = subscriptions.get(i); if (subscription.subscriber == subscriber) { //note2 subscription.active = false; subscriptions.remove(i); i--; size--; } } } }
public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); //note1 List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event); //note2 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);//note3 } } finally { postingState.isPosting = false; postingState.isMainThread = false; } } }
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() { @Override protected PostingThreadState initialValue() { return new PostingThreadState(); } //当前推送线程状态 };
final static class PostingThreadState { final List<Object> eventQueue = new ArrayList<Object>(); //待派送的事件队列 boolean isPosting; //当前PostingThreadState对象是否正在派送事件的标志位 boolean isMainThread; //当前PostingThreadState对象是否是工作在UI线程的标志位 Subscription subscription; //事件处理器 Object event; //待处理事件 boolean canceled; //是否取消事件派送的标志位 }
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { Class<?> eventClass = event.getClass(); boolean subscriptionFound = false; if (eventInheritance) { List<Class<?>> eventTypes = lookupAllEventTypes(eventClass); //note2 int countTypes = eventTypes.size(); for (int h = 0; h < countTypes; h++) { //note3 Class<?> clazz = eventTypes.get(h); subscriptionFound |= postSingleEventForEventType(event, postingState, clazz); } } else { subscriptionFound = postSingleEventForEventType(event, postingState, eventClass); } if (!subscriptionFound) { //note4 if (logNoSubscriberMessages) { Log.d(TAG, "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);//note1 } if (subscriptions != null && !subscriptions.isEmpty()) { for (Subscription subscription : subscriptions) { postingState.event = event; postingState.subscription = subscription; boolean aborted = false; try { postToSubscription(subscription, event, postingState.isMainThread); //note2 aborted = postingState.canceled; } finally { postingState.event = null; postingState.subscription = null; postingState.canceled = false; } if (aborted) { break; } } return true; } return false; }
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { //第一个参数是事件处理器、第二个参数是待处理事件、第三个为当前线程是否是UI线程的标志位 switch (subscription.subscriberMethod.threadMode) { case POSTING: //note1 invokeSubscriber(subscription, event); break; case MAIN: //note2 if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(subscription, event); } break; case BACKGROUND: //note3 if (isMainThread) { backgroundPoster.enqueue(subscription, event); } else { invokeSubscriber(subscription, event); } break; case ASYNC: //note4 asyncPoster.enqueue(subscription, event); break; default: throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode); } }
void invokeSubscriber(Subscription subscription, Object event) { try { subscription.subscriberMethod.method.invoke(subscription.subscriber, event);//note1 } catch (...) { .... } }
void invokeSubscriber(PendingPost pendingPost) { Object event = pendingPost.event; Subscription subscription = pendingPost.subscription; PendingPost.releasePendingPost(pendingPost); if (subscription.active) { invokeSubscriber(subscription, event); //note1 } }
final class Subscription { final Object subscriber; //订阅者 final SubscriberMethod subscriberMethod; //对订阅者使用@Subscribe标注的方法进行转化后得到的对象 volatile boolean active; Subscription(Object subscriber, SubscriberMethod subscriberMethod) { this.subscriber = subscriber; this.subscriberMethod = subscriberMethod; active = true; } @Override public boolean equals(Object other) { if (other instanceof Subscription) { Subscription otherSubscription = (Subscription) other; return subscriber == otherSubscription.subscriber &&subscriberMethod.equals(otherSubscription.subscriberMethod); } else { return false; } } @Override public int hashCode() { return subscriber.hashCode() + subscriberMethod.methodString.hashCode();}//map集合中会用到 }
public class SubscriberMethod { final Method method; final ThreadMode threadMode; //Method线程模式,确定当前Method执行的线程 final Class<?> eventType; //Method接收的参数类型 final int priority; //Method的优先级 final boolean sticky; //@Subscribe sticky标志位 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; } .... }
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>(); /*以订阅者为key, 以对订阅者使用@Subscribe标注的方法进行转化后得到的SubscriberMethod对象集合为value;用作缓存,毕竟解析过程会比较耗时。 注意!!!!!这里的MAP的key是订阅者对应的Class对象,而不是订阅者本身(Object对象);因为SubscribeMethod只跟Class有关而跟具体的Object无关; 一个类的不同实例具有同样的SubscribeMethod对象!而EventBus中必须以Object为key,因为事件处理方法大多数不是静态方法, 可能需要访问所属对象的状态(对象中的非static域)!*/ private static final int POOL_SIZE = 4; private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE]; //FindState的对象池,对象池是一种提高资源重复利用率普遍采用的一种做法 private List<SubscriberInfoIndex> subscriberInfoIndexes; //默认为空 private final boolean strictMethodVerification; //默认为false private final boolean ignoreGeneratedIndex; //默认为false
SubscriberMethodFinder(List<SubscriberInfoIndex> subscriberInfoIndexes, boolean strictMethodVerification, boolean ignoreGeneratedIndex) { //一般情况参数为null、false、false this.subscriberInfoIndexes = subscriberInfoIndexes; this.strictMethodVerification = strictMethodVerification; this.ignoreGeneratedIndex = ignoreGeneratedIndex; }
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) { List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass); //note1 if (subscriberMethods != null) { return subscriberMethods; } if (ignoreGeneratedIndex) { subscriberMethods = findUsingReflection(subscriberClass); } else { subscriberMethods = findUsingInfo(subscriberClass); } //note2 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); //note3 return subscriberMethods; } }
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) { FindState findState = prepareFindState();//note1 findState.initForSubscriber(subscriberClass); //note2 while (findState.clazz != null) { findState.subscriberInfo = getSubscriberInfo(findState); //note3 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); } //note4 findState.moveToSuperclass(); //note5 } return getMethodsAndRelease(findState); //note6 }
private FindState prepareFindState() { synchronized (FIND_STATE_POOL) { for (int i = 0; i < POOL_SIZE; i++) { FindState state = FIND_STATE_POOL[i]; if (state != null) { FIND_STATE_POOL[i] = null; return state; } } } return new FindState(); }
private SubscriberInfo getSubscriberInfo(FindState findState) { if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) { //note1 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) { return info; } } } return null; }
private void findUsingReflectionInSingleClass(FindState findState) { Method[] methods; try { methods = findState.clazz.getDeclaredMethods(); //note1 } catch (Throwable th) { methods = findState.clazz.getMethods(); findState.skipSuperClasses = true; //跳过超类标志位设为true } for (Method method : methods) { int modifiers = method.getModifiers(); //note2 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)) { //note3 ThreadMode threadMode = subscribeAnnotation.threadMode(); //note4 findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode, subscribeAnnotation.priority(), subscribeAnnotation.sticky())); //note5 } } } 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"); } } //end of for }
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) { List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods); //note1 findState.recycle(); //note2 synchronized (FIND_STATE_POOL) { //note3 for (int i = 0; i < POOL_SIZE; i++) { if (FIND_STATE_POOL[i] == null) { FIND_STATE_POOL[i] = findState; break; } } } return subscriberMethods; //note4 }
final Map<Class, Object> anyMethodByEventType = new HashMap<>(); final List<SubscriberMethod> subscriberMethods = new ArrayList<>(); Class<?> subscriberClass; Class<?> clazz; //用以遍历subscriberClass的所有父类 boolean skipSuperClasses; SubscriberInfo subscriberInfo;
void initForSubscriber(Class<?> subscriberClass) { this.subscriberClass = clazz = subscriberClass; skipSuperClasses = false; //不跳过当前类的父类 subscriberInfo = null; }
boolean checkAdd(Method method, Class<?> eventType) { Object existing = anyMethodByEventType.put(eventType, method); if (existing == null) { return true; } ...... }
private final static List<PendingPost> pendingPostPool = new ArrayList<PendingPost>(); //PendingPost对象池 Object event; //待处理事件 Subscription subscription; //处理上述事件的方法 PendingPost next;
private PendingPost(Object event, Subscription subscription) { this.event = event; this.subscription = subscription; }
static PendingPost obtainPendingPost(Subscription subscription, Object event) { synchronized (pendingPostPool) { int size = pendingPostPool.size(); if (size > 0) { PendingPost pendingPost = pendingPostPool.remove(size - 1); pendingPost.event = event; pendingPost.subscription = subscription; pendingPost.next = null; return pendingPost; } } return new PendingPost(event, subscription); }
static void releasePendingPost(PendingPost pendingPost) { pendingPost.event = null; pendingPost.subscription = null; pendingPost.next = null; synchronized (pendingPostPool) { if (pendingPostPool.size() < 10000) {pendingPostPool.add(pendingPost); } } } }
private final PendingPostQueue queue; private final EventBus eventBus; private boolean handlerActive; private final int maxMillisInsideHandleMessage;
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); //note1 synchronized (this) { queue.enqueue(pendingPost); if (!handlerActive) { handlerActive = true; if (!sendMessage(obtainMessage())) { throw new EventBusException("Could not send handler message");}//note2 } } }
public void handleMessage(Message msg) { boolean rescheduled = false; try { long started = SystemClock.uptimeMillis(); //note1 while (true) { PendingPost pendingPost = queue.poll(); //note2 if (pendingPost == null) { synchronized (this) { pendingPost = queue.poll(); if (pendingPost == null) { handlerActive = false; return;} } } eventBus.invokeSubscriber(pendingPost); //note3 long timeInMethod = SystemClock.uptimeMillis() - started; //note4 if (timeInMethod >= maxMillisInsideHandleMessage) { if (!sendMessage(obtainMessage())) { throw new EventBusException("Could not send handler message"); } rescheduled = true; return; } } } finally { handlerActive = rescheduled; } } }
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); //note1 if (!executorRunning) { executorRunning = true; eventBus.getExecutorService().execute(this); //note2 } } }
public void run() { try { try { while (true) { PendingPost pendingPost = queue.poll(1000); if (pendingPost == null) { synchronized (this) { pendingPost = queue.poll(); if (pendingPost == null) {executorRunning = false; return;} } } eventBus.invokeSubscriber(pendingPost); //思路都是一样的 }//end of while }//end of second try catch (InterruptedException e) { Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);} } //end of first try finally { executorRunning = false; } }//end of function
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); }
public void run() { PendingPost pendingPost = queue.poll(); if(pendingPost == null) {throw new IllegalStateException("No pending post available"); } eventBus.invokeSubscriber(pendingPost); } }
标签:
原文地址:http://blog.csdn.net/evan_man/article/details/51328628