How do I detect if the user has left my app?

Viewed 22823

I am developing an Android app and I want to detect when the user exits my app either by clicking the Back button or the Home button.

Also, an event like onInit() would be useful in my scenario, as I just want to have the MyInıt action start at first.

onDestroy() is not called until other apps need more memory.

6 Answers

With the help of Application.ActivityLifecycleCallbacks you can track which activity is destroying and new activity is starting but when user swipe or back button(on last stack) then postdelayed will not call and also Activitystop and destroy will always call when you're inside your application if you want to catch user swipe or back button(on last stack) then this code will work.

public class Yourapp extends Application implements Application.ActivityLifecycleCallbacks {

    private Activity currentActivity; 
    private Handler closecheckhandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //do whatever you want
                default:
                    super.handleMessage(msg);
            }
        }
    };
    @Override
    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(this);

    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
        currentActivity = activity;

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity destroActivity) {
      if (currentActivity.equals(destroActivity)) {
            closecheckhandler.sendEmptyMessage(//Custom Code);
        } else {
            //do whatever you want
        }
    }
}
Related