Lifecycle简介
Lifecycle是一个生命周期感知组件,一般用来响应Activity、Fragment等组件的生命周期变化,并将变化通知到已注册的观察者。有助于更好地组织代码,让代码逻辑符合生命周期规范,减少内存泄漏,增强稳定性。
可以和Lifecycle一起工作的类我们称之为有生命周期意识的控件。
我们建议那些提供了需要和Android生命周期打交道的类的库最好提供有生命周期意识的控件,
这样它们的用户就能轻松的集成这些类,而不是在客户端手动管理生命周期。
LiveData 就是一个有生命周期意识的控件的例子。使用LiveData 和 ViewModel 可以让数据部署到UI更简单。
Lifecycle已经纳入新版本的AppCompatActivity和Fragment中了,并且Lifecycle还是Android Jetpack中其他两个组件LiveData和ViewModel的基础
Lifecycle最佳实践
尽可能保持UI控制器(Activity和Fragment)的简洁。它们不应该去获取数据,而是使用ViewModel 来做这个工作,然后观察LiveData 把变化反应给view。
尝试写数据驱动的UI,UI controller的职责是在数据改变的时候更新view,或者把用户的操作通知给ViewModel。
把数据逻辑放在ViewModel 类中。ViewModel的角色是UI控制器与app其余部分的桥梁。不过要注意,ViewModel的职责并不是获取数据(比如,从网络)。相反 ViewModel应该调用合适的控件去做这件事情,然后把结果提供给UI控制器。
使用 Data Binding来让view和UI控制器之间的接口保持干净。这可以让你的view更加声明式同时最小化Activity和Fragment中的代码。如果你更喜欢用Java代码做这件事情,使用 Butter Knife来避免繁琐的代码。
如果你的UI非常复杂,考虑创建一个Presenter类来处理UI的变动。通常这会有点多余,但可能会让UI的测试更加简单。
绝对不要在 ViewModel中引用View 或者 Activity 的context。如果ViewModel活的比Activity更长,Activity可能会泄漏,无法正常回收。
使用Lifecycle解耦页面与组件
1.倒计时
class CountDownTimerLifecycle(btnCount:Button) : LifecycleObserver {
//总时间和倒计时间隔时间
val dSecond: Long = 1000
private var countDownTimer: CountDownTimer = object : CountDownTimer(10 * dSecond, 1 * dSecond) {
override fun onFinish() {
Log.i("zx", "倒计时完成")
btnCount.text = "倒计时完成"
}
override fun onTick(millisUntilFinished: Long) {
Log.i("zx", "倒计时:${millisUntilFinished / 1000}")
btnCount.text = "${millisUntilFinished / 1000}"
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun startCount() {
countDownTimer.start()
Log.i("zx", "on_resume")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun stopCount() {
countDownTimer.cancel()
Log.i("zx", "on_pause")
}
}
2.广播
class BroadCastLifecycle(private val activity: AppCompatActivity) : LifecycleObserver {
private val myBroadcastReceiver by lazy { MyBroadcastReceiver() }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun lifeOnResume() {
Log.v("zx", "注册广播")
val intentFilter = IntentFilter("zxmsg")
activity.registerReceiver(myBroadcastReceiver, intentFilter)
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun lifeOnPause() {
Log.v("zx", "取消注册广播")
activity.unregisterReceiver(myBroadcastReceiver)
}
}
使用LifecycleService解耦Service与组件
class LocationService : LifecycleService() {
override fun onCreate() {
super.onCreate()
lifecycle.addObserver(LocationObserver(this))
}
}
class LocationObserver(val context: Context) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun startLocation() {
Log.v("zx","startLocation")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun stopLocation() {
Log.v("zx","stopLocation")
}
}
binding.btnStartService.setOnClickListener {
startService(Intent(this, LocationService::class.java))
}
binding.btnStopService.setOnClickListener {
stopService(Intent(this, LocationService::class.java))
}
<service android:name=".lifecycle.LocationService"/>
使用ProcessLifecycleOwner监听应用程序生命周期
class IApplication:Application() {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationObserver())
}
}
class ApplicationObserver:LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(){
Log.v("zx","Application onCreate")
}
}
新版本AppCompatActivity和Fragment已经实现了LifecycleOwner,如果没实现需要怎么做呢
下面使用Activity实现LifecycleOwner
class TestActivity : Activity(), LifecycleOwner {
private val mLifecycleRegistry = LifecycleRegistry(this)
override fun onCreate(savedInstanceState: Bundle?) {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test)
initLifecycle()
}
private fun initLifecycle() {
lifecycle.addObserver(MyLifecycle())
}
override fun onStart() {
super.onStart()
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
}
override fun onResume() {
super.onResume()
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
}
override fun onPause() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
super.onPause()
}
override fun onStop() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
super.onStop()
}
override fun onDestroy() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
super.onDestroy()
}
override fun getLifecycle(): Lifecycle {
return mLifecycleRegistry
}
}
class MyLifecycle : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun myOnCreate() {
Log.v("zx", "myOnCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun myOnResume() {
Log.v("zx", "myOnResume")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun myOnPause() {
Log.v("zx", "myOnPause")
}
}
这样TestActivity 里面的生命执行的时候MyLifecycle 也会执行
Lifecycle官方库
lifecycle-extensions 中的 API 已弃用。您可以为特定 Lifecycle 工件添加所需的依赖项。
dependencies {
def lifecycle_version = "2.4.0"
def arch_version = "2.1.0"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
// Saved state module for ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
// Annotation processor
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
// optional - helpers for implementing LifecycleOwner in a Service
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
// optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
// optional - ReactiveStreams support for LiveData
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"
// optional - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$arch_version"
}
知识点1:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
lifecycleScope.launch {
//单次触发
whenCreated {}
whenStarted {}
whenResumed {}
lifecycleScope.launchWhenCreated {}
lifecycleScope.launchWhenStarted {}
lifecycleScope.launchWhenResumed {}
//多次onResume触发
viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
val id = BWallet.get().getCurrentWallet()?.id ?: 0
val pWallet = LitePal.find(PWallet::class.java, id, true)
refreshWallet(pWallet)
}
}
更多:
Android-Lifecycle超能解析-生命周期的那些事儿
Android 自定义view中实现LifecycleOwner
Jetpack 之 LifeCycle 组件原理解析