I can't seem to make crash-free implementation of starting background service from foreground app. When my app starts I start background service with SignalR implementation for some websocket magic. I am aware of Android O limitations, but I always start it with the app going to foreground. Here is my clean solution:
class ActivityDelegate(private val activity: FragmentActivity) : LifecycleObserver {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activity.lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun startSignalR() {
activity.startService(Intent(context, CoreSignalRService::class.java))
}
}
Now there are few more adjustments, equally not working:
lifecycle.currentState
will not helpNevertheless, every time I publish the app, I get now and then error of
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=tld.example.something.CoreSignalRService }: app is in background uid UidRecord{98536ea}
What am I doing wrong? How better to get app's status then this lifecycle way?
P.S.: No, I don't want foreground service. I am nut supposed to even need it as I need my service only when app is active (in foreground).
P.P.S: I know this question seems similar to those asked few times, but they are (i hope all) different being necessary in using foreground service.
I wrote a medium article about this, including solution for most cases afaik.
https://medium.com/@lepicekmichal/android-background-service-without-hiccup-501e4479110f
Basically, you use ProcessLifecycleOwner, repeat in STARTED/RESUMED state, with some try again logic and cleverly catch errors.