Skip to content

Instantly share code, notes, and snippets.

@jesselima
Forked from petterh/MainActivity.java
Created March 31, 2020 18:30
Show Gist options
  • Save jesselima/50504775fc19f253a824451877626092 to your computer and use it in GitHub Desktop.
Save jesselima/50504775fc19f253a824451877626092 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);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment