'Adding function to foreground service lifecycle methods can create an issue? Is this best practise?

I created a timer app. So it's counting time basically and I'm saving the time to room when service close in OnDestroy scope. Is it best practise? Or is there any case that call the lifecycle methods without at user request?

onDestroy(){
      someBusinessLogic() // I'm saving the time to room here
      super.onDestroy()
   }


Solution 1:[1]

Please note that the above approach is not efficient / performant.
This approach is consuming valuable Android System Resources because the timer which is counting time is still running in the background when the user navigates to another app OR when user received a phone call.

This app will work but the Android OS will kill this app session first when it needs more memory.
This will lead to inconsistent user experience and low rating on Play Store.

The solution to this case is to study and implement Activity Lifecycle callback.

The timer should stop as soon as the onPause() is called and not on onDestroy().

Please refer to above link and implement required callbacks accordingly. This way you will create a performant and memory friendly app.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SVK