App closing event in Android

In general, there's no such thing as closing applications in Android: the user just stops using the app. It's up to the programmer to make sure that the user does not mention process creation and termination.

Please note that Android may kill the application process when it lacks memory and restart the application later.

For example, one of old office-like apps had the following bug: the user wanted to insert a photo, the office application invoked the Camera app, and Android killed the office app. The office app was not ready for a restart and lost all document changes (which was the bug). Apparently, the buggy app ignored the bundle passed to onCreate().

So the process life cycle and the application life cycle are different things. The process restart is visible to the application: the static variables get reset to their initial values (most likely, null). So it is possible to have a non-null bundle and null static data structures.

One example of executing a piece of code when the process dies may be found below: Android camera locked after force close . The problem solved in that post was that Android by itself does not close the camera when the process dies. I cannot tell from your post whether or not your problem is similar to this one.


I suggest you to make a custom application class and note store the visibility of application wether it is running in background or not.obviously if you don't close the application like this

How to close Android application?

have a look at this so that you don't close it from background and perform the visibility check like this.

public class MyApplication extends Application {

public static boolean isActivityVisible() {
return activityVisible;
}  

public static void activityResumed() {
activityVisible = true;
}

public static void activityPaused() {
activityVisible = false;
}

 private static boolean activityVisible;
}

and this is how you register you application class to the manifest file.

<application
android:name="your.app.package.MyApplication"
android:icon="@drawable/icon"
android:label="@string/app_name" >

and override these two methods like this.

@Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();
}

@Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();
}

now check this status and perform what you like if it is running in background.You can take help of Booleans to check if the application is not closed by other reasons.


Just to answer my own question now after so much time. When user close the app, the process is terminated with no notice. onDestroy is not guaranteed to be called. only when you explicitly call finish().