Android:用Greenrobot EventBus如何在2个Activity之间进行通信?

ant*_*ony 5 android android-activity greenrobot-eventbus

我想在2活动之间进行沟通.两者都是register()和unregister()方法:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}
Run Code Online (Sandbox Code Playgroud)

单击列表(项目选择)时,将启动ActivityB.ActivityB的目的是更新一些信息,并将这些新信息发送给ActivityA; 所以在ActivityB中我打电话:

EventBus.getDefault().post(new MyNewEvent(bla bla bla));
Run Code Online (Sandbox Code Playgroud)

在我的ActivityA中我有这个方法:

public void onEvent(MyNewEvent event) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个方法onEvent从未被调用过.为什么?因为当ActivityB启动时,调用ActivityA中的方法onStop(),所以完成了对总线的取消注册...

那么如何通过使用EventBus在这两个Activity之间进行通信?

感谢你们!

Doo*_*om5 5

你可以通过使用粘性事件来实现这一点.

http://greenrobot.org/eventbus/documentation/configuration/sticky-events/

基本上,您.postSticky()在活动B上发布一个粘性事件,当活动A再次注册时,它将自动收到该粘性事件.

但正如@ jlhonora的回答所述,startActivityForResult可能更适合您的需求.


jlh*_*ora 3

正如您已经发现的,您将无法使用 EventBus 在两个活动之间进行通信,因为您不能同时注册两个活动。

startActivityForResult 模式更适合您想要实现的目标:http://developer.android.com/reference/android/app/Activity.html#StartingActivities