Monday 25 July 2022

App process does not die when stopping a bound foreground service

I have a bound foreground service that is supposed to live even when the app is removed from recents, but with the option to also stop the service when the app gets removed. That optional path is what I am having trouble with.

If the service is not set as foreground, stopping the service causes the process to die as well. This is the desired effect:

enter image description here

However, if the service is set as foreground, the app process does not die:

enter image description here

What I tried:

  1. Stopping from onTaskRemoved inside the service:
    override fun onTaskRemoved(rootIntent: Intent) {
        stopForeground(true)
        stopSelf()
    }
  1. Setting stopAppWithTask to true in the manifest:
   <service
        android:name=".TestService" android:stopWithTask="true">
   </service>
  1. Stopping via activity:
override fun onStop() {
    super.onStop()
    unbindService(connection)
  
    mBound = false
}

override fun onDestroy() {
    Intent(applicationContext, TestService::class.java).also { intent ->
        stopService(intent)
    }
    super.onDestroy()
}
  1. Same as .3, but I stop the service as foreground in onStop. This works, but it's not ideal, as the service will stop being foreground every time the app is put to recents.
    override fun onStop() {
        super.onStop()
        mService.stopForeground()
        unbindService(connection)
        mBound = false
    }

    override fun onDestroy() {
        Intent(applicationContext, TestService::class.java).also { intent ->
            stopService(intent)
        }
        super.onDestroy()
    }
    // in the service
    fun stopForeground() {
        stopForeground(true)
    }

The questions I have are the following:

  1. Is the app process not stopping the desired effect?
  2. If yes, why does the process never die? I would be fine with the OS eventually killing the service, but it never happens (from what I have noticed)
  3. Why does stopping foreground in onStop lead to the process dying properly, but stopping it in onTaskRemoved keeps the process alive.


from App process does not die when stopping a bound foreground service

No comments:

Post a Comment