我正在尝试在 IntentService
中接收粘性事件。我 try catch onEvent()
和 onEventBackgroundThread()
中的事件,但没有收到事件。我知道如何在 Activity 和 fragment 之间发送和接收事件,但无法将事件发送到服务工作。 eventbus 是否发布到服务?如果有的话在哪里订阅事件?我尝试在 onHandleIntent(Intent Intent) 和服务的构造函数中进行订阅。没有运气。有人可以帮忙吗?
最佳答案
服务和 EventBus 并没有真正混合。 IntentService 旨在在后台线程中执行某些操作 - 即发即忘。服务可以在不同的进程中运行并使用不同的上下文。它们的通信方式非常专有,不太适合 EventBus 等外部框架。
我的建议是重新考虑 IntentService 的需求并考虑使用 http://greenrobot.org/eventbus/documentation/delivery-threads-threadmode/不同的传递方法,因此将事件从 UI 发布到通信层中的管理器,该管理器将在后台线程上接收该事件,处理它,然后发布另一个带有结果的事件,UI 将在主线程上监听该事件.
所以你的经理看起来像这样:
@Subscribe(threadMode = ThreadMode.BackgroundThread)
public void onEvent(AccountsDoGetEvent event){
//do long running task like going to network or database
EventBus.getDefault().post(new AccountsUpdatedEvent);
}
你的 fragment 看起来像这样:
@Subscribe(threadMode = ThreadMode.MainThread)
public void onEvent(AccountsUpdatedEvent event){
//update the UI
}
public void onButtonClicked(){
EventBus.getDefault().post(new AccountsDoGetEvent());
}
关于android - 如何在 Intent 服务中接收事件(Greenrobots 事件总线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28493772/