Android Jetpack - Lifecycles

Posted teletian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Jetpack - Lifecycles相关的知识,希望对你有一定的参考价值。

◾︎简介

Lifecycles 是一个持有组件生命周期状态(如 Activity、Fragment)信息的类,并允许其他对象观察此状态。可以帮助我们方便的管理 Activity 和 Fragment 的生命周期。通过使用 Lifecycles 组件,可以将依赖组件的代码从生命周期方法移入组件本身中。有助于写出更有条理且往往更精简的代码,这样的代码更易于维护。

生命周期的状态和事件如下图

本文代码使用 Kotlin 讲解,若需查看 Java 代码写法,请参考文末 Sample

◾︎添加依赖

def lifecycle_version = "2.3.1"

// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"

◾︎简单例子

Lifecycles 是通过观察者模式实现的。
先定义一个观察者类继承自 LifecycleObserver,然后在 Activity 中注册这个观察者。
Activity 必须继承自 androidx.activity.ComponentActivity 或它的子类(AppCompatActivity 就是这样的类),因为 ComponentActivity 实现了 LifecycleOwner 接口,否则要自己实现并添加相关代码

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.i(javaClass.name, "onCreate")

        lifecycle.addObserver(MyObserver())
    }

    override fun onStart() {
        super.onStart()
        Log.i(javaClass.name, "onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.i(javaClass.name, "onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.i(javaClass.name, "onPause")
    }

    override fun onStop() {
        super.onStop()
        Log.i(javaClass.name, "onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(javaClass.name, "onDestroy")
    }

    class MyObserver : LifecycleObserver {
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate() {
            Log.i(javaClass.name, "onCreate")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onStart() {
            Log.i(javaClass.name, "onStart")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun onResume() {
            Log.i(javaClass.name, "onResume")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun onPause() {
            Log.i(javaClass.name, "onPause")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onStop() {
            Log.i(javaClass.name, "onStop")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun onDestroy() {
            Log.i(javaClass.name, "onDestroy")
        }
    }
}

◾︎Presenter 例子

如果不使用 Lifecycles 管理,必须在 Activity 的每个生命周期里面调用 Presenter 的方法,代码如下:

interface BasePresenter {
    fun onCreate()
    fun onStart()
    fun onResume()
    fun onStop()
    fun onDestroy()
}
class MainPresenter : BasePresenter {

    override fun onCreate() {
        Log.i(javaClass.name, "onCreate")
    }

    override fun onStart() {
        Log.i(javaClass.name, "onStart")
    }

    override fun onResume() {
        Log.i(javaClass.name, "onResume")
    }

    override fun onStop() {
        Log.i(javaClass.name, "onStop")
    }

    override fun onDestroy() {
        Log.i(javaClass.name, "onDestroy")
    }
}
class MainActivity : AppCompatActivity() {
    private val presenter: MainPresenter = MainPresenter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.i(javaClass.name, "onCreate")
        presenter.onCreate()
    }

    override fun onStart() {
        super.onStart()
        Log.i(javaClass.name, "onStart")
        presenter.onCreate()
    }

    override fun onResume() {
        super.onResume()
        Log.i(javaClass.name, "onResume")
        presenter.onCreate()
    }

    override fun onPause() {
        super.onPause()
        Log.i(javaClass.name, "onPause")
        presenter.onCreate()
    }

    override fun onStop() {
        super.onStop()
        Log.i(javaClass.name, "onStop")
        presenter.onCreate()
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(javaClass.name, "onDestroy")
        presenter.onCreate()
    }
}

那么怎么使用 Lifecycles 管理 Presenter 周期呢?
改造 MainPresenter,让它实现 LifecycleObserver 接口,并为每个生命周期函数添加 @OnLifecycleEvent 事件

class MainPresenter : BasePresenter, LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    override fun onCreate() {
        Log.i(javaClass.name, "onCreate")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    override fun onStart() {
        Log.i(javaClass.name, "onStart")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    override fun onResume() {
        Log.i(javaClass.name, "onResume")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    override fun onStop() {
        Log.i(javaClass.name, "onStop")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    override fun onDestroy() {
        Log.i(javaClass.name, "onDestroy")
    }
}

MainActivity 中不需要每个生命周期函数调用 Presenter 了,直接注册 LifecycleObserver 即可

class MainActivity : AppCompatActivity() {

    private val presenter: MainPresenter = MainPresenter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.i(javaClass.name, "onCreate")
        lifecycle.addObserver(presenter)
    }

    override fun onStart() {
        super.onStart()
        Log.i(javaClass.name, "onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.i(javaClass.name, "onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.i(javaClass.name, "onPause")
    }

    override fun onStop() {
        super.onStop()
        Log.i(javaClass.name, "onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(javaClass.name, "onDestroy")
    }
}

◾︎监听 Application 生命周期

Android 里面没有提供应用进入后台以及回到前台的回调方法。一般的做法是通过registerActivityLifecycleCallbacks 方法,然后再 callback 的 onActivityStarted 中计数加 1,onActivityStopped 中计数减 1,从而判断前后台状态。

有了 Lifecycle,并通过 ProcessLifecycleOwner 可以更简单的实现。

添加依赖

implementation 'androidx.lifecycle:lifecycle-process:2.3.1'

像使用 Livecycle 一样使用 ProcessLifecycleOwner。

import android.app.Application
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner

class App : Application() {

    override fun onCreate() {
        super.onCreate()

        ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationLifecycleObserver())
    }

    inner class ApplicationLifecycleObserver : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onAppForeground() {
            Log.i("tianjf", "App foreground")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onAppBackground() {
            Log.i("tianjf", "App background")
        }
    }
}

◾︎Sample

Kotlin 版
Java 版

以上是关于Android Jetpack - Lifecycles的主要内容,如果未能解决你的问题,请参考以下文章

Android Jetpack学习之旅--> 开始使用 Jetpack

Android Jetpack架构组件带你了解Android Jetpack

Android Jetpack简介

Android Jetpack架构组件——什么是Jetpack?

Android Jetpack架构组件——什么是Jetpack?

《Android Jetpack从入门到精通+高级Jetpack强化实战》,最新Jetpack系列开发笔记开源