EventBus.post() 在服务中,如何从 Thread.BACKGROUND 调用函数

EventBus.post() within Service, how to call function from Thread.BACKGROUND

我正在尝试实现一个功能,该功能将在用户关闭应用程序(滑动关闭)时进行一些清理。

里面Activity.class

  @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void stopSearching(MyService.StopSearching stopSearching)
    {
        Log.d(TAG, "stopSearching: ");

    }

MyService.class

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ClearFromRecentService", "Service Started");
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("ClearFromRecentService", "Service Destroyed");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.e("ClearFromRecentService", "END");
        EventBus.getDefault().post(new StopSearching());
        stopSelf();
    }

    public class StopSearching {
        StopSearching() {
        }
    }
}

但我得到:

EventBus: No subscribers registered for event class com.talkie.ashaneen.firebaseapp.other.MyService$StopSearching

EventBus: No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent

问题是您必须在调用 onStop 函数时取消注册事件总线。当您的应用最小化时,它处于停止阶段,因此您的 Activity 无法接收任何事件。在这种情况下,我认为您不能从后台线程执行任何事件,因为您的 activity 已从内存中删除,它甚至无法从 EventBus 接收任何回调。