Search code examples
androidservicebackground-service

Android start background service from foreground app


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:

  • OnLifecycleEvent(ON_RESUME) instead of ON_START
  • Hooking onto ProcessLifecycleOwner.get() lifecycle instead of activity's one
  • Even checking right before lifecycle.currentState will not help

Nevertheless, 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.


Solution

  • 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.