is there an Application::onDestroy() equivalent for Android?
Asked Answered
D

3

10

Hi I am using the Application::onCreate to put my initialisation code of my app, but when waiting some time and starting other apps, I noticed the instance of the Application class gets created again...

How to detect globally when Android is shuttting down my Application instance?

Deliberation answered 17/5, 2011 at 10:55 Comment(1)
It looks like using a Service instead of the Application class is the way to go. The Service class provides an onDestroy handler.Deliberation
D
4

I have been using the Service class and had no problem since. If someone has a better answer, let me know.

Deliberation answered 26/7, 2011 at 21:12 Comment(3)
Do you mean herer that you just extended the Service class instead of the Application one? Or maybe it isn't so trivial?Indefatigable
One tricky thing to note is that your activities may be garbage collected while your service will stay alive. It's not a problem unless for some odd reason you need the service to maintain a reference to the activity (e.g. if you need to stream data from the service to the activty).Deliberation
That would not be a problem. My idea was to implement a file logger other than Log that could flush its buffers once the main application (in this case the service) is destroyed. And since the Application class does not have that method, I didn't even tried for the moment.Indefatigable
W
2

How to detect globally when Android is shutting down my Application instance?

You can't do that. User/Environment can kill the application manually on production. Android would not give you any feedback about this.

P.S. If you're using emulated process environment you can take a look at Application onTerminate method.

Winfordwinfred answered 19/10, 2014 at 16:40 Comment(0)
T
0

I am not an experienced android developer. But as a beginner, I think you can use the onDestroy() method of the Activity.

It's a good idea for you to look into the Lifecycle of the Activity.

(Search for Lifecycle in the following link) http://developer.android.com/guide/topics/fundamentals/activities.html

Treble answered 17/5, 2011 at 11:6 Comment(3)
yes, but I have several activities and I want to get notified when Android kills my app process. Activities will be shutdown when they are not in used, but the Application process is supposed to remain in memory. However there is cases when the Application is still closed by Android, how to handle this event ?Deliberation
There is an event Application::onTerminate() but according to the API it is only called while running the app on the emulator.Deliberation
This could be part of the solution. In the sense that I could also flush the Logger as soon as one activity is closed. But still I will need to know when my entire application is closed, not only each single activity. Thank you very much for your effort!Indefatigable

© 2022 - 2024 — McMap. All rights reserved.