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?

David
  • 1,842
  • 2
  • 21
  • 31
  • It looks like using a Service instead of the Application class is the way to go. The Service class provides an onDestroy handler. – David May 19 '11 at 00:23

3 Answers3

3

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

David
  • 1,842
  • 2
  • 21
  • 31
  • Do you mean herer that you just extended the Service class instead of the Application one? Or maybe it isn't so trivial? – 2dvisio Oct 04 '12 at 10:47
  • 1
    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). – David Oct 06 '12 at 06:00
  • 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. – 2dvisio Oct 06 '12 at 21:13
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.

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

Charith
  • 87
  • 4
  • 1
    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 ? – David May 18 '11 at 00:07
  • There is an event Application::onTerminate() but according to the API it is only called while running the app on the emulator. – David May 18 '11 at 00:07
  • 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! – 2dvisio Oct 09 '12 at 15:49