开源框架 —> EventBus 消息总线框架使用
标签(空格分隔): EventBus Android框架
1. 前言
OTA模块用到消息总线框架EventBus,经过对比handler,项目中消息比较多,使用EventBus框架,便于统一管理
EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦
下载EventBus框架类库
源码:https://github.com/greenrobot/EventBus
2. 实战
2.1 基本使用方法
(1) 自定义一个消息类
public class MyEventBus{
public static final int JUMP_TO_NETWORKSETTINGS = 0x01;
public static final int RETURN_TO_SECONDPAGER = 0x02;
private String message;
private int what;
public MessageEvent(String message) {
this.message = message;
}
public MessageEvent(int what) {
this.what = what;
}
public MessageEvent(String message, int what) {
this.message = message;
this.what = what;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getWhat() {
return what;
}
public void setWhat(int what) {
this.what = what;
}
}
(2) 接受消息的界面注册与反注册,以及接收消息后实现
//OnCreate函数中注册EventBus
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册EventBus
EventBus.getDefault().register(this);
}
//OnDestory函数中反注册EventBus
@Override
protected void onDestroy() {
//反注册EventBus
EventBus.getDefault().unregister(this);
super.onDestroy();
}
//接收消息后的实现,4种不同的实现方法,根据项目实际需要选取
public void onEventMainThread(MyEventBus myEventBus) {
String msg = "onEventMainThread收到了消息" + myEvent.getmMsg();
textView.setText(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
4种不同方法实现的区别:
//onEvent:
如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,
onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。
使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
//onEventMainThread:
如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,
onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,
因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
//onEventBackground:
如果使用onEventBackgrond作为订阅函数,
那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,
如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
//onEventAsync:
使用这个函数作为订阅函数,那么无论事件在哪个线程发布,
都会创建新的子线程在执行onEventAsync.
(3) 发送消息
//发送消息界面无需注册于反注册
EventBus.getDefault().post(new MyEvent("EventBus first Msg!!!"));