2

I want to perform some activities like clearing cache, singletons clearing etc. I will write all this code in Service which will be background but I need this service to be triggered only when application is closed or exited.

I cant put my code to statrt service in onDestroy of activity as whenever i will move between my activities it will call onDestroy of previous activity.

How to know if application is exited.

Example will really help.

Thanks.

virendrao
  • 1,763
  • 2
  • 22
  • 42
  • `onStop()` and `onDestroy()` are the places to check whether your app is there or not in memory. – intrepidkarthi Jul 29 '14 at 07:45
  • Better use the `onDestroy()` override – Phantômaxx Jul 29 '14 at 07:49
  • Using a `Service` to do this is bad design and a pointless use of extra code (which may or may not run correctly anyway).You need to save data as you go along and save state of application components at the point they are either paused or stopped. – Squonk Jul 29 '14 at 07:52
  • @FrankN.Stein : The `onDestroy` method of `Activity` is not guaranteed to be called and should never be relied on for saving data or state. – Squonk Jul 29 '14 at 07:54
  • @Squonk : But `onStop()` will fire at every device rotation... – Phantômaxx Jul 29 '14 at 07:58
  • Here http://stackoverflow.com/questions/12121783/saving-android-application-data-on-app-exit is similar thread. Read accepted answer. – Pankaj Kumar Jul 29 '14 at 07:58
  • @FrankN.Stein : So what is your point? Change of device orientation will cause an `Activity` to be destroyed and recreated - in this case `onDestroy()` will be called but under other circumstances `onDestroy` may not be called. As a result, relying on `onDestroy` for saving of data or state isn't a safe option. – Squonk Jul 29 '14 at 08:09
  • @Squonk You're right. I didn't think that `onDestroy()` was called upon rotation too. Just upon app termination. – Phantômaxx Jul 29 '14 at 08:12
  • @all i want to handle when application is exited not when activity is destroyed – virendrao Jul 29 '14 at 08:37

2 Answers2

2

The ActivityManager should be what you are looking for.

For example see here

Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
1

in your main activity, capture the "back" key and check for Activity.isTaskRoot() whether it is the last one. If yes, your app is going to "exit", then do some communication with your service.

please note pressing the Home key doesn't mean to "exit" your app

DayDayHappy
  • 1,679
  • 1
  • 15
  • 26