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.