1

I had an eventbus problem and tried a lot of ways.

I use the service to schedule my app, I will post an event to Eventbus in App.Activity every time.

RefreshService.java

Runnable run = new Runnable() {
    @Override
    public void run() {
        if (instanceNetwork.isOnline(RefreshService.this)) {
            Log.d("LOG_SERVICE_POST", "run: ");
            EventBus.getDefault().postSticky(RUNNING);
        }

        mHandler.postDelayed(this::run, timeRefresh);
    }
};


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (timeRefresh == null) {
        timeRefresh = instanceSharedPreferences.getTimeRefresh(Setting.KEY_AUTO_REFRESH, getString(R.string.TIME_REFRESH_DEFAULT));
    }

    mHandler.postDelayed(run, timeRefresh);
    return super.onStartCommand(intent, flags, startId);
}

Activity App

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app);

    Intent intent = new Intent(this, RefreshService.class);
    startService(intent);
}

@Override
protected void onStart() {
    super.onStart();
    if (!EventBus.getDefault().isRegistered(this)) {
        EventBus.getDefault().register(this);
    }
}

@Override
protected void onDestroy() {
    if(EventBus.getDefault().isRegistered(this)){
        EventBus.getDefault().unregister(this);
    }
    AppDatabase.destroyInstance();
    super.onDestroy();
}

@Subscribe(sticky = true, threadMode = ThreadMode.BACKGROUND)
public void onMessageEvent(Boolean isRun) {
    if (isRun == RefreshService.RUNNING) {
        Log.d("LOG_REFRESHED", "onMessageEvent: ");
        runnableRefresh.run();
    }
}

Currently, Service and Eventbus can run normally, but when the app is off, only the Service will run (Subscribe does not receive the event).

What I want is that Subscribe can receive my event even when the app is off.

Zeroes
  • 142
  • 1
  • 10
  • Subscribe is your Activity how can it receive event if its not running ? – ADM Apr 23 '20 at 05:02
  • Try changing `threadMode = ThreadMode.BACKGROUND` to `ThreadMode.MAIN`. – Hussain Apr 23 '20 at 05:04
  • i tried **threadMode = ThreadMode.MAIN** and it's don't working when app off. – Zeroes Apr 23 '20 at 05:10
  • @ADM I see Log in Subscribe and check last update when i open app. – Zeroes Apr 23 '20 at 05:16
  • If your Service is running then you should get the sticky event. If your Application is killed and restart again you will lost the events..[See this](https://stackoverflow.com/questions/30020966/sticky-events-should-remain-after-app-close-greenrobot-eventbus) .. – ADM Apr 23 '20 at 05:22
  • @ADM I can not use sticky, currently I want to know how to run background for eventbus, can you help me do that? – Zeroes Apr 23 '20 at 06:32

0 Answers0