赞
踩
EventBus不适合向一个不存在于activity栈中的activity发送消息,这样是失败的,
例如:
情况1:一个activity 还没有生成,就post,肯定报这样的错;
情况2:一个activity曾经生成了,但是不在activity栈中了,也是收不到消息的
情况3:生命周期的问题
官方推荐是这样写:
https://github.com/greenrobot/EventBus
@Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); }
而实际上这样不好,不应该在onStop里面就注销了,应该在onDestroy里面注销比较好
@Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); }
原因应该是:EventBus 是为已经存在的activity传递消息,而且订阅者必须要注册且不能被注销了,
如果你在onStop里面注销了,栈中虽然有这个activity,但是EventBus并没有被注册,所以也接收不到消息,
就报:No Subscribers registered 的问题
下面的话来自stackflow,很好:
In general, the EventBus is used to receive updated data for an already active activity or fragment. Think of the EventBus as more of a wrapper around an observer/consumer. For this example it looks like you are using it to pass data to another Activity.
所以有时候最好还是用标准的方法去传递相关的数据,比如bundle,在intent里面带过去
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。