Faced such a problem: it is necessary to catch the launch and close of my application. At startup, a thread should be created (well, I have no problems with this), and when stopped method should be called once.

onCreate with start - created a class successor ( Application ), in onCreate appointed start of a flow. And with the closure of the application, I was stumped. The fact is that my application contains a lot of activations that open during the application, so in each onStop not an option to call stopped , and the Application cannot override the onStop method (since it does not exist).

The question is: "Is it possible to catch the complete closure of the application (and not a certain activation) and how?".

    1 answer 1

    Here I google to request:

    receive application stop event android

    issued this . Apparently, the second variant from the answer will suit you. In short, you need to set an Application in the Application setter and getter for the flag RUNNING and update it from each activation in onResume () and onPause ().

     class BaseActivity extends Activity { @Override protected void onResume() { super.onResume(); ((MyAppContext)getApplication()).setIsAppRunning(true); } @Override protected void onPause() { ((MyAppContext)getApplication()).setIsAppRunning(false); super.onPause(); } } 

    Thus, if all activations are closed, it will be false;
    And in the Apllication timer, follow the flag and do something. Code from the link:

     public class MyAppContext extends Application { public boolean isAppRunning = true; public final int timerRate = 500; // Execute timer task every 500mS public void setIsAppRunning(boolean v){ isAppRunning = v; } public boolean isAppRunning(){ return isAppRunning; } @Override public void onCreate() { super.onCreate(); Timer mTimer = new Timer(); mTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if(isAppRunning) startSesionTracking(); else stopSesionTracking(); } }, 0, REFRESH_TIME); } private void startSesionTracking () { ... }; private void stopSesionTracking () { ... }; }