您的位置:首页 > 其它

使用EventBus代替startActivityForResult向上传递数据

2016-05-05 16:44 525 查看
这几天接触了下EventBus,EventBus是一款针对Android优化的发布/订阅事件总线。对于Fragment和Fragment通信,Service和Fragment通信,EventBus是一个不错的选择。

以前我们如果想要在Activity之间向上传递数据,都会采用startActivityForResult()方法来实现。其实用EventBus也能实现这个功能。

首先新建一个事件类ForTopEvent:

public class ForTopEvent{
private String data;
public ForTopEvent(String data){
this.data= data;
}

public String getData(){
return data;
}
}


比如要从SecondActivity往FristActivity传递数据,那么SecondActivity是发送数据的页面,FristActivity就是接受数据的一方。

在SecondActivity中发送数据,可以写在onClick()事件中:

EventBus.getDefault().post(
new ForTopEvent("这是MainActivity传过来的信息"));


在FristActivity中注册EventBus:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frist);
EventBus.getDefault().register(this);
}


也要在FristActivity的onDestroy()中解除EventBus注册:

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


在FristActivity中接收数据,这里使用的是onEventMainThread(),使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行。:

public void onEventMainThread(ForTopEvent event){
textView.setText(event.getData());
}


EventBus还有另外3个接收消息的函数:

1.onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。

2.onEventBackgroundThread:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。

3.onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.

至此我们已经在FristActivity中接收了来自SecondActivity的消息。但是使用EventBus没有办法实现从FristActivity传递数据给SecondActivity,因为当FristActivity发出数据的时候,SecondActivity还没有被创建,所以没有办法接收来自FristActivity的数据,同样的如果在开启SecondActivity的时候把FristActivity
finish了,那么FristActivity也同样无法接收到消息(其实是废话)。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: