EventBus使用与分析
写在前面
哪里可以获得
怎么使用
使用方式
快速上手
注册方法:
反注册方法:
接收回调:
发送事件:
使用过程
package com.lzy.evbusdemo;public class MyEvent {private String msg;public MyEvent(String msg) {this.msg = msg;}public String getMsg() {return msg;}
}
其他两个主文件
package com.lzy.evbusdemo;import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.TextView;public class MainActivity extends Activity {private TextView tvShowTextView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tvShowTextView = (TextView) findViewById(R.id.tvShow);EventBus.getDefault().register(this);// 订阅}public void jumpTo(View view) {startActivity(new Intent(this, OtherActivity.class));}@Overrideprotected void onDestroy() {super.onDestroy();EventBus.getDefault().unregister(this);}/*** 接收* */@Subscribepublic void onEvent(MyEvent event) {Log.i("Main", "Main - onEvent: " + event.getMsg());}@Subscribepublic void onEventAsync(MyEvent event) {Log.i("Main", "Main - onEventAsync: " + event.getMsg());}@Subscribepublic void onEventBackgroundThread(MyEvent event) {Log.i("Main", "Main - onEventBackgroundThread: " + event.getMsg());}@Subscribepublic void onEventMainThread(MyEvent event) {Log.i("Main", "Main - onEventMainThread: " + event.getMsg());tvShowTextView.setText(event.getMsg());}
}
package com.lzy.evbusdemo;import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;public class OtherActivity extends Activity {private TextView textView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_other);EventBus.getDefault().register(this);textView = new TextView(this);textView.setText(getResources().getString(R.string.Text_Other_Activity));addContentView(textView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));textView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {EventBus.getDefault().post(new MyEvent("LD"));// 发布}});}@Overrideprotected void onDestroy() {super.onDestroy();EventBus.getDefault().unregister(this);}/*** 接收* */@Subscribepublic void onEvent(MyEvent event) {Log.i("Other", "Other - onEvent: " + event.getMsg());}@Subscribepublic void onEventAsync(MyEvent event) {Log.i("Other", "Other - onEventAsync: " + event.getMsg());}@Subscribepublic void onEventBackgroundThread(MyEvent event) {Log.i("Other", "Other - onEventBackgroundThread: " + event.getMsg());}@Subscribepublic void onEventMainThread(MyEvent event) {Log.i("Other", "Other - onEventMainThread: " + event.getMsg());textView.setText(event.getMsg());}
}
通过以上我们就实现了订阅与分发,只要是订阅者,在发送的时候就都能收到了。不过这几个方法我们应该使用哪个呢,还有他们是怎么调用的呢?上述代码调试信息如下
04-08 06:18:47.657: I/Main(1570): Main - onEventAsync
04-08 06:18:47.661: I/Main(1570): Main - onEventBackgroundThread
04-08 06:18:47.661: I/Main(1570): Main - onEventMainThread
04-08 06:18:47.661: I/Other(1570): Other - onEvent
04-08 06:18:47.661: I/Other(1570): Other - onEventAsync
04-08 06:18:47.661: I/Other(1570): Other - onEventBackgroundThread
04-08 06:18:47.661: I/Other(1570): Other - onEventMainThread
package com.lzy.evbusdemo;import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.TextView;public class MainActivity extends Activity {private TextView tvShowTextView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tvShowTextView = (TextView) findViewById(R.id.tvShow);EventBus.getDefault().register(this);// 订阅}public void jumpTo(View view) {startActivity(new Intent(this, OtherActivity.class));}@Overrideprotected void onDestroy() {super.onDestroy();EventBus.getDefault().unregister(this);}/*** 接收* */@Subscribepublic void onEvent(MyEvent event) {Log.i("Main", "Main - onEvent: " + event.getMsg());}@Subscribepublic void onEventAsync(MyEvent1 event) {Log.i("Main", "Main - onEventAsync: " + event.getMsg());}@Subscribepublic void onEventBackgroundThread(MyEvent2 event) {Log.i("Main", "Main - onEventBackgroundThread: " + event.getMsg());}@Subscribepublic void onEventMainThread(MyEvent3 event) {Log.i("Main", "Main - onEventMainThread: " + event.getMsg());tvShowTextView.setText(event.getMsg());}
}
package com.lzy.evbusdemo;import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;public class OtherActivity extends Activity {private TextView textView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_other);EventBus.getDefault().register(this);textView = new TextView(this);textView.setText(getResources().getString(R.string.Text_Other_Activity));addContentView(textView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));textView.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {EventBus.getDefault().post(new MyEvent("LD"));// 发布EventBus.getDefault().post(new MyEvent1("DCM"));EventBus.getDefault().post(new MyEvent2("HY"));EventBus.getDefault().post(new MyEvent3("JSM"));}});}@Overrideprotected void onDestroy() {super.onDestroy();EventBus.getDefault().unregister(this);}/*** 接收* */@Subscribepublic void onEvent(MyEvent event) {Log.i("Other", "Other - onEvent: " + event.getMsg());}@Subscribepublic void onEventAsync(MyEvent3 event) {Log.i("Other", "Other - onEventAsync: " + event.getMsg());}@Subscribepublic void onEventBackgroundThread(MyEvent1 event) {Log.i("Other", "Other - onEventBackgroundThread: " + event.getMsg());}@Subscribepublic void onEventMainThread(MyEvent2 event) {Log.i("Other", "Other - onEventMainThread: " + event.getMsg());textView.setText(event.getMsg());}
}
运行一下:
04-08 07:18:58.717: I/Other(2008): Other - onEvent: LD ----------------------------------------- MyEvent
04-08 07:18:58.717: I/Main(2008): Main - onEventAsync: DCM ----------------------------------------- MyEvent1
04-08 07:18:58.717: I/Other(2008): Other - onEventBackgroundThread: DCM ----------------------------------------- MyEvent1
04-08 07:18:58.717: I/Main(2008): Main - onEventBackgroundThread: HY ----------------------------------------- MyEvent2
04-08 07:18:58.717: I/Other(2008): Other - onEventMainThread: HY ----------------------------------------- MyEvent2
04-08 07:18:58.717: I/Main(2008): Main - onEventMainThread: JSM ----------------------------------------- MyEvent3
04-08 07:18:58.717: I/Other(2008): Other - onEventAsync: JSM ----------------------------------------- MyEvent3
源码分析
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) {// 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);}}
订阅者方法实体是SubscriberMethod,定义了一系列属性
private void findUsingReflectionInSingleClass(FindState findState) {Method[] methods;try {// This is faster than getMethods, especially when subscribers are fat classes like Activitiesmethods = findState.clazz.getDeclaredMethods();} catch (Throwable th) {// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149methods = 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");}}}
筛选:
private SubscriberInfo getSubscriberInfo(FindState findState) {if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {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;}
返回符合的:
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(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;}
将对应事件所有的找到后
栗子下载
下载
【欢迎上码】
【微信公众号搜索 h2o2s2】
EventBus使用与分析相关推荐
- EventBus源码分析
简介 前面我学习了如何使用EventBus,还有了解了EventBus的特性,那么接下来我们一起来学习EventBus的源码,查看EventBus的源码,看看EventBus给我们带来什么惊喜以及编程 ...
- EventBus源码分析 1
本篇文章将从EventBus的常用使用步骤去逐步分析它的源码和内部实现,其中会额外提到粘性事件.观察者模式和接口回调的区别以及EventBus线程调度相关知识. 下面就从以下的使用流程去逐步分析Eve ...
- android eventbus 使用,Android之EventBus使用与分析
EventBus定义 EventBus 是Greenrobot开源的一款轻量级的发布/订阅事件总线. EventBus-Publish-Subscribe.png Publisher方发布Event事 ...
- Android主流三方库源码分析(九、深入理解EventBus源码)
一.EventBus使用流程概念 1.Android事件发布/订阅框架 2.事件传递既可用于Android四大组件间通信 3.EventBus的优点是代码简洁,使用简单,事件发布.订阅充分解耦 4.首 ...
- 【EventBus】EventBus 源码解析 ( 事件发送 | 线程池中执行订阅方法 )
文章目录 一.EventBus 中主线程支持类 二.EventBus 中 AsyncPoster 分析 三.AsyncPoster 线程池 Runnable 任务类 一.EventBus 中主线程支持 ...
- Android EventBus 3.0.0 使用总结
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/53065112 本文出自[赵彦军的博客] 前言 EventBus框架 EventBu ...
- 浅谈EventBus的使用原理
EventBus这是一个目前被广泛使用的,用于在不同的界面(Activity/Fragment)之间传递数据的三方库,其简单的使用深受广大开发者喜欢. 相比起Bundle或者接口回调,EventBus ...
- EventBus使用详解(二)——EventBus使用进阶
前言:这段时间感觉自己也有点懒了,真是内心有点自责呢,除了工作,也没做点什么,EventBus也是一周前总结出来的,只能以写博客为名来弥补内心的罪恶感了,集合同事们做的项目,虽然上周开动了,但总感觉大 ...
- Android中的单例模式(java单例模式详解,Glide,EventBus,LayoutInfalter的源码单例模式详解)
一.单例模式 (1)单例模式介绍和定义 大概意思是保证一个类在任何时候都只有一个实例在内存里,以static形式提供整个项目的访问.在Android系统中常用的地方有:创建一个SQLiteOpen ...
最新文章
- BAT看上了产业互联网
- python PyQt5如何绘制矩形框?(画框/绘框)
- gin ajax 获取请求参数,go的gin框架从请求中获取参数的方法
- 004-JQuery属性
- firefox应用自动全屏显示_【b】—自动化测试:基础selenium—API
- 软件工程复习提纲——第三章
- Python中写一个乒乓球类的游戏
- 计算机二级基础知识微盘,计算机二级C++基础知识(整理版).pdf
- 使用 Unity* 进行并行处理的一种方法
- 【火炉炼AI】机器学习040-NLP性别判断分类器
- Python 获得汉字笔画
- mfc动态改变clip风格_游戏背景音乐的种类—动态音效
- 微信小程序跳一跳的游戏辅助实现
- 做到这几点在家也能拍出好看的证件照
- 2019天梯赛+第一次面试总结
- 阿里云403(Forbidden)Access to XMLHttpRequest at ‘‘ fromorigin ‘‘ has been blocked by CORS policy:Respon
- 使用sessionStorage实现页面间传值与传对象
- Python 生成excel表格
- 使用win10自带功能,横屏、竖屏显示器分别设置壁纸
- 用php开发扑克小游戏网页版,开发日记:KBEngine+Unity+php做个扑克小游戏(一)