官方文档: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看看。多看多试。
这节课就到这里,下节课再见。
网友评论