我正在使用Otto事件总线订阅ListFragment中的某些事件。 总线实例在应用程序的子类中存储和创建,换句话说,它应该作为一个单独的实例运行。 看来这不是一个案例。
fragment 正在注册到 onActivityCreated(Bundle) 中的总线并在 onDestroy() 中注销。 这里操作不能正常工作。 在调用 unregister() ( java 。lang 。illegalargumentexception ) 时,我从设备崩溃了几个崩溃报告: 缺少带注释的方法的事件处理程序。) 。 只有在调用 unregister() 调用 register ( ) 或者调用 unregister() 时,才会引发这里异常。 这可能只发生在。在 onDestroy() 之前不调用 onActivityCreated(Bundle) 。
onDestroy() 被调用两次。
在调用 onActivityCreated(Bundle) 和 onDestroy() 之间重新创建了 Application 实例。
我的应用程序类:public class App extends Application {
private static App sInstance;
private Bus bus;
public static App getInstance() {
return sInstance;
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
bus = new Bus(ThreadEnforcer.ANY);
}
public Bus getEventBus() {
return bus;
}
}
fragment 类:public class MyFragment extends ListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
App.getInstance().getEventBus().register(this);
}
@Subscribe
public void onEvent(MyEvent event) {
. . ..
}
@Override
public void onDestroy() {
App.getInstance().getEventBus().unregister(this);
super.onDestroy();
}
}
更新:
我遗漏了一个重要细节:Fragments 在 ViewPager 中使用。 当用户在 ViewPager 中的页面之间滑动时,它们按需实例化。 这个小细节似乎改变了一些设备上的Fragments 生命周期: 创建 ViewPager 后,onActivityCreated() 永远不会调用 Fragments 。