-
-
Save petterh/ad5e52859bb906b9ac4da784ea568d7a to your computer and use it in GitHub Desktop.
Sample usage of the "android.app.Application.ActivityLifecycleCallbacks" class.
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
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); | |
} | |
} | |
} | |
} |
That was useful to me, thanks!
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
This example is an embellishment of this one, with some tweaks: