トラッキング コード

12/12/2012

How to use ActivityLifecycleCallbacks in Application Class

Do you want to add same code in all your ActivityLifeCycle?
You must use ActivityLifecycleCallbacks.

ActivityLifecycleCallbacks is interface of Application.class.
Can handle the called lifeCycle of Activity.


Sample code:
public class MyApplication extends Application {

    @Override
 public void onCreate (){
  super.onCreate();
  registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
 }
 
    @Override
    public void onTerminate (){
     super.onTerminate();
    }
    
    @Override
    public void onConfigurationChanged (Configuration newConfig){
     super.onConfigurationChanged(newConfig);
    }
    
    private static final class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {

  public void onActivityCreated(Activity activity, Bundle bundle) {
   Log.e("","onActivityCreated:" + activity.getLocalClassName());
  }

  public void onActivityDestroyed(Activity activity) {
   Log.e("","onActivityDestroyed:" + activity.getLocalClassName());
  }

  public void onActivityPaused(Activity activity) {
   Log.e("","onActivityPaused:" + activity.getLocalClassName());
  }

  public void onActivityResumed(Activity activity) {
   Log.e("","onActivityResumed:" + activity.getLocalClassName());
  }

  public void onActivitySaveInstanceState(Activity activity,
    Bundle outState) {
   Log.e("","onActivitySaveInstanceState:" + activity.getLocalClassName());
  }

  public void onActivityStarted(Activity activity) {
   Log.e("","onActivityStarted:" + activity.getLocalClassName());
  }

  public void onActivityStopped(Activity activity) {
   Log.e("","onActivityStopped:" + activity.getLocalClassName());
  }
    }
}

5 comments:

  1. Excellent, concise example. Thank you!

    ReplyDelete
  2. 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 ?
    I need at application level to check the application - is in background or foreground ??
    Plz give the answer ..

    ReplyDelete
  3. what is the main purpose for the method registerActivityLifecycleCallbacks ??

    ReplyDelete
  4. Very nice demonstration. Thank you so much, you made my day.

    ReplyDelete