EventBus 入门使用
一、EventBus 简介
EventBus是一种用于Android的事件发布-订阅总线,由GreenRobot开发,Gihub地址是:EventBus。它简化了应用程序内各个组件之间进行通信的复杂度,尤其是碎片之间进行通信的问题,可以避免由于使用广播通信而带来的诸多不便。
1.1 三个重要角色
- Event:事件,它可以是任意类型,EventBus会根据事件类型进行全局的通知。
- Subscriber:事件订阅者,在EventBus 3.0之前我们必须定义以onEvent开头的那几个方法,分别是onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,而在3.0之后事件处理的方法名可以随意取,不过需要加上注解@subscribe,并且指定线程模型,默认是POSTING。
- Publisher:事件的发布者,可以在任意线程里发布事件。一般情况下,使用EventBus.getDefault()就可以得到一个EventBus对象,然后再调用post(Object)方法即可。
1.2 四种线程模型
EventBus3.0有四种线程模型,分别是:
- POSTING:默认,表示事件处理函数的线程跟发布事件的线程在同一个线程。
- MAIN:表示事件处理函数的线程在主线程(UI)线程,因此在这里不能进行耗时操作。
- BACKGROUND:表示事件处理函数的线程在后台线程,因此不能进行UI操作。如果发布事件的线程是主线程(UI线程),那么事件处理函数将会开启一个后台线程,如果果发布事件的线程是在后台线程,那么事件处理函数就使用该线程。
- ASYNC:表示无论事件发布的线程是哪一个,事件处理函数始终会新建一个子线程运行,同样不能进行UI操作。
二、EventBus 使用示例
2.1 引入依赖
implementation 'org.greenrobot:eventbus:3.1.1'
2.2 新建一个实体类,作为传递的对象
public class MessageInfo {
private String message;
public MessageInfo(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2.3 定义接收事件
Activity:
public class MainActivity extends AppCompatActivity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
EventBus.getDefault().register(this); //初始化EventBus
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this); //释放
}
// 定义接收的事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void getMessage(MessageInfo messageInfo) {
tv.setText(messageInfo.getMessage());
Toast.makeText(this, "接收到的消息为:" + messageInfo.getMessage(), Toast.LENGTH_SHORT).show();
}
public void GoMain2Activity(View view) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="GoMain2Activity"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</android.support.constraint.ConstraintLayout>
2.3 定义发送事件
Activity:
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
/**
* 发送消息
*
* @param view
*/
public void publishMessage(View view) {
EventBus.getDefault().post(new MessageInfo("小李子"));
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="publishMessage"/>
</android.support.constraint.ConstraintLayout>
2.4 粘性事件
所谓的黏性事件,就是指发送了该事件之后再订阅者依然能够接收到的事件。使用黏性事件的时候有两个地方需要做些修改。一个是订阅事件的地方,这里我们在先打开的Activity中注册监听黏性事件:
添加 sticky = true
属性
// 定义接收的事件
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void getMessage(MessageInfo messageInfo) {
tv.setText(messageInfo.getMessage());
Toast.makeText(this, "接收到的消息为:" + messageInfo.getMessage(), Toast.LENGTH_SHORT).show();
}
在发送事件时使用postSticky
来发送:
/**
* 发送消息
*
* @param view
*/
public void publishMessage(View view) {
EventBus.getDefault().postSticky(new MessageInfo("小李子"));
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
2.5 优先级
在Subscribe注解中总共有3个参数,上面我们用到了其中的两个,这里我们使用以下第三个参数,即priority。它用来指定订阅方法的优先级,是一个整数类型的值,默认是0,值越大表示优先级越大。在某个事件被发布出来的时候,优先级较高的订阅方法会首先接受到事件。
这里有几个地方需要注意:
- 只有当两个订阅方法使用相同的ThreadMode参数的时候,它们的优先级才会与priority指定的值一致;
- 只有当某个订阅方法的ThreadMode参数为POSTING的时候,它才能停止该事件的继续分发。
联系
遇到问题或想持续学习,请关注公众号“Android唐浮”