EventBus 3.0+ 简单集成使用

  1. dependencies 引入
 compile 'de.greenrobot:eventbus:3.0.0-beta1'

2.注册与取消注册

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EventBus.getDefault().register(this);

        }
    }

@Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

3.发起事件

EventBus.getDefault().post(“我是发起的事件”);

注:发起的事件,参数可以自定义 推荐用定义的bean 如

UserBean userInfo = new UserBean();
userInfo.setName("张三");
EventBus.getDefault().post(userInfo);

4.接收事件;

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(KjjBean x){
        Log.e("wh", "sendEventBus处理消息的线程为" + Thread.currentThread().getName());
        Log.e("wh", "sendEventBus EventBus返回值为" + x.getKjj());

    }

说明:3.0及以后的版本加入了 @Subscribe 注解 threadMode指定了要运行的线程,MainTread就是运行在UI线程,也就是主线程。 PostThread是运行在发起事件的线程。也就是说发起事件在哪个线程,接收事件会在同一个线程来接收。BackgroundThread 就是在非UI线程里接收事件。如果是UI线程发来的消息,就会新起线程来接收事件。如果是子线程发来的消息 就在相同的线程里处理接收消息,也就是说这个线程不可以处理UI事件。async 无论事件在哪个线程发布,该事件处理函数都会在新建的子线程中执行,同样,此事件处理函数中禁止进行UI更新操作。

发布了36 篇原创文章 · 获赞 21 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_15110579/article/details/79214052
今日推荐