其他分享
首页 > 其他分享> > android – 只要视图没有启动就使用总线?

android – 只要视图没有启动就使用总线?

作者:互联网

我有这个问题,因为我切换到EventBus(任何总线库都会发生),每当我想在视图没有准备好时执行动作,那么我将得到总线未注册的错误;

E/EventBus: Could not dispatch event: class com.android.greenfield.Action to subscribing class class com.android.greenfield.GreenStore

当我想在生命周期的那些部分中触发Action时会发生这种情况:

当我拍摄照片/视频时:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {   
   actionsCreator.uploadFile(filepath, "image/jpg");
   // ... (Error here because the bus isn't yet registered)
}

或者在我收到NFC标签时:

@Override
public void onNewIntent(Intent intent) {
   actionsCreator.uploadNfcTag(intent);
   // ... (Error here because the bus isn't yet registered)
}

如果我按照他们在文档中说的那样遵循正常方式或EventBus,我应该注册并取消注册:

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

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

到目前为止,我发现的唯一解决方法是在我想执行onStart()和onStop()生命周期之间的操作时注册和取消注册…但它很脏而且我感觉很糟糕

@Override
public void onNewIntent(Intent intent) {
   dispatcher.register(GreenStore);
   actionsCreator.uplaodNfcTag(intent);
   dispatcher.register(GreenStore);
}

解决方法:

如果您尝试在onActivityResult中显示对话框片段,则会出现与获取IllegalStateException的原因相同的问题.简单地说,它在用户界面恢复生机之前运行.

简单解决方案

1.)

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
    @Override
    public void run() {
         actionsCreator.uploadFile(filepath, "image/jpg");
    }
});

2.)while the bus is paused (this is something you’d handle manually), you should queue up the events, and then when it’s unpaused, execute them.

标签:android,event-bus,greenrobot-eventbus
来源: https://codeday.me/bug/20190706/1393957.html