EventBus
1.简介
在简书看到的一篇文章,修改之后重新上传的.原文链接:https://www.jianshu.com/p/e7d5c7bda783
用于Android的事件发布-订阅总线, 是一个基于 订阅/发布 模式实现的 基于事件的异步分发处理系统。由GreenRobot开发.它简化了应用程序内各个组件之间进行通信的复杂度,尤其是碎片之间进行通信的问题,可以避免由于使用广播通信而带来的诸多不便。
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 特点
- 简化组件之间的通信
分离事件发送者和接收者
在活动、片段和后台线程中表现良好
避免复杂且容易出错的依赖关系和生命周期问题 - 让你的代码更简单
- 很快
- 很小(~60k jar)
- 安装量超过 1,000,000,000 次的应用在实践中得到了证明
- 具有交付线程、订阅者优先级等高级功能。
1.3 四种线程模型
**POSTING:**默认,表示事件处理函数的线程跟发布事件的线程在同一个线程。
**MAIN:**表示事件处理函数的线程在主线程(UI)线程,因此在这里不能进行耗时操作。
**BACKGROUND:**表示事件处理函数的线程在后台线程,因此不能进行UI操作。如果发布事件的线程是主线程(UI线程),那么事件处理函数将会开启一个后台线程,如果果发布事件的线程是在后台线程,那么事件处理函数就使用该线程。
**ASYNC:**表示无论事件发布的线程是哪一个,事件处理函数始终会新建一个子线程运行,同样不能进行UI操作。
2.使用
1.导入依赖
implementation 'org.greenrobot:eventbus:3.1.1'
2 . 注册
EventBus.getDefault().register(MainActivity.this);
3.解注册
@Override
protected void onDestroy(){
super.onDestroy();
//2.解注册
EventBus.getDefault().unregister(MainActivity.this);//反注册EventBus
}
4.构造发送消息类
//.构造发送消息类
public class MessageEvent {
public String message;
public MessageEvent(String message) {
this.message = message;
}
public String getMessage(){
return message;
}
}
5.发送消息
//.发送消息
EventBus.getDefault().post(
new MessageEvent("主线程发送消息"));
6.接收消息
//.接收消息
@Subscribe(threadMode = ThreadMode.MAIN)
public void MessageEventBus(MessageEvent event){
//显示接收的消息
tv_eventbus_result.setText(event.message);
}
3.DEMO
3.1 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<Button
android:layout_margin="25dp"
android:id="@+id/btn_eventbus_send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="跳转到发送页面"
android:background="#FFEB3B"
/>
<Button
android:layout_margin="25dp"
android:id="@+id/btn_eventbus_sticky"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送粘性事件跳转到发送页面"
android:background="#6ABEE4"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height ="wrap_content"
android:text="接收显示的结果"
android:textSize="20sp"
android:layout_margin="5dp"/>
<TextView
android:id="@+id/tv_eventbus_result"
android:text=""
android:textColor="@color/black"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
3.2 activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".SecondActivity"
android:orientation="vertical">
<Button
android:layout_margin="25dp"
android:text="主线程发送数据"
android:id="@+id/btn_eventbus_send_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#6ABEE4"
/>
<Button
android:layout_margin="25dp"
android:text="接收粘性数据"
android:id="@+id/btn_eventbus_send_sticky"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFEB3B"/>
<TextView
android:text="显示结果"
android:textSize="20sp"
android:layout_margin="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_eventbus_send_result"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
3.3MainActivity.java
package com.example.eventbusdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class MainActivity extends AppCompatActivity {
private Button btn_eventbus_send;
private Button btn_eventbus_sticky;
private TextView tv_eventbus_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
initListener();
}
//5.接收消息
@Subscribe(threadMode = ThreadMode.MAIN)
public void MessageEventBus(MessageEvent event){
//显示接收的消息
tv_eventbus_result.setText(event.message);
Log.d("harvic", "onEventMainThread收到了消息:" + event.getMessage());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventBackground(MessageEvent event){
Log.d("harvic", "onEventBackground收到了消息:" + event.getMessage());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventAsync(MessageEvent event){
Log.d("harvic", "onEventAsync收到了消息:" + event.getMessage());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(MessageEvent event) {
Log.d("harvic", "OnEvent收到了消息:" + event.getMessage());
}
private void initListener() {
//主线程发送数据按钮点击事件处理
btn_eventbus_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
//发送粘性事件到发送页面
btn_eventbus_sticky.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EventBus.getDefault().postSticky(
new StickyEvent("我是粘性事件")
);
//跳转到发送数据的页面
Intent intent = new Intent(MainActivity.this,
SecondActivity.class);
startActivity(intent);
}
});
}
private void initView() {
btn_eventbus_send = (Button) findViewById(R.id.btn_eventbus_send);
btn_eventbus_sticky= (Button) findViewById(R.id.btn_eventbus_sticky);
tv_eventbus_result = (TextView) findViewById(R.id.tv_eventbus_result);
}
private void initData() {
//1.注册EventBus
EventBus.getDefault().register(MainActivity.this);
}
@Override
protected void onDestroy(){
super.onDestroy();
//2.解注册
EventBus.getDefault().unregister(MainActivity.this);//反注册EventBus
}
}
3.4MessageEvent.java
package com.example.eventbusdemo;
//3.构造发送消息类
public class MessageEvent {
public String message;
public MessageEvent(String message) {
this.message = message;
}
public String getMessage(){
return message;
}
}
3.5 StickyEvent.java
package com.example.eventbusdemo;
/**
* 创建一个粘性事件类
*/
public class StickyEvent {
public String msg;
public StickyEvent(String msg) {
this.msg = msg;
}
}
3.6 SecondActivity.java
package com.example.eventbusdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class SecondActivity extends AppCompatActivity {
private Button btn_eventbus_send_main;
private Button btn_eventbus_send_sticky;
private TextView tv_eventbus_send_result;
private boolean isFirstFlag = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
initView();
initListener();
}
private void initListener() {
//主线程发送数据按钮点击事件处理
btn_eventbus_send_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//4.发送消息
EventBus.getDefault().post(
new MessageEvent("主线程发送消息"));
Intent intent = new Intent(SecondActivity.this,MainActivity.class);
startActivity(intent);
}
});
//接收粘性事件数据啊牛的点击事件处理
btn_eventbus_send_sticky.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isFirstFlag){
isFirstFlag = false;
//注册
EventBus.getDefault().register(SecondActivity.this);
}
}
});
}
//接收粘性事件
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void StickyEventBus(StickyEvent event){
//显示接收的数据
tv_eventbus_send_result.setText(event.msg);
}
private void initView() {
btn_eventbus_send_main = (Button) findViewById(R.id.btn_eventbus_send_main);
btn_eventbus_send_sticky = (Button) findViewById(R.id.btn_eventbus_send_sticky);
tv_eventbus_send_result = (TextView) findViewById(R.id.tv_eventbus_send_result);
}
@Override
protected void onDestroy() {
super.onDestroy();
//解注册
EventBus.getDefault().removeAllStickyEvents();
EventBus.getDefault().unregister(SecondActivity.this);
}
}
参考文章:
EventBus使用详解(二)——EventBus使用进阶:https://blog.youkuaiyun.com/wuqingyidongren/article/details/50904605
EventBus官方文档:https://github.com/greenrobot/EventBus