Created
December 17, 2017 15:50
-
-
Save devqmr/509c5aa7cf840aa2a4dee37045e370d7 to your computer and use it in GitHub Desktop.
How to detect when an Android app goes to the background and come back to the foreground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity; | |
import android.app.Application; | |
import android.os.Bundle; | |
import android.util.Log; | |
/** | |
* Created by Ahmed AbuQamar on 12/17/17. | |
* | |
* | |
* Add next line Application class in your App | |
* registerActivityLifecycleCallbacks(new AppLifecycleTracker()); | |
* | |
* As next: | |
* | |
* @Override | |
* public void onCreate() { | |
* super.onCreate(); | |
* registerActivityLifecycleCallbacks(new AppLifecycleTracker()); | |
* } | |
* | |
*/ | |
public class AppLifecycleTracker implements Application.ActivityLifecycleCallbacks { | |
private static final String TAG = "AppLifecycleTracker"; | |
private int numberActivitiesStart = 0; | |
@Override | |
public void onActivityCreated(Activity activity, Bundle savedInstanceState) { | |
} | |
@Override | |
public void onActivityStarted(Activity activity) { | |
if (numberActivitiesStart == 0) { | |
// The application come from background to foreground | |
Log.d(TAG, "AppController status > onActivityStarted: app went to foreground"); | |
} | |
numberActivitiesStart++; | |
} | |
@Override | |
public void onActivityResumed(Activity activity) { | |
} | |
@Override | |
public void onActivityPaused(Activity activity) { | |
} | |
@Override | |
public void onActivityStopped(Activity activity) { | |
numberActivitiesStart--; | |
if (numberActivitiesStart == 0) { | |
// The application go from foreground to background | |
Log.d(TAG, "AppController status > onActivityStopped: app went to background"); | |
} | |
} | |
@Override | |
public void onActivitySaveInstanceState(Activity activity, Bundle outState) { | |
} | |
@Override | |
public void onActivityDestroyed(Activity activity) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment