Is it possible to detect the Android App killed or exit by the user?
I try to use ActivityLifecycleCallbacks registerred in the Application class to detect it by assing an int parameter and increasing it in onActivityCreated like below; but it does not work.
I think the Android Service in my App makes this global counter variable (defined in a singleton class) not killed although the app has been killed.
It starts with zero only the first time when the app first start, then every app restart it has the the last value as the last time the app has been killed and never has a value of zero again.
Another question is that how can we release the global values to their initial values when the app killed that uses Android Service?
Singleton Class which has the global activity counter
public class SingletonClass {
public int created_activity_number;
private static volatile SingletonClass instance = null;
private SingletonClass() {
}
public static SingletonClass getInstance() {
if (instance == null) {
synchronized (SingletonClass.class) {
// Double check
if (instance == null) {
instance = new SingletonClass();
}
}
}
return instance;
}
}
ActivityLifecycleCallbacks class
public class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {
private static int created;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
SingletonClass.getInstance().created_activity_number++;
}
@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 bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
In any Activity I use below condition to check if the activity is the first created acitivy when the app starts.
// Enter this condition only one time no mattter how many times the application killed by the user end starts again.
if (SingletonClass.getInstance().created_activity_number == 1) {
// Yes, it is the first created activiy
}