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;
}
@Override
public 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);//注册eventbus
button = findViewById(R.id.main_btn);
button .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
@Override
protected 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button = findViewById(R.id.main2_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);//注册eventbus
button = findViewById(R.id.main_btn);
button .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
@Override
protected 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button = findViewById(R.id.main2_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyStudent myStudent = new MyStudent();
myStudent.setName("eventbus");
myStudent.setOld(2);
myStudent.setSex(2);
EventBus.getDefault().postSticky(myStudent);
finish();
}
});
}
为什么叫粘性事件呢?
先举个小例子,比如说:你定报纸,本来按理说你必须提前订阅了,在发报纸的时候才能收到。 而粘性事件是: 你别管他什么时候发的,就算他先发了报纸,那么你订阅的时候你也能收到这个报纸。(我觉得这个例子已经很形象了)
那么EventBus的粘性事件也是这样,如果他先发消息,发的时候你还没注册,不要紧,你什么时候注册什么时候接收,处理下面的事情。
学习的同学可以多打印log看看。多看多试。
这节课就到这里,下节课再见。

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
史上最全WebView使用,附送Html5Activity一份
WebView在现在的项目中使用的频率应该还是非常高的。我个人总觉得HTML5是一种趋势。找了一些东西,在此总结。本篇最后有一个非常不错 的 Html5Activity 加载类,不想看的可以直接跳下载。 WebSettings WebSettings webSettings = mWebView .getSettings(); //支持获取手势焦点,输入用户名、密码或其他 webview.requestFocusFromTouch(); setJavaScriptEnabled(true); //支持js setPluginsEnabled(true); //支持插件 webSettings.setRenderPriority(RenderPriority.HIGH); //提高渲染的优先级 设置自适应屏幕,两者合用 setUseWideViewPort(true); //将图片调整到适合webview的大小 setLoadWithOverviewMode(true); // 缩放至屏幕的大小 setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。...
-
下一篇
Architecture -- Lifecycle
1). 简介 生命周期感知组件执行操作以响应另一个组件(例如活动和片段)的生命周期状态的更改。 这些组件可帮助您生成更易于组织且通常更轻量级的代码,这些代码更易于维护。 一种常见的模式是在活动和片段的生命周期方法中实现依赖组件的操作。 但是,这种模式导致代码组织不良以及错误的增加。 通过使用生命周期感知组件,您可以将依赖组件的代码移出生命周期方法并移入组件本身。 2). 依赖 // ViewModel and LiveData implementation "android.arch.lifecycle:extensions:$lifecycle_version" // alternatively - just ViewModel implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // use -ktx for Kotlin // alternatively - just LiveData implementation "android.arch.lifecycle:livedata:$lifecy...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- SpringBoot2全家桶,快速入门学习开发网站教程
- MySQL8.0.19开启GTID主从同步CentOS8
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- CentOS7,8上快速安装Gitea,搭建Git服务器
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程