Android 使用ActivityLifecycleCallbacks监听自己应用Activity的生命周期

   

有时候我们需要对自己的Activity的生命周期进行监控,比如说手势密码,当满足条件后,需要把手势密码界面覆盖上去,Android 在4.0之后提供了

ActivityLifecycleCallbacks
这个借口提供了应用所有Activity的生命周期回调,用法如下:

public class MyApplication extends Application {

    private  int resumed;
    private  int paused;

    @Override
    public void onCreate() {
        super.onCreate();
        this.registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks()) ;

    }

    class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks
    {
        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
            Log.e("Activity", activity.getClass().getSimpleName()+"onActivityCreated");
        }

        @Override
        public void onActivityStarted(Activity activity) {
            Log.e("Activity",activity.getClass().getSimpleName()+"onActivityStarted");
        }

        @Override
        public void onActivityResumed(Activity activity) {
            Log.e("Activity",activity.getClass().getSimpleName()+"onActivityResumed");
            resumed++ ;
        }

        @Override
        public void onActivityPaused(Activity activity) {
            Log.e("Activity",activity.getClass().getSimpleName()+"onActivityPaused");
            paused++ ;
        }

        @Override
        public void onActivityStopped(Activity activity) {
            Log.e("Activity",activity.getClass().getSimpleName()+"onActivityStopped");

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
            Log.e("Activity",activity.getClass().getSimpleName()+"onActivitySaveInstanceState");
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            Log.e("Activity",activity.getClass().getSimpleName()+"onActivityDestroyed");
        }

       /* public boolean isApplicationInForeground() {
            // 当所有 Activity 的状态中处于 resumed 的大于 paused 状态的,即可认为有Activity处于前台状态中
            return resumed > paused;
        }*/
    }

}
在Application中实现这个接口,我们在启动MainActivity的时候打印日志:

 E/Activity: MainActivityonActivityCreated
 E/Activity: MainActivityonActivityStarted
 E/Activity: MainActivityonActivityResumed
然后在MainActivity中启动第二个Activity:


 E/Activity: MainActivityonActivityPaused
 E/Activity: SecondActivityonActivityCreated
 E/Activity: SecondActivityonActivityStarted
 E/Activity: SecondActivityonActivityResumed
 E/Activity: MainActivityonActivitySaveInstanceState
 E/Activity: MainActivityonActivityStopped
 第二个Activity 的生命周期依次打印,使用起来是非常的简便。


你可能感兴趣的:(Activity)