记得年初公司招人,在面试的过程中我问过这个问题“android中两个Activity之间常用的传递消息的方式有哪些?”
应聘者的答案集中在
1.Intent
2.广播
3.全局变量和Application
4.Android系统剪切板
5.本地化存储方式
6.一些android组建
一部分还能说出**“事件总线(如EventBus)”**
所以今天就来分享一下我自己使用EventBus的一些体会和感想。
1.EventBus的基本用法
EventBus的使用可以分为以下5个步骤:
(1)自定义一个事件类
public class MessageEvent{
```
}
(2)在需要订阅的地方注册事件
EventBus.getDefault().register(this);
(3)发送事件
EventBus.getDefault().post(messageEvent);
(4)处理事件
@Subscribe(threadMode=ThreadMode.MAIN)
public void XXX(MessageEvent messageEvent){
```
}
(5)取消事件订阅
EventBus.getDefault().unregister(this);
一.EventBus应用
上面提到了EventBus的基本用法,但是这样说过于简单,下面来举例应用EventBus。
(1)添加依赖库
首先配置gradle,如下所示:
compile 'org.greenrobot:eventbus:3.0.0'
(2)自定义消息事件
public class MessageEvent{
private String message1;
public MessageEvent(String message){
this.message1=message;
}
public String getMessage(){
return message1;
}
public void setmessage(int message){
this.message1=message;
}
}
(3)注册和取消订阅事件
在MainActivity中注册和取消订阅事件,如下所示:
public class MainActivity extends Activity{
@Override
protect void OnCreate(Bundle savedInteanceState){
super.Oncreate(savedInteanceState);
setContentView(R.layout.acitivity_main);
//注册事件
EventBus.getDefault().register(MainActivity.this);
}
@Override
protected void onDestroy(){
super.onDestroy();
//取消注册事件
EventBus.getDefault().unregister(this);
}
}
(4)事件订阅处理事件
在MainActivity中自定义方法来处理事件,在这里ThreadMode设置为MAIN,事件的处理会在UI线程中执行,用TextView来展示收到的事件消息:
@Subscribe(threadMode=ThreadMode.MAIN)
public void onMoonEvent(MessageEvent messageEvent){
tv_message.setText(messageEvent.getMessage());
}
(5)事件发布者发布事件
Eventbus.getDefault().post(new MessageEvent("欢迎来到EventBus的世界!");
(6)ProGuard混淆规则
最后不要忘了在ProGuard中加入如下混淆规则:
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
#Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
二.EventBus的粘性事件
除了上述的普通事件之外,EventBus还支持发送粘性事件,就是在发送事件之后再订阅该事件也能收到该事件,这跟粘性广播类似。为了验证粘性事件,我们修改以前的代码,如下:
(1)订阅者处理粘性事件
@subscribe(threadMode=threadMode.POSTING,sticky=true)
public void onMoonstickyEvent(MessageEvent messageEvent){
tv_message.setText(messageEvent.getMessage());
}
(2)发送粘性事件
EventBus.getDefault().postSticky(new MessageEvent("粘性事件"));
2.EventBus源码解析
前面介绍了EventBus的用法,下面我们就从EventBus的源码分析一下
1.EventBus 的构造方法
当我们要使用EventBus时,首先会调用EventBus.getDefault()来获取EventBus实例。现在就可以getDefault方法做了什么,如下所示:
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
典型的单例模式,使用了双重检查锁(DCL)。
下面我们看EventBus的构造方法做了什么:
public EventBus() {
this(DEFAULT_BUILDER);
}
默认使用EventBusBuilder来构造EventBus:
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
this调用了EventBus的另一个构造方法,如下所示:
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;
}
通过构造一个EventBusBuilder 对EventBus进行配置,采用建造者模式。
2.订阅者注册
获取到EventBus之后,就可以把订阅者注册到EventBus中了,下面看一下register方法:
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);//A1
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);//A2
}
}
}
(1)查找订阅者的订阅方法
上面代码注释A1处的findSubscriberMethods方法找出一个SubscriberMethod的集合,也就是传进来的订阅者的所有订阅方法,接下来遍历订阅者的订阅方法来完成订阅者的注册操作。可以看出register方法做了两件事:
1.查找订阅者的订阅方法;
2.订阅者的注册
在SubscriberMethod类中,主要用来保存订阅方法的Method对象、线程模式、事件类型、优先级、是否粘性等属性。下面来看看findSubscriberMethods方法:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);//B1
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
subscriberMethods = findUsingInfo(subscriberClass);//B3
}
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);//B2
return subscriberMethods;
}
}
以上代码注释B1处从缓存中查找是否有订阅方法的集合,如果找到了就马上返回。如果缓存中没有,则根据ignoreGeneratedIndex属性的值来选择采用何种方法来查找订阅方法的集合。ignoreGeneratedIndex表示是否忽略注解器生成的MyEventBusIndex类以及它的使用,可以参考官方文档,这里就不再赘述。ignoreGeneratedIndex的默认值是false,可以通过EventBusBuilder来设置它的值。在注释B2出找到了订阅方法的集合后,放入缓存,以免下次继续查找。我们在项目中经常通过EventBus单例模式来获取默认的EventBus对象,也就是ignoreGeneratedIndex为false的情况,这种情况调用了注释B3处的findUsingInfo方法:
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findState.subscriberInfo = getSubscriberInfo(findState);//C1
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();//C2
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
findUsingReflectionInSingleClass(findState);//C3
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
以上代码注释C1处通过getSubscriberInfo方法来获取订阅者的信息。在开始查找订阅方法的时候并没有忽略注解器为我们生成的索引MyEventBusIndex。如果我们通过EventBusBuilder配置了MyEventBusIndex,便会获取subscriberInfo。注释C2处调用subscriberInfo的getSubscriberMethods方法可以得到订阅方法相关的信息。如果没有配置MyEventBusIndex,便会执行注释C3处的findUsingReflectionInSingleClass方法,将订方法保存到findState中。最后再通过getMethodsAndRelease方法对findState做回收处理并返回订阅方法的List集合。默认情况下是没有配置MyEventBusIndex的,因此查看findUsing-RefectionInSingleClass方法的执行过程,如下所示:
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();//D1
} 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");
}
}
}
从上面代码注释D1处通过反射来获取订阅者中所有的方法,并根据方法的类型、参数和注释来找到订阅方法。找到订阅方法的相关信息保存到findstates中。
(2)订阅者的注册过程
在找到订阅者的订阅方法之后便开始对所有注册方法进行注册。我们再回到register方法中,在那里的注释A2处调用了subscribe方法来对订阅者进行注册,如下所示:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);//E1
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//E2
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);//E3
break;
}
}
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);//E4
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();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
以上代码E1处会根据subscriber(订阅者)和subscriberMethod(订阅方法)创建一个Subscription(订阅对象)。注释E2处根据eventType(事件类型)获取Subscriptions(订阅对象集合)。如果Subscriptions为null则重新创建,并将Subscriptions根据eventType保存在subscriptionsByEventType(Map集合)注释E3处按照订阅方法的优先级插入到订阅对象集合中,完成订阅方法的注册。注释E4处通过subscriber获取subscribedEvents(事件类型集合)。如果subscribedEvents为null则重新创建,并将eventType添加到subscribedEvents中,并根据subscriber将subscribedEvents存储在typesBySubscriber(Map集合)。如果是粘性事件,则从stickyEvents事件保存队列中取出该事件类型的事件发送给当前订阅者。总结一下,subscribe方法主要就是做了两件事:一,将Subscriptions感觉eventType封装到subscriptionsByEventType中,将subscribedEvents根据subscriber封装到typesBySubscriber中;二,对粘性事件的处理。
3.事件的发送
在获取到EventBus对象之后,可以通过post方法来进行事件的提交。post方法的源码如下:
/** Posts the given event to the event bus. */
public void post(Object event) {
//PostingThreadState 保存了事件队列和线程状态信息
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对象中取出事件队列,然后再将当前的事件出入到事件队列。最后将队列中的事件依次交由postSingleEvent方法进行处理,并移除该事件。之后查看postSingleEvent方法里做了什么:
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//eventInheritance表示是否向上查找事件的父类,默认为true
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));
}
}
}
eventInheritance表示是否向上查找事件的父类,它的默认值是true,可以通过在EventBusBuilder中进行配置。当eventInheritance为true时,则通过loopupAllEventTypes找到所有的父类事件并存在List中,然后通过postSingleEventForEventType方法对事件逐一处理。postSingleEventForEventType方法的源码如下:
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);//F1
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {//F2
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;
}
上面代码注释F1处同步取出该事件对于的Subscriptions (订阅集合对象)。注释F2出遍历Subscriptions ,将事件event和对应的Subscription(订阅对象)传递给postingState并调用postToSubscription方法对事件进行处理.接下来查看postToSubsciption方法:
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);
}
}
取出订阅方法的threadMode(线程模式),之后根据threadMode来分别处理。如果threadMode是MAIN,若提交的线程是主线程,则通过反射直接运行订阅的方法;若其不是主线程,则需要mainThreadPoster将我们的订阅事件添加到主线程队列中。mainThreadPoster是HandlerPoster类型的,继承自Handler,通过Handler将订阅的方法切换到主线程执行。
4.订阅者的取消注册
取消注册需要调用unregister方法,如下所示:
public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);//G1
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);//G2
}
typesBySubscriber.remove(subscriber);//G3
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
在订阅者注册的过程中讲到typesBySubscriber,它是一个map集合。上面代码注释G1处通过subscriber找到subscribedTypes(事件类型集合)。注释G3处将subscriber对应的eventType从typesBySubscriber中移除。注释G2处遍历subscribedTypes,并调用unsubscribeByEventType方法:
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//H1
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--;
}
}
}
}
上面注释H1处通过对应的Subscriptions(订阅对象集合),并在for循环中判断如果Subscription(订阅对象)的subscriber(订阅者)属性等于传进来的subscriber,则从Subscirptions中移除该Subscription。