【Android】ActivityLifecycleCallbacks探索

【Android】ActivityLifecycleCallbacks探索_第1张图片
0_1314838777He6C.gif

上面的图,大家都不陌生,我想大家都在activity里的生命周期里面写过打印语句,如

@Override
protected void onRestart() {
super.onRestart();

    Log.i(TAG, "onRestart:这个要注意 ");
}

其实,谷歌在Application里提供了一个内部接口ActivityLifecycleCallbacks,我们只需要在Application里面实现这个接口,即可打印Activity生命周期,如下:

private static class ActivityLifecycle implements Application.ActivityLifecycleCallbacks {
private static final String TAG = "Activity";

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        Log.i(TAG, "onCreate: " + activity.getClass().getSimpleName());
        getInstance().mActivityStack.add(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {
    }

    @Override
    public void onActivityResumed(Activity activity) {
    }

    @Override
    public void onActivityPaused(Activity activity) {
    }

    @Override
    public void onActivityStopped(Activity activity) {
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        Log.i(TAG, "onDestroy: " + activity.getClass().getSimpleName());
        getInstance().mActivityStack.remove(activity);
    }
}

你可能感兴趣的:(【Android】ActivityLifecycleCallbacks探索)