Last active
August 12, 2020 12:06
-
-
Save alexjlockwood/6298122 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 { | |
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()"); | |
} | |
} | |
} |
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.)
That was useful to me, thanks!
Thank you so much!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@raul1991 This should set you in the right direction - http://baroqueworksdev.blogspot.in/2012/12/how-to-use-activitylifecyclecallbacks.html ...