I have this piece of code on MainActivity that starts a foreground service when the app is resumed.
private final Handler handler = new Handler();
private final Runnable runnable = () -> {
Intent intent = new Intent(this, MyService.class);
ContextCompat.startForegroundService(this, intent);
bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);
};
private class AppLifecycleListener implements DefaultLifecycleObserver {
@Override
public void onResume(LifecycleOwner owner) { // app moved to foreground
handler.postDelayed(runnable, 1000);
}
}
I have tried to solve this error without the handler.postDelayed and runnable in onResume, just by running the code inside Runnable inside onResume, but I've got even more ForegroundServiceStartNotAllowedException crashes.
If we cannot start foreground services on background anymore (since Android API 32), what is the problem with my approach ? In other words, how to avoid this exception when it is needed to start a foreground service right after user opens the app ? (and if it's possible without WorkManager)
Dependency used:
implementation 'androidx.lifecycle:lifecycle-process:2.4.1'