gpt4 book ai didi

android - 如何在 Intent 服务中接收事件(Greenrobots Event Bus)

转载 作者:搜寻专家 更新时间:2023-11-01 07:55:21 24 4
gpt4 key购买 nike

我正在尝试在 IntentService 中接收粘性事件。我尝试在 onEvent()onEventBackgroundThread() 中捕获事件,但我没有收到事件。我知道如何在无法将事件发送到服务的 Activity 和 fragment 之间发送和接收事件。事件总线是否发布到服务?如果它确实在哪里订阅事件?我尝试在 onHandleIntent(Intent intent) 和服务的构造函数中进行订阅。没有运气。有人可以帮忙吗?

最佳答案

Services 和 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 Event Bus),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28493772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com