android EventBus 使用
来源:互联网 发布:提示我windows未能启动 编辑:程序博客网 时间:2024/06/07 13:22
EventBus定义:是一个发布 / 订阅的事件总线。
EventBus解耦性极高,下面是EventBus的一个流程图
下面的代码将举一个例子在项目中也可以运用,一个Activity向另一个Activity传值 因为布局很简单就是一个按钮,所以就只有逻辑代码
首先我们要创建一个消息类,也就是EventBus要传递这个消息类
public class FirstEvent { String msg; public FirstEvent(String msg) { this.msg = msg; } public String getMsg() { return msg; }}
@Override public void onClick(View v) { switch (v.getId()) { case R.id.back: EventBus.getDefault().post(new FirstEvent("第二页给第一页字符串")); finish(); break; } }在要接收值,也就是需要订阅事件的Activity中(第一个Activity)
我们首先初始化EventBus,在onDestroy生命中解除注册
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this); initView(); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); }下面是EventBus的回调接收的方法,也就是说当订阅的EventBus收到post发过来的通知的时候会执行这个方法,要加上注解.
@Subscribe public void onEventMainThread(FirstEvent event) { String msg = "onEventMainThread收到了消息:" + event.getMsg(); tv.setText(msg); }这样第一个Activity就收到了第二个Activity传递过来的消息类
EventBus一共有四种回调接收的方法
1、onEvent
2、onEventMainThread
3、onEventBackgroundThread
4、onEventAsync
这四种订阅函数都是使用onEvent开头的,它们的功能稍有不同,在介绍不同之前先介绍两个概念:
告知观察者事件发生时通过EventBus.post函数实现,这个过程叫做事件的发布,观察者被告知事件发生叫做事件的接收,是通过下面的订阅函数实现的。
onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackground:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.
所以可以根据不同的情景来选择
- Android - EventBus使用 备忘
- android EventBus 使用
- Android EventBus 使用详解
- Android EventBus使用详解
- Android EventBus的使用
- Android使用EventBus
- android EventBus的使用
- Android-eventBus的使用
- Android EventBus的使用
- Android EventBus 基本使用
- Android EventBus的使用
- Android EventBus使用详解
- Android EventBus 3.0使用
- android EventBus的使用
- android EventBus使用 总结
- android-eventbus-使用详解
- Android EventBus使用总结
- Android -- EventBus使用
- linux 怎么样复制文件夹内所有文件到另一个文件夹?
- HDU1548A strange lift(bfs)
- Java三大器(Filter,Listener,Interceptor)
- 鸡兔同笼
- Linux下两个特殊文件/dev/null 和 /dev/zero
- android EventBus 使用
- stm32头文件学习之Core_cm3.c(h)
- jdbc&sqlite
- nginx缩略图image_filter配置整合fastdfs
- 13周
- Java小练习——简单的登录界面
- 趣图:改 Bug
- Leetcode 71. Simplify Path
- 面向对象:在平淡的生活中,活成不平凡的你我,希望你是那个对的他