4

I am new to android development. I am working on a android app.

Can anyone say me how to call a particular method in android, when an user kill or terminate my app. In other words, I need to execute a particular method first when user kills/terminate my app from their mobile. So that, the specific method will be executed first and then my app will be closed.

Any suggestions please. Thank you.

1 Answers1

5

This is possible by overriding the onStop or onDestroy methods of your Activity.

Like this:

public class MyActivity extends Activity{

     //Other methods here (onCreate, and such)

     @Override
     public void onStop()
     {
         super.onStop();
         //Do whatever you want to do when the application stops.
     }
     @Override
     public void onDestroy()
     {
         super.onDestroy();
         //Do whatever you want to do when the application is destroyed.
     }

}
  • onStop gets called just before the user exits the activity , or when another activity starts pushing this one in the background.
  • onDestroy gets called just before you completely finish the activity by calling Activity.Finish(), or when the system has to remove it from the memory to save space.

For more info about the application lifecycle , see here.

Leon Lucardie
  • 9,541
  • 4
  • 50
  • 70
  • 1
    NB. See the Android Activity lifecycle documentation. These methods are not guaranteed to be called. You should not rely on them to put your app into a state when it can safely be resumed. It's too late. You should be doing stuff earlier, e.g. onPause() – Simon Sep 23 '12 at 16:51
  • That's true. One thing to take note of in `onPause` however is the fact that it also fires when another `Activity` comes into the foreground. (Like a custom dialog for example). See http://stackoverflow.com/questions/7240916/android-under-what-circumstances-would-a-dialog-appearing-cause-onpause-to-be/7384782#7384782 – Leon Lucardie Sep 23 '12 at 17:02