Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do some cleanup right before an Android app is quitting?

Is there some sort of onTerminate() method where I can do some cleanup (I want to clear some SharedPreferences) when my Android app is terminating?

I have an Activity that is keeping a running average of a few numbers, that I'm storing in a SharedPreference. I want this average to last while the app is running (the user can move between different activities) so I can't clear it on onDestroy() for that particular activity. I need to be able to clear it once the app is about to quit.

How can I do this?

like image 261
Sheehan Alam Avatar asked Nov 29 '25 22:11

Sheehan Alam


1 Answers

I've not tried this, but here's what I would do:

  • As Alex mentioned in the comment to original question, use a Service to share the app-wide state between Activities.
  • Whenever you move between Activities, bind to the service from the "new" activity, and unbind from the "old" one. Check this to understand how to coordinate activities.
  • If you follow this properly, you can ensure that at least one Activity is always bound to the Service as long as your app is running; and that all Activities are unbound when the app is no longer running - at which point your service's onDestroy() is called. This is where you perform your cleanup.
like image 68
curioustechizen Avatar answered Dec 01 '25 13:12

curioustechizen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!