EventBus介绍
eventbus是一款针对Android优化的发布/订阅事件总线,主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息,优点是开销小,代码更优雅,以及将发送者和接收者解耦。
EventBus使用
1.依赖
在build.gradle文件中添加依赖
implementation 'org.greenrobot:eventbus:3.1.1'
添加完依赖后,点击Android Studio提示的进行同步
2.注册
在需要发送消息的Activity中,进行注册
//2.注册EventBus
EventBus.getDefault().register(this);//this当前类
3.发送事件,发送消息
EventBus.getDefault().post(type);//发送的事件类型与接收消息的事件类型一样