1. EventBus简介
EventBus是一款在Android开发中使用的发布/订阅事件总线框架,基于观察者模式,将事件的接收者和发送者分开,简化了组件之间的通信,尤其是碎片之间进行通信的问题,可以避免由于使用广播通信而带来的诸多不便。 使用简单、效率高、体积小!下边是官方的 EventBus 原理图:
2. EventBus使用方法
2.1 使用步骤
a. 添加依赖库 在项目对应的build.gradle文件添加
compile 'org.greenrobot:eventbus:3.0.0'
b. 注册
EventBus.getDefault().register(this);
c. 注销
EventBus.getDefault().unregister(this);
d. 构造发送事件类
public class MyEvent {
private int mMsg;
public MyEvent(int msg) {
mMsg = msg;
}
public int getMsg(){
return mMsg;
}
}
e. 发布事件
EventBus.getDefault().post(new MyEvent(time));
f. 接收事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(MyEvent event){
progressBar.setProgress(event.getMsg());
}
onEvent为Subscriber,MyEvent为监听的事件类型
2.2 使用示例
实现一个进度条,线程A发送进度百分比,线程B接收进度百分比并显示 参考:https://blog.csdn.net/bzlj2912009596/article/details/81664984 a. build.gradle
dependencies {
compile 'org.greenrobot:eventbus:3.0.0'
}
b. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.wgh.eventbusdemo.MainActivity"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progressbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:max="100"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>
<Button
android:id="@+id/button"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始下载"/>
</LinearLayout>
c. MainActivity.java
package com.example.wgh.eventbusdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class MainActivity extends Activity {
public ProgressBar progressBar = null;
public int time = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
while (time<100){
time += 15;
EventBus.getDefault().post(new MyEvent(time));
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
progressBar = (ProgressBar) findViewById(R.id.progressbar);
EventBus.getDefault().register(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(MyEvent event){
progressBar.setProgress(event.getMsg());
}
}
d. MyEvent.java
public class MyEvent {
private int mMsg;
public MyEvent(int msg) {
mMsg = msg;
}
public int getMsg(){
return mMsg;
}
}
注意:发送的消息和接收消息的函数参数必须一致,否则接收消息的函数无法接收到消息 例如发送消息:EventBus.getDefault().post(new MyEvent1(time));时,只有消息函数1能接收到消息。 接收消息函数1:public void onEvent(MyEvent1 event){…} 接收消息函数2:public void onEvent(MyEvent2 event){…}
3. EventBus原理
3.1 Subscribe注解
EventBus3.0 开始用Subscribe注解配置事件订阅方法,不再使用方法名了
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
ThreadMode threadMode() default ThreadMode.POSTING;
boolean sticky() default false;
int priority() default 0;
}
- ThreadMode.POSTING,默认的线程模式,在那个线程发送事件就在对应线程处理事件,避免了线程切换,效率高。
- ThreadMode.MAIN,如在主线程(UI线程)发送事件,则直接在主线程处理事件;如果在子线程发送事件,则先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。
- ThreadMode.MAIN_ORDERED,无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。
- ThreadMode.BACKGROUND,如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件;如果在子线程发送事件,则直接在发送事件的线程处理事件。
- ThreadMode.ASYNC,无论在那个线程发送事件,都将事件入队列,然后通过线程池处理。
3.2 Subscribers和Events之间的关系
注册的Subscriber将会保存到subscriptionsByEventType和typesBySubscriber a. subscriptionsByEventType
subscriptionsByEventType是一个HashMap,key为注册Subscriber监听事件的事件类型eventType,value为所有监听相同事件类型为eventType的Subscriber b. typesBySubscriber
typesBySubscriber是一个HashMap,key为注册Subscriber的当前类MainActivity,value为当前类包含的所有类型Subscriber
3.3 粘性事件
一般情况,我们使用EventBus都是准备好订阅事件的方法,然后注册事件,最后在发送事件,即要先有事件的接收者。但粘性事件却恰恰相反,我们可以先发送事件,然后再准备订阅事件的方法、注册事件,这种事件即为粘性事件。 即一般事件先注册监听某事件的Subscriber,再发送此事件;但是粘性事件是先发送某事件,再注册该事件的Subscriber
4. EventBus源码分析
4.1 register注册事件
EventBus.getDefault().register(this);
源码分析:
EventBus.java (frameworks\base\packages\systemui\src\com\android\systemui\recents\events) 39817 2017/8/25
public class EventBus extends BroadcastReceiver {
public static EventBus getDefault() {
if (sDefaultBus == null)
synchronized (sLock) {
if (sDefaultBus == null) {
if (DEBUG_TRACE_ALL) {
logWithPid("New EventBus");
}
sDefaultBus = new EventBus(Looper.getMainLooper());
}
}
return sDefaultBus;
}
}
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
subscriber为MainActivity,subscriberMethods为保存了当前注册类MainActivity及其父类中所有订阅事件的方法的集合
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);
}
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) {
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);
}
}
}
注册的Subscriber将会保存到subscriptionsByEventType和typesBySubscriber subscriptionsByEventType是一个HashMap,key为注册Subscriber监听事件的事件类型eventType,value为所有监听相同事件类型为eventType的Subscriber typesBySubscriber是一个HashMap,key为注册Subscriber的当前类MainActivity,value为当前类包含的所有类型Subscriber
4.2 post发送事件
EventBus.getDefault().post(new MyEvent(time));
源码分析:
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
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()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
将发送的事件保存到eventQueue,并遍历eventQueue执行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) {
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 {
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;
}
根据当前发送事件的事件类型,从subscriptionsByEventType中获所有监听此事件类型的Subscriber,遍历这些Subscriber并执行postToSubscription进行进一步处理,即所有监听此事件的Subscriber对应的方法都会被调用
4.3 处理事件
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 MAIN_ORDERED:
if (mainThreadPoster != null) {
mainThreadPoster.enqueue(subscription, event);
} else {
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 {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
使用反射来执行订阅事件event的方法onEvent,这样发送出去的事件就被订阅者Subscriber接收并做相应处理了
4.4 粘性事件
EventBus.getDefault().postSticky(new MyEvent(time));
源码分析:
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
post(event);
}
将发送的粘性事件保存到stickyEvents中
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
......
......
......
if (subscriberMethod.sticky) {
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)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
if (stickyEvent != null) {
postToSubscription(newSubscription, stickyEvent, isMainThread());
}
}
eventType为当前Subscriber监听的事件类型,从stickyEvents取出发送的粘性事件,如果注册的Subscriber监听的事件类型正好为粘性事件的事件类型,则直接调用checkPostStickyEventToSubscription进行事件处理
5. EventBus总结
- 注册事件:将注册的Subscriber保存到subscriptionsByEventType和typesBySubscriber
subscriptionsByEventType是一个HashMap,key为注册Subscriber监听事件的事件类型eventType,value为所有监听相同事件类型为eventType的Subscriber typesBySubscriber是一个HashMap,key为注册Subscriber的当前类MainActivity,value为当前类包含的所有类型Subscriber - 发送事件:根据当前发送事件的事件类型,从subscriptionsByEventType中获所有监听此事件类型的Subscriber,遍历这些Subscriber并执行postToSubscription进行进一步处理,即所有监听此事件的Subscriber对应的方法都会被调用
- 处理事件:使用反射来执行订阅事件event的方法onEvent,这样发送出去的事件就被订阅者Subscriber接收并做相应处理了
好文章: https://www.jianshu.com/p/d9516884dbd4 https://www.6hu.cc/archives/215.html
|