Android EventBus使用(不含源码解析)
官方文档:https://github.com/greenrobot/EventBus
simplifies the communication between components
decouples event senders and receivers
performs well with Activities, Fragments, and background threads
avoids complex and error-prone dependencies and life cycle issues
makes your code simpler
is fast
is tiny (~50k jar)
is proven in practice by apps with 100,000,000+ installs
has advanced features like delivery threads, subscriber priorities, etc.
这句话大概是说:
简化组件之间的通信
解耦事件发送者和接收者
对活动、片段和后台线程进行良好的操作
而且非常快
jar包小至50k
已经有超过了一亿用户安装
而且还可以定义优先级
不看了,反正对于开发者来说就一句话:好用!
不废话了,下面开始说使用教程:
1、加入EventBus3.0依赖
implementation 'org.greenrobot:eventbus:3.0.0'
2、既然说了EventBus是用来传值用的,那么先定义这个值吧。
创建一个实体类,MyStudent
public class MyStudent extends Observable {private String name;private int sex;private int old;public String getName() {return name == null ? "" : name;}public void setName(String name) {this.name = name;}public int getSex() {return sex;}public void setSex(int sex) {this.sex = sex;}public int getOld() {return old;}public void setOld(int old) {this.old = old;}@Overridepublic String toString() {return "MyStudent{" +"name='" + name + '\'' +", sex=" + sex +", old=" + old +'}';}
3、值有了,那么这个值有入口和出口的吧
建立两个Activity,我这里就建两个,一个MainActivity,一个Main2Activity,(这里创建流程就不写了,只写Activity中的核心代码)
public class MainActivity extends AppCompatActivity {private Button button;private MyStudent myStudent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);EventBus.getDefault().register(this);//注册eventbusbutton = findViewById(R.id.main_btn);button .setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {startActivity(new Intent(MainActivity.this, Main2Activity.class));}});}@Overrideprotected void onDestroy() {super.onDestroy();EventBus.getDefault().unregister(MainActivity.this);}
//接收事件,EventBus3.0之后采用注解的方式@Subscribe(threadMode = ThreadMode.MAIN)public void Event(MyStudent myStudent) {Log.e("MainActivity", myStudent.toString());}
}
下面看看Main2
public class Main2Activity extends AppCompatActivity {Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);button = findViewById(R.id.main2_btn);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {MyStudent myStudent = new MyStudent();myStudent.setName("eventbus");myStudent.setOld(2);myStudent.setSex(2);EventBus.getDefault().post(myStudent);finish();}});}
这里Log的打印结果是:(我不说,打印结果希望看博客的同学可以自己动手操作一波,这样你的记忆力才深刻。)
4、其实最基本的使用到这里就完了,有一些需要注意的地方在这里说一下:
我们可以看到,在接收参数的方法上面会有一个注解:
@Subscribe(threadMode = ThreadMode.MAIN)
在接收参数的方法上一定要带这个注解,不然参数会接收不到。
注解中的:
threadMode = ThreadMode.MAIN,指的是在什么线程下操作。我们点进去源码看看
public enum ThreadMode {/*** Subscriber will be called in the same thread, which is posting the event. This is the default. Event delivery* implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for* simple tasks that are known to complete is a very short time without requiring the main thread. Event handlers* using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.*/POSTING,/*** Subscriber will be called in Android's main thread (sometimes referred to as UI thread). If the posting thread is* the main thread, event handler methods will be called directly. Event handlers using this mode must return* quickly to avoid blocking the main thread.*/MAIN,/*** Subscriber will be called in a background thread. If posting thread is not the main thread, event handler methods* will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single* background thread, that will deliver all its events sequentially. Event handlers using this mode should try to* return quickly to avoid blocking the background thread.*/BACKGROUND,/*** Event handler methods are called in a separate thread. This is always independent from the posting thread and the* main thread. Posting events never wait for event handler methods using this mode. Event handler methods should* use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number* of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus* uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.*/ASYNC
}
哦,是个枚举类型。
POSTING:意思大概是,为了避免线程切换,在什么线程发的你接受默认就是什么线程
MAIN:主线程,也就是ui线程,不要做耗时操作哟
BACKGROUND:顾名思义,就是子线程啦。
ASYNC:异步,我感觉EventBus很贴心,异步都提供了。
5、EventBus还有一种使用,那就是EventBus的粘性事件(这里仅仅简单举个例子,我目前并没有在实际场景中用到)
依旧是这两个Activity
public class MainActivity extends AppCompatActivity {private Button button;private MyStudent myStudent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);EventBus.getDefault().register(this);//注册eventbusbutton = findViewById(R.id.main_btn);button .setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {startActivity(new Intent(MainActivity.this, Main2Activity.class));}});}@Overrideprotected void onDestroy() {super.onDestroy();EventBus.getDefault().unregister(MainActivity.this);}
//接收事件,EventBus3.0之后采用注解的方式@Subscribe(threadMode = ThreadMode.MAIN , sticky = true)//sticky是为了声明是粘性事件public void Event(MyStudent myStudent) {Log.e("MainActivity", myStudent.toString());}
}
看看Main2
public class Main2Activity extends AppCompatActivity {Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);button = findViewById(R.id.main2_btn);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {MyStudent myStudent = new MyStudent();myStudent.setName("eventbus");myStudent.setOld(2);myStudent.setSex(2);EventBus.getDefault().postSticky(myStudent);finish();}});}
为什么叫粘性事件呢?
先举个小例子,比如说:你定报纸,本来按理说你必须提前订阅了,在发报纸的时候才能收到。 而粘性事件是: 你别管他什么时候发的,就算他先发了报纸,那么你订阅的时候你也能收到这个报纸。(我觉得这个例子已经很形象了)
那么EventBus的粘性事件也是这样,如果他先发消息,发的时候你还没注册,不要紧,你什么时候注册什么时候接收,处理下面的事情。
学习的同学可以多打印log看看。多看多试。
这节课就到这里,下节课再见。
Android EventBus使用(不含源码解析)相关推荐
- Android多线程之ArrayBlockingQueue源码解析
阻塞队列系列 Android多线程之LinkedBlockingQueue源码解析 Android多线程之SynchronousQueue源码解析 Andorid多线程之DelayQueue源码分析 ...
- Android多线程之IntentService源码解析
想要了解 IntentService 的工作原理需要先对 Android 系统中以 Handler.Looper.MessageQueue 组成的异步消息处理机制以及 HandlerThread 有所 ...
- 面部表情识别3:Android实现表情识别(含源码,可实时检测)
面部表情识别3:Android实现表情识别(含源码,可实时检测) 目录 面部表情识别3:Android实现表情识别(含源码,可实时检测) 1.面部表情识别方法 2.人脸检测方法 3.面部表情识别模型训 ...
- Android Glide 3.7.0 源码解析(八) , RecyclableBufferedInputStream 的 mark/reset 实现
个人博客传送门 一.mark / reset 的作用 Android Glide 3.7.0 源码解析(七) , 细说图形变换和解码有提到过RecyclableBufferedInputStream ...
- 行人检测(人体检测)3:Android实现人体检测(含源码,可实时人体检测)
行人检测(人体检测)3:Android实现人体检测(含源码,可实时人体检测) 目录 行人检测(人体检测)3:Android实现人体检测(含源码,可实时人体检测) 1. 前言 2. 人体检测数据集说明 ...
- 跌倒检测和识别3:Android实现跌倒检测(含源码,可实时跌倒检测)
跌倒检测和识别3:Android实现跌倒检测(含源码,可实时跌倒检测) 目录 跌倒检测和识别3:Android实现跌倒检测(含源码,可实时跌倒检测) 1. 前言 2. 跌倒检测数据集说明 3. 基于Y ...
- 【Android应用开发】EasyDialog 源码解析
示例源码下载 : http://download.csdn.net/detail/han1202012/9115227 EasyDialog 简介 : -- 作用 : 用于在界面进行一些介绍, 说明; ...
- 体验Android:个人所得税计算器 含源码
体验Android 个人所得税计算器 含源码 http://files.cnblogs.com/mobile/ptc.rar 转载于:https://www.cnblogs.com/mobile/ar ...
- 【Android 控件使用及源码解析】 GridView规则显示图片仿微信朋友圈发图片
今天闲下来想用心写一点东西,发现没什么可写的,就写一下最近项目上用到的一些东西吧.最近项目要求上传多图并且多图显示,而且要规则的显示,就像微信朋友圈的图片显示一样. 想了一下用GridView再适合不 ...
最新文章
- photoshop CS不能打字,出现死机等现象的解决办法!!
- 【NLP】 聊聊NLP中的attention机制
- 诸神战纪2java_诸神战纪2死神归来
- JavaScript实现longestCommonSubsequence最长公共子序列算法(附完整源码)
- grep -e命令详解_grep中的正则表达式
- css如何让不确定宽度的div水平居中
- 国家图书馆关于php的书,国家图书馆啊,能借的书太少
- windows进程中的内存结构(转)
- ACM ICPC 2011-2012 Northeastern European Regional Contest(NEERC)B Binary Encoding
- storm1.x介绍
- 仿射解密c语言程序实验报告,仿射加密解密 - 依姆哣特的个人空间 - OSCHINA - 中文开源技术交流社区...
- Backbone的RESTFUL API 解释
- Transformer为啥在NER上表现不好
- fatal error: krb5.h: 没有那个文件或目录
- 杨志便嗔道 瑞星杀毒软件序列号
- 基于STM32和ESP8266的WIFI信号检测仪
- 一种自动化生产测试流水线
- 7-3 求100以内的素数
- asp.net gridview ItemTemplate 获得 一行 数据
- 面向对象——类和对象