Skip to content

Instantly share code, notes, and snippets.

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

petterh commented Apr 8, 2017

This example is an embellishment of this one, with some 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!

@aouledissa
Copy link

Nice approach, Except that you will leak the activity in line 6 by passing this of a non final class.

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