Hammad Shahid
Hammad Shahid

Reputation: 2216

How to check whether an application is being closed in android

I am trying to mantain a log , when exits the applicaiton. I have used this code :

public void onDestroy() {
    super.onDestroy();    
    Log.d("D", "Destroyed");     
}

But this only works when I press the Back button. When I press Home button , the application Pauses , and If I close this application from task manager , then the onDestroy function is not called. How to handle this ?

Any idea ?

Upvotes: 1

Views: 2492

Answers (4)

Shreyos Adikari
Shreyos Adikari

Reputation: 12744

You can do your stuff in onPause() method.
In your case:
If End Process is used from Process list in task manager, then nothing is called in application, the application is simply terminated.
If End Task is used from Applications list, then WM_CLOSE is sent to the window, which in turn allows application to do the cleanup.

Upvotes: 1

W.K.S
W.K.S

Reputation: 10095

From the Android Developer Guide:

There are a few scenarios in which your activity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish(). The system may also destroy your activity if it's currently stopped and hasn't been used in a long time or the foreground activity requires more resources so the system must shut down background processes to recover memory.

When you switch between apps by pressing the home button, Android pauses the activity and resumes it when you return to the activity.

For the most part, the OS decides when to quit an application so it wouldn't make sense for you to log when an activity is destroyed. I would suggest overriding the onPause() or the onStop() method

Upvotes: 0

Sunil Kumar
Sunil Kumar

Reputation: 7092

onDestroy() is called when an activity finishes its life cycle. It is also called once in the lifecycle of an activity.

The OS decides when things "go away." The onDestroy is there to let your app have a final chance to clean things up before the activity does get destroyed.

Upvotes: 0

Eli Blokh
Eli Blokh

Reputation: 12293

You can't handle the closing of application from task manager. In this case you're killing the app and onDestroy isn't called. You should make all clean up in onPause

Upvotes: 2

Related Questions