Skip to content

Instantly share code, notes, and snippets.

@alexjlockwood
Last active August 12, 2020 12:06
Show Gist options
  • Save alexjlockwood/6298122 to your computer and use it in GitHub Desktop.
Save alexjlockwood/6298122 to your computer and use it in GitHub Desktop.
Sample usage of the "android.app.Application.ActivityLifecycleCallbacks" class.
public class MainActivity extends Activity {
private final MyActivityLifecycleCallbacks mCallbacks = new MyActivityLifecycleCallbacks();
@Override
protected void onCreate(Bundle savedInstanceState) {
// Always register before calling into the super class.
getApplication().registerActivityLifecycleCallbacks(mCallbacks);
super.onCreate(savedInstanceState);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Always unregister after calling into the super class.
getApplication().unregisterActivityLifecycleCallbacks(mCallbacks);
}
public static class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Log.i(activity.getClass().getSimpleName(), "onCreate(Bundle)");
}
@Override
public void onActivityStarted(Activity activity) {
Log.i(activity.getClass().getSimpleName(), "onStart()");
}
@Override
public void onActivityResumed(Activity activity) {
Log.i(activity.getClass().getSimpleName(), "onResume()");
}
@Override
public void onActivityPaused(Activity activity) {
Log.i(activity.getClass().getSimpleName(), "onPause()");
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
Log.i(activity.getClass().getSimpleName(), "onSaveInstanceState(Bundle)");
}
@Override
public void onActivityStopped(Activity activity) {
Log.i(activity.getClass().getSimpleName(), "onStop()");
}
@Override
public void onActivityDestroyed(Activity activity) {
Log.i(activity.getClass().getSimpleName(), "onDestroy()");
}
}
}
@raul1991
Copy link

For an application having multiple activities , cant we implement this callback class in the Main Application class so it would know that which activity is currently being created/resumed/stopped etc ?

@sbmaggarwal
Copy link

@petterh
Copy link

petterh commented Apr 8, 2017

For what it's worth, I created a variant of this with a couple of tweaks:

  • The callback un-registers itself, thereby simplifying usage.
  • The callback knows which activity it was registered for, and ignores all others. (The callback is invoked for all activities, not just the one where we registered it.)

@ncuillery
Copy link

That was useful to me, thanks!

@rekafekili
Copy link

Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment