Android EventBus源码学习

2024-06-01 06:18
文章标签 android 源码 学习 eventbus

本文主要是介绍Android EventBus源码学习,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、Register(注册过程)

会调用private synchronized voidregister(Object subscriber, boolean sticky, int priority)
其中Object subscriber是注册代码所在函数的对象,就是消息的订阅者(subscriber),sticky指是否是粘性,priority是指订阅的优先级,这个函数的源码是:

List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass());
for (SubscriberMethod subscriberMethod : subscriberMethods) {subscribe(subscriber, subscriberMethod, sticky, priority);
}

这个方法详细解释:

(1)SubscriberMethod:这个类封装了三个对象,分别是:

final Method method

java里面的Method类,这个对象方便发送消息之后,调用invoke执行接收消息函数

final ThreadMode threadMode,定义接收到返回的数据所在的线程,有四种情况:
  • PostThread
    订阅者和消息发送者在同一个线程,这是默认的一种情况,
    当需要处理非常简单的单任务的时候,不依赖在主线程里面,建议使用这种模式
  • MainThread
    订阅者在主线程,即UI线程
  • BackgroundThread
    后台线程,订阅者在后台线程
  • Async
    异步线程,在订阅者方法里面实现耗时操作可以使用这种模式,应该避免大数量长时间的使用异步线程来处理消息,因为EventBus使用缓存线程池高效的回收利用线程完成处理的消息
final Class<?> eventType

订阅消息方法的参数类型(这个类型可以是基本类型,也可以是自己封装的类型)

(2) SubscriberMethodFinder

这个类主要用来查找消息订阅者函数

(3) findSubscriberMethods

查找注册消息订阅类的接收消息的函数,详解如下:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {String key = subscriberClass.getName();//获取注册类的名字,作为map的keyList<SubscriberMethod> subscriberMethods; //用于存储找到的订阅函数synchronized (methodCache) {subscriberMethods = methodCache.get(key);//首先查找是否在map里存在订阅函数}if (subscriberMethods != null) {return subscriberMethods;//如果在map里面找到了订阅函数就返回}subscriberMethods = new ArrayList<SubscriberMethod>();Class<?> clazz = subscriberClass;HashSet<String> eventTypesFound = new HashSet<String>();StringBuilder methodKeyBuilder = new StringBuilder();while (clazz != null) {String name = clazz.getName();if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {// Skip system classes, this just degrades performance 表明不支持系统的类break;}// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)Method[] methods = clazz.getDeclaredMethods();//获取注册所在类定义的函数for (Method method : methods) {//遍历函数查找订阅消息的函数String methodName = method.getName();//获取函数名//判断函数是否是以”onEvent开头”,此处说明定义消息订阅函数的时候要以”onEvent”开头if (methodName.startsWith(ON_EVENT_METHOD_NAME)) {int modifiers = method.getModifiers(); //获取订阅函数的修饰符(public,private,protected)//订阅者必须是public修饰的if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {Class<?>[] parameterTypes = method.getParameterTypes(); //获取订阅函数的参数类型if (parameterTypes.length == 1) {//只有一个参数</span>//获取除”onEvent”之外的字符,用于判断线程类型String modifierString = methodName.substring(ON_EVENT_METHOD_NAME.length());ThreadMode threadMode;//如果订阅函数的名字是”onEvent”,那么默认是PostThread类型if (modifierString.length() == 0) { threadMode = ThreadMode.PostThread;} else if (modifierString.equals("MainThread")) {//如果订阅函数的名字是”onEventMainThread”,那么是MainThread类型threadMode = ThreadMode.MainThread; } else if (modifierString.equals("BackgroundThread")) { //如果订阅函数的名字是”onEventBackgroundThread”,那么是BackgroundThread类型threadMode = ThreadMode.BackgroundThread; } else if (modifierString.equals("Async")) {//如果订阅函数的名字是”onEventAsync”,那么是Async类型threadMode = ThreadMode.Async; } else {//特殊情况继续if (skipMethodVerificationForClasses.containsKey(clazz)) {continue;} else {//否则注册消息不合法throw new EventBusException("Illegal onEvent method, check for typos: " + method);}}Class<?> eventType = parameterTypes[0];methodKeyBuilder.setLength(0);methodKeyBuilder.append(methodName);methodKeyBuilder.append('>').append(eventType.getName());//将订阅函数,订阅函数的类型放到StringBuffer里面String methodKey = methodKeyBuilder.toString();//Haset的值唯一性,如果之前存在就不添加到订阅集合里面去if (eventTypesFound.add(methodKey)) { // Only add if not already found in a sub class// SubscriberMethod封装了Method方法,订阅函数所处的线程,订阅函数参数类型的名字             subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType)); } }} else if (!skipMethodVerificationForClasses.containsKey(clazz)) { Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "." + methodName); }} } clazz = clazz.getSuperclass(); }//为空,表明没有在注册的类里面找到订阅消息的函数,抛出没有找到用public修饰的订阅函数if (subscriberMethods.isEmpty()) { throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called " + ON_EVENT_METHOD_NAME); }else {//在map容器里面添加订阅<key=注册函数所属的类,value=List<SubscriberMethod>>synchronized (methodCache) { methodCache.put(key, subscriberMethods); } return subscriberMethods; }}
}

接下来是真正的消息订阅的过程:

//这个函数只能在同步代码块中执行,因为可能有多个函数注册为订阅者
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {//获得订阅函数参数的类型Class<?> eventType = subscriberMethod.eventType;//获取订阅属性CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); //封装订阅者,订阅方法,优先级Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);if (subscriptions == null) {//新建一个subscriptions = new CopyOnWriteArrayList<Subscription>();subscriptionsByEventType.put(eventType, subscriptions);} else {if (subscriptions.contains(newSubscription)) {throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType);}}// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)// subscriberMethod.method.setAccessible(true);int size = subscriptions.size();for (int i = 0; i <= size; i++) {if (i == size || newSubscription.priority > subscriptions.get(i).priority) {subscriptions.add(i, newSubscription);//添加一个订阅者break;}}List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);if (subscribedEvents == null) {subscribedEvents = new ArrayList<Class<?>>();//key=订阅者所属的类,value=订阅函数参数类型名,这里添加是为了到时注销订阅typesBySubscriber.put(subscriber, subscribedEvents);}//添加订阅函数参数属性名subscribedEvents.add(eventType); if (sticky) {//是否是粘性注册if (eventInheritance) {//默认为true// 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>).//如果是postSticky的话,stickyEvents这里会有值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();//这里实际上直接invoke这个stickyEvent方法了checkPostStickyEventToSubscription(newSubscription, stickyEvent);}}} else {Object stickyEvent = stickyEvents.get(eventType);checkPostStickyEventToSubscription(newSubscription, stickyEvent);}}
}

2、Post(发送消息)

接下来看消息发送过程,开始函数是post(),如果是postSticky(),代码如下:

//粘性发送消息,最近的粘性消息会被保存在内存当中,被之后调用,当然注册的时候使用registerSticky(Object)
public void postSticky(Object event) {synchronized (stickyEvents) {stickyEvents.put(event.getClass(), event);}// Should be posted after it is putted, in case the subscriber wants to remove immediatelypost(event);//最后会调用post函数
}

接下来分析Post函数:

public void post(Object event) {//获取post线程状态的初始值(ThreadLocal)PostingThreadState postingState = currentPostingThreadState.get();List<Object> eventQueue = postingState.eventQueue;//post队列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;}}
}

接下来分析postSingleEvent函数:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {//获取消息所属函数名(“start” = String)Class<?> eventClass = event.getClass();boolean subscriptionFound = false;//是否找到订阅者if (eventInheritance) {//默认为true//查找发送消息类型相关的类型,例如public final class String implements Serializable, Comparable<String>//此时List里面有String , Serializable , Comparable , CharSequence , ObjectList<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));}}}
}

接下来分析lookupAllEventTypes()函数:

private List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {synchronized (eventTypesCache) {List<Class<?>> eventTypes = eventTypesCache.get(eventClass);//获取消息类型相关的类型if (eventTypes == null) {eventTypes = new ArrayList<Class<?>>();Class<?> clazz = eventClass;while (clazz != null) {eventTypes.add(clazz);//添加这个class本身addInterfaces(eventTypes, clazz.getInterfaces());//添加这个class完成的interfaceclazz = clazz.getSuperclass();//添加这个class所属的父类}eventTypesCache.put(eventClass, eventTypes);}return eventTypes;}
} 

接下来分析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;
} 

接下来分析postToSubscription()函数:

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {//根据消息订阅者所在的线程调用switch (subscription.subscriberMethod.threadMode) {case PostThread:invokeSubscriber(subscription, event);//默认情况直接调用break;case MainThread:if (isMainThread) {invokeSubscriber(subscription, event);//如果在UI线程就直接调用} else {//不在UI线程,通过handler方式发送消息(在UI线程中定义非ui线程订阅函数)mainThreadPoster.enqueue(subscription, event);}break;case BackgroundThread:if (isMainThread) {// UI线程,在线程池(EventBus类中的Executors.newCachedThreadPool)发送消息(在后台线程中定义ui线程订阅函数)backgroundPoster.enqueue(subscription, event);} else {//在后台线程发送消息invokeSubscriber(subscription, event); }break;case Async:// 在线程池(EventBus类中的Executors.newCachedThreadPool)发送消息asyncPoster.enqueue(subscription, event);break;default:throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);}
} 

3、UnRegister(注销)

注销订阅,主要在函数unregister()中体现:

public synchronized void unregister(Object subscriber) {//获取所有注册函数的参数类型<key=注册所在的类,value=类里面注册函数参数的类型>List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);       if (subscribedTypes != null) {for (Class<?> eventType : subscribedTypes) {unubscribeByEventType(subscriber, eventType);//根据参数类型,逐一注销}typesBySubscriber.remove(subscriber);//移除注册类} else {Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());}
}

接下来分析unubscribeByEventType()函数:

private void unubscribeByEventType(Object subscriber, Class<?> eventType) {//获取封装了订阅函数的容器List<Subscription> subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions != null) {int size = subscriptions.size();for (int i = 0; i < size; i++) {//对于封装的Subscriber和Method等逐一移除Subscription subscription = subscriptions.get(i);if (subscription.subscriber == subscriber) {subscription.active = false;subscriptions.remove(i);i--;size--;}}}
}

这篇关于Android EventBus源码学习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1020205

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

Android平台播放RTSP流的几种方案探究(VLC VS ExoPlayer VS SmartPlayer)

技术背景 好多开发者需要遴选Android平台RTSP直播播放器的时候,不知道如何选的好,本文针对常用的方案,做个大概的说明: 1. 使用VLC for Android VLC Media Player(VLC多媒体播放器),最初命名为VideoLAN客户端,是VideoLAN品牌产品,是VideoLAN计划的多媒体播放器。它支持众多音频与视频解码器及文件格式,并支持DVD影音光盘,VCD影

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

【学习笔记】 陈强-机器学习-Python-Ch15 人工神经网络(1)sklearn

系列文章目录 监督学习:参数方法 【学习笔记】 陈强-机器学习-Python-Ch4 线性回归 【学习笔记】 陈强-机器学习-Python-Ch5 逻辑回归 【课后题练习】 陈强-机器学习-Python-Ch5 逻辑回归(SAheart.csv) 【学习笔记】 陈强-机器学习-Python-Ch6 多项逻辑回归 【学习笔记 及 课后题练习】 陈强-机器学习-Python-Ch7 判别分析 【学