开发小技巧之在Application中监听App中的Activity的生命周期

在有一些场景下,需要我们在app从后台进程到前台进程的切换过程中,做一些操作,如展示一个公司广告页面等等情况。这个时候,我们可以在我们的Application中来监听当前App的状态,Google已经给我们封装好了方法:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("justh","application oncreate");

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                Log.i("justh","onActivityCreated");
            }

            @Override
            public void onActivityStarted(Activity activity) {
                Log.w("justh","onActivityStarted");
            }

            @Override
            public void onActivityResumed(Activity activity) {
                Log.e("justh","onActivityResumed");
            }

            @Override
            public void onActivityPaused(Activity activity) {
                Log.i("justh","onActivityPaused");
            }

            @Override
            public void onActivityStopped(Activity activity) {
                Log.i("justh","onActivityStopped");
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                Log.i("justh","onActivitySaveInstanceState");
            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }
}

对,就是这个registerActivityLifecycleCallbacks方法,具体的生命周期该调用的方法应该就不需要过多说明了吧,嘿嘿!

你可能感兴趣的:(Android)