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()); } } }
Excellent, concise example. Thank you!
ReplyDeleteFor 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 ?
ReplyDeleteI need at application level to check the application - is in background or foreground ??
Plz give the answer ..
what is the main purpose for the method registerActivityLifecycleCallbacks ??
ReplyDeleteVery nice demonstration. Thank you so much, you made my day.
ReplyDelete