Stefan Maimon
Stefan Maimon

Reputation: 233

Android, How do I know if the application has closed

I need to know when the user close the App, not when the user press on the "home" button, but when the user close the App at the "recent applications menu". At those two cases the App go to the onPause method. Is there any way to tell them apart? I`m asking because, I want to delete the user from my database on one situation, and not at the other.

Upvotes: 0

Views: 144

Answers (3)

Mario Lenci
Mario Lenci

Reputation: 10542

you can try combining multiple callbacks from the activity lifecycle.

onUserLeaveHint() can be realy usefull to get know if the activity is in background or foreground

isFinishing(): can bu used to know if the activity is been closed by a finish() call or if is the system shutting down the activity to free resources

Upvotes: 1

Vladimir Samoylov
Vladimir Samoylov

Reputation: 521

I'm not sure, but maybe ActivityLifecycleCallbacks can help you. It need to test.

Example:

public class YourApplication extends Application {

    @Override
    public void onCreate() {
        lifecycleListener = new ActivityLifecycleListener();
        registerActivityLifecycleCallbacks(lifecycleListener);
    }

    public class ActivityLifecycleListener implements Application.ActivityLifecycleCallbacks {

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

        @Override
        public void onActivityStarted(Activity activity) {
        }

        @Override
        public void onActivityResumed(Activity 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 activity) {
        }
    }
}

Upvotes: 0

ingyesid
ingyesid

Reputation: 2884

you can try using a Service for that, in this service override onTrimMemory method

@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    switch (level) {
        case ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN:
               //app was closed        
            break;
    }

}

check more about services

Upvotes: 0

Related Questions