介绍一种监视全局Activity生命周期的方法

2019-12-15  本文已影响0人  超级绿茶

以前想要对全部Activity的生命周期进行监控的通常作法是自定义一个BaseActivity,在这个类里面重写所有的生命周期方法,然后让所有的Activity都继承BaseActivity。不过最近才发现从Android API 28开始出现了一个Application类有了一个新的方法:registerActivityLifecycleCallbacks。方法定义如下:

    public void registerActivityLifecycleCallbacks(ActivityLifecycleCallbacks callback) {
        synchronized (mActivityLifecycleCallbacks) {
            mActivityLifecycleCallbacks.add(callback);
        }
    }

    public void unregisterActivityLifecycleCallbacks(ActivityLifecycleCallbacks callback) {
        synchronized (mActivityLifecycleCallbacks) {
            mActivityLifecycleCallbacks.remove(callback);
        }
    }

看源码就知道,registerActivityLifecycleCallbacks是用于注册生命周期监听的,而unregisterActivityLifecycleCallbacks自然就是用于注销监听的销。用法也很简单:

        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityPaused(activity: Activity?) {
                Log.i("123", activity?.localClassName + " onActivityPaused")
            }

            override fun onActivityResumed(activity: Activity?) {
                Log.i("123", activity?.localClassName + " onActivityResumed")
            }

            override fun onActivityStarted(activity: Activity?) {
                Log.i("123", activity?.localClassName + " onActivityStarted")
            }

            override fun onActivityDestroyed(activity: Activity?) {
                Log.i("123", activity?.localClassName + " onActivityDestroyed")
            }

            override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
                Log.i("123", activity?.localClassName + " onActivitySaveInstanceState")
            }

            override fun onActivityStopped(activity: Activity?) {
                Log.i("123", activity?.localClassName + " onActivityStopped")
            }

            override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
                Log.i("123", activity?.localClassName + " onActivityCreated")
            }

        })

上面的示例中在每个Activity的生命周期中都打印了一条Log语句。这时你可能会有个想法,如果我在自己指定的Activity的生命周期中也有代码,比如:都在onStart周期中插入了Log,那么全局的和局部的,哪个先执行?

    override fun onStart() {
        Log.i("123","onStart in actvitiy 1")
        super.onStart()
        Log.i("123","onStart in actvitiy 2")
    }

运行结果如下:


QQ截图20191215162138.png

可以看出全局的是通过父类的同名生命周期方法执行的。所以有了registerActivityLifecycleCallbacks后再做项目埋点时的时候又多了一种新的方法。

点击链接加入群聊【口袋里的安卓】:https://jq.qq.com/?_wv=1027&k=5z4fzdT
或关注微信公众号:

上一篇下一篇

猜你喜欢

热点阅读