lannyf
lannyf

Reputation: 11025

Unbound and stopped Service's onDestroy is not called

The Activity in its onStart() binds to the MusicPlayService, and in its onStop() it unbinds the MusicPlayService. In its onDestroy() it calls the stopService, but the MusicPlayService's onDestroy() is not getting called at all.

****** UPDATE: it is the isFinishing in the onDestroy() is false.

if press the Back button, the activity::onDestroy() has isFinishing == true, and if press home button the onDestroy() is called (I have the 'dont keep activity alive' setting checked) but the isFinishing == false.

I guess it is the correct behavior, that only activity's finish() will start to set isFinishing == true. Even though the home button will trigger the onDestroy(), the os may still think this is not the true 'finishing'.

Wondering if the new arch-lifecycle LifecycleRegistryOwner could provides some hook for the activity is truly be destroyed.

Here is the snippet of the activity:

override fun onStart() {
    super.onStart()
    if (!isBound) {
        val bindIntent = Intent(this, MusicPlayService::class.java)
        isBound = bindService(bindIntent, myConnection,
                Context.BIND_AUTO_CREATE)
    }
}

override fun onStop() {
    super.onStop()
    unbindService(myConnection)
    isBound = false
}


override fun onDestroy() {
    super.onDestroy()
    if (isFinishing) {
        val intentStopService = Intent(this, MusicPlayService::class.java)
        stopService(intentStopService)
    }
}

Upvotes: 2

Views: 406

Answers (2)

Malik Ahsan
Malik Ahsan

Reputation: 989

The condition

if (isFinishing) {
    val intentStopService = Intent(this, 
MusicPlayService::class.java)
    stopService(intentStopService)
 }

which you are checking in the onDestroy() always returns false in onDestroy. isFinishing is usually used in onPause () and returns true there. As onDestroy is called after the activity has already been finished and isFinished returns false. Hence the service destroy code of your implementation is not execured.

Upvotes: 0

stkent
stkent

Reputation: 20128

To answer your eventual question (paraphrased):

Why would isFinishing ever be false in onDestroy?

Here's the relevant snippet from the source code:

* The final call you receive before your
* activity is destroyed.  This can happen either because the
* activity is finishing (someone called {@link Activity#finish} on
* it, or because the system is temporarily destroying this
* instance of the activity to save space.  You can distinguish
* between these two scenarios with the {@link
* Activity#isFinishing} method.

So the isFinishing flag is a helper for differentiating between two distinct reasons for Activity destruction.

Upvotes: 3

Related Questions