Search code examples
androidandroid-fragmentsback-buttoncountdowntimerondestroy

Back button calls onDestroy() while my countdowntimer is active


I'm running a countdowntimer in a fragment and everytime I press the back button onDestroy() is called and kills my countdowns. When I launch my app again a new activity has started and the countdowns are gone.

onDestroy() isFinished() returns true.

This wont happend if I press the home button.

How can I keep this from happening? Use services? Set flags? override the back button? I'm lost here.


Solution

  • The destruction of your activity is out of your control. It fully depends on the garbage collector. If it needs to clean up memory, and your activity is in the background, it will destroy it most likely.

    You should use a service with startForeground(...) to make sure it will only be destroyed when it is absoslutely necessary. Also don't forget to acquire a WakeLock in your service, if you want to keep it alive while the screen is locked.