Muhammad Nasir
Muhammad Nasir

Reputation: 9

How to get App closing event?

I want to stop my thread when my app closes. Does any one know how can I do this?

public class ControlApplication extends Application
{
    private static final String TAG=ControlApplication.class.getName();
    private Waiter waiter;  //Thread which controls idle time
    private MySharedPrefrences prefs;

    // only lazy initializations here!
    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.d(TAG, "Starting application" + this.toString());
        Context ctx=getApplicationContext();
        waiter=new Waiter(1*60*1000,ctx);//(1*60*1000); //1 mins
        prefs=new MySharedPrefrences(this);
   //    start();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Log.d(TAG,"App terminated");
        prefs.SetLastVisitedActivity("");
        waiter.stopThread();
        waiter.loginUpdate(false);

    }
}

I want to call some methods when app terminates but I can't seem to get it working. Any suggestion please?

Upvotes: 0

Views: 1853

Answers (2)

Sid
Sid

Reputation: 489

Try calling super.onTerminate(); after stopping the thread, i.e.,

@Override
public void onTerminate() {
    Log.d(TAG,"App terminated");
    prefs.SetLastVisitedActivity("");
    waiter.stopThread();
    waiter.loginUpdate(false);
    super.onTerminate();
}

Update: onTerminate will never work on a device. http://developer.android.com/reference/android/app/Application.html#onTerminate%28%29

This method is for use in emulated process environments. It will never be called on a >production Android device, where processes are removed by simply killing them; no user code >(including this callback) is executed when doing so.

So your best bet is to create a base activity and let all other activities extend it. You can use onPause() of an Activity but if the app is terminated then there is no guarantee unless you call finish().

Update: As Nasir said in one of the comments, using onPause is not a good idea.

Upvotes: 1

Chandrakanth
Chandrakanth

Reputation: 3831

If your application has only one entry point then in your home/first activity override onDestroy() method, and from that method stop the thread.

Upvotes: 0

Related Questions