Android app doesn't call "onDestroy()" when killed (ICS)

The Good Giant picture The Good Giant · Jul 13, 2012 · Viewed 25.3k times · Source

I'm developing an android app using bluetooth communication (using a propetary protocol) and I need to catch the moment when the app is killed.

I wanted to use the "onDestroy()" method but it isn't called every time the app is killed. I noticed that it is called when I press the back button and, only sometimes, when I kill the app from the task manager.

The question is: How can I catch the moment before the app is killed?

Here is the code I tried to use:

@Override
public void onDestroy() {
    sendMessage(msg);
    Log.d("SampleApp", "destroy");
    super.onDestroy();
}

@Override
public void finish(){

    sendMessage(msg);
    Log.d("SampleApp", "finish");
    super.finish();
}

Unfortunately finish() is never called and onDestroy isn't called every time I close the app from the task manager.

How can I handle this?

Answer

Raghav Sood picture Raghav Sood · Jul 13, 2012

As stated in the documentation here, there is no guarantee that onDestroy() will ever be called. Instead, use onPause() to do the things you want to do whenever the app moves into the background, and leave only that code in onDestroy() that you want run when your app is killed.

EDIT:

From your comments, it seems that you want to run some code whenever your app goes into the background, but not if it went into the background because you launched an intent. AFAIK, there is no method in Android that handles this by default, but you can use something like this:

Have a boolean like:

boolean usedIntent = false;

Now before using an intent, set the boolean to true. Now in your onPause(), move the code for the intent case into an if block like this one:

if(usedIntent)
{
//Your code
}

Finally, in your onResume(), set the boolean to false again so that it can deal with your app being moved into the background by a non intent means properly.