Android系统之EventBus用法及源码分析

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 {
	//1. 添加依赖库
    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;
							//4. 发送消息
                            EventBus.getDefault().post(new MyEvent(time));
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
		//2. 注册EventBus
        EventBus.getDefault().register(this);
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
		//6. 注销EventBus
        EventBus.getDefault().unregister(this);
    }
	//5. 接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MyEvent event){
        progressBar.setProgress(event.getMsg());
    }
}

d. MyEvent.java

//3. 构造发送消息类
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 {
    // 指定事件订阅方法的线程模式,即在那个线程执行事件订阅方法处理事件,默认为POSTING
    ThreadMode threadMode() default ThreadMode.POSTING;
    // 是否支持粘性事件,默认为false
    boolean sticky() default false;
    // 指定事件订阅方法的优先级,默认为0,如果多个事件订阅方法可以接收相同事件的,则优先级高的先接收到事件
    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();	//获取当前注册Subscriber的类,此处为MainActivity
	List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);	//获取当前类中的所有注册事件的函数,即获取所有Subscribe注解的函数
	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);	//1. 创建当前监听事件对应的Subscription
	CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);	//1. 重点:subscriptionsByEventType是一个HashMap,key为eventType事件类型,value为所有监听相同事件类型的函数
	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);		//1. 将注册的Subscriber保存到subscriptionsByEventType
			break;
		}
	}
	//-------------------------------------------
	List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);	//2. 重点:typesBySubscriber是一个HashMap,key为注册subscriber的当前类MainActivity,value为当前类包含的所有类型Subscriber
	// 不存在则创建一个subscribedEvents,并保存到typesBySubscriber
	if (subscribedEvents == null) {
		subscribedEvents = new ArrayList<>();
		typesBySubscriber.put(subscriber, subscribedEvents);
	}
	subscribedEvents.add(eventType);	//2. 将注册的Subscriber对应的事件类型eventType保存到typesBySubscriber
	// 粘性事件相关的,后边具体分析
	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);
		}
	}
}

注册的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) {
	// currentPostingThreadState是一个PostingThreadState类型的ThreadLocal
	// PostingThreadState类保存了事件队列和线程模式等信息
	PostingThreadState postingState = currentPostingThreadState.get();
	List<Object> eventQueue = postingState.eventQueue;
	// 将要发送的事件添加到事件队列
	eventQueue.add(event);
	// isPosting默认为false
	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()) {
				// 发送单个事件
				// eventQueue.remove(0),从事件队列移除事件
				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;
	// eventInheritance默认为true,表示是否向上查找事件的父类
	if (eventInheritance) {
		// 查找当前事件类型的Class,连同当前事件类型的Class保存到集合
		List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
		int countTypes = eventTypes.size();
		// 遍历Class集合,继续处理事件
		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) {
		// 获取事件类型对应的Subscription集合
		subscriptions = subscriptionsByEventType.get(eventClass);
	}
	// 如果已订阅了对应类型的事件
	if (subscriptions != null && !subscriptions.isEmpty()) {
		for (Subscription subscription : subscriptions) {
			// 记录事件
			postingState.event = event;
			// 记录对应的subscription
			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 {
				 // 如果是在子线程发送事件,则将事件入队列,通过Handler切换到主线程执行处理事件
				// mainThreadPoster 不为空
				mainThreadPoster.enqueue(subscription, event);
			}
			break;
		// 无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。
		// mainThreadPoster 不为空
		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) {
	......
	......
	......
	// 如果当前订阅事件的方法的Subscribe注解的sticky属性为true,即该方法可接受粘性事件
	if (subscriberMethod.sticky) {
		// 默认为true,表示是否向上查找事件的父类
		if (eventInheritance) {
			// stickyEvents就是发送粘性事件时,保存了事件类型和对应事件
			Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
			for (Map.Entry<Class<?>, Object> entry : entries) {
				Class<?> candidateEventType = entry.getKey();
				// 如果candidateEventType是eventType的子类或
				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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值