当前位置:网站首页>2022 · 让我带你Jetpack架构组件从入门到精通 — Lifecycle
2022 · 让我带你Jetpack架构组件从入门到精通 — Lifecycle
2022-07-01 13:19:00 【InfoQ】
前言
介绍


Lifecycle
我相信,在你第一次看见Lifecycle时,你会有下面四个疑问:
- Lifecycle到底是什么呢?
- 它是用来干什么的?
- 它有什么优势呢?
- 它要怎么用呢?
Lifecycle是什么:
- life:生命,(某事物)的存在期
- cycle:周期
Lifecycle用来干什么:
lifecycle有什么优势呢?
- Lifecycler实现了执行的逻辑和活动的分离,代码解耦并且增加了代码的额可读性
- Lifecycler在活动结束时自定移除监听,避免了声明周期的问题
如何使用Lifecycle呢?
- Lifecycle
- Lifecycle是一个抽象类,实现子类为LifecycleRegistry
class LifecycleRegistry extends Lifecycle{
.......
}
- lifecycleRegister
- lifecycle的唯一子类,用于在生命周期变化时触发自身状态和相关观察者的订阅回调逻辑
- LifecycleOwner
- 用于连接有生命周期的对象
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
- LifecycleObserver
- Lifecycle观察者
- State(Lifecycle的抽象类内部)
- 表示当前生命周期所处状态
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
- Event(Lifecycle的抽象类内部)
- 当前生命周期改变对应的事件
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
......
}
Lifecycle的使用:
- gradle的引用
dependencies {
def lifecycle_version = "2.5.0-rc01"
def arch_version = "2.1.0"
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"
testImplementation "androidx.arch.core:core-testing:$arch_version"
}
> 这里可以发现我们导入了lifecycle-service,lifecycle-process这两个组件,因为,在新版的SDK中,Activity/Fragment已经默认实现了LifecycleOwner接口,针对Service,Android 单独提供了LifeCycleService,而不是像Activity、Fragment默认实现了LifeCycleOwner。针对Application,Android 提供了ProcessLifeCycleOwner 用于监听整个应用程序的生命周期。
LifecycleObserver
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
//OnLifecycleEvent已经过时了
class MyLifecycleTest : LifecycleObserver {
companion object{
private const val TAG = "MyLifecycleTest"
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun create() {
Log.d(TAG, "create: ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun start() {
Log.d(TAG, "start: ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun resume() {
Log.d(TAG, "resume: ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun pause() {
Log.d(TAG, "pause: ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stop() {
Log.d(TAG, "stop: ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun destroy() {
Log.d(TAG, "destroy: ")
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun any() {
// Log.d(TAG, "any: ")
}
}
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(MyLifecycleTest())
}
}

- 使用
DefaultLifecycleObserver
DefaultLifecycleObserver@OnLifecycleEventMyDefaultLifecycleObserver继承于DefaultLifecycleObserverimport android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
class MyDefaultLifecycleObserver : DefaultLifecycleObserver {
companion object {
private const val TAG = "MyDefaultLifecycleObserver"
}
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
Log.d(TAG, "onCreate: ")
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
Log.d(TAG, "onStart: ")
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
Log.d(TAG, "onResume: ")
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
Log.d(TAG, "onPause: ")
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
Log.d(TAG, "onStop: ")
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
Log.d(TAG, "onDestroy: ")
}
}
MyApplicationaddObserver()ObserverLifecycleRegistryimport android.app.Application
import androidx.lifecycle.ProcessLifecycleOwner
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(MyDefaultLifecycleObserver())
}
}


举例几个Lifecycle的使用场景:
- Retrofit配合Lifecycle管理Http生命周期
- 这里推荐阅读:https://mp.weixin.qq.com/s/omCnmMX3XVq-vnKoDnQXTg
- 暂停和恢复动画绘制
- 视频的暂停与播放
- Handler 的消息移除
- ........
这里留下几个问题:
- Lifecycle的创建方式有哪几种(有什么不同,推荐使用哪一种)?
- Lifecycle是如何进行生命周期同步的?
- Event事件和State状态是什么关系?
- Lifecycle的注册,派发,感知的过程是怎么样的?
- 什么叫做嵌套事件?发生的时机是什么?Lifecycle是如何解决的?
边栏推荐
- Listen in the network
- SAP intelligent robot process automation (IRPA) solution sharing
- 终端识别技术和管理技术
- Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 2022 ~ 2028
- 二传感器尺寸「建议收藏」
- Example code of second kill based on MySQL optimistic lock
- Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"
- Report on the current situation and development trend of bidirectional polypropylene composite film industry in the world and China Ⓟ 2022 ~ 2028
- 20个实用的 TypeScript 单行代码汇总
- Investment analysis and prospect prediction report of global and Chinese dimethyl sulfoxide industry Ⓦ 2022 ~ 2028
猜你喜欢

波浪动画彩色五角星loader加载js特效

Cs5268 advantages replace ag9321mcq typec multi in one docking station scheme

French Data Protection Agency: using Google Analytics or violating gdpr
![[machine learning] VAE variational self encoder learning notes](/img/38/3eb8d9078b2dcbe780430abb15edcb.png)
[machine learning] VAE variational self encoder learning notes

Judea pearl, Turing prize winner: 19 causal inference papers worth reading recently

进入前六!博云在中国云管理软件市场销量排行持续上升

JS discolored Lego building blocks

SVG钻石样式代码

Anti fraud, refusing to gamble, safe payment | there are many online investment scams, so it's impossible to make money like this

Terminal identification technology and management technology
随机推荐
焱融看 | 混合云时代下,如何制定多云策略
Spark source code (V) how does dagscheduler taskscheduler cooperate with submitting tasks, and what is the corresponding relationship between application, job, stage, taskset, and task?
Some summary of pyqt5 learning (overview of the general meaning of some signals and methods)
Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 2022 ~ 2028
Google Earth engine (GEE) - Global Human Settlements grid data 1975-1990-2000-2014 (p2016)
Word2vec training Chinese word vector
洞态在某互联⽹⾦融科技企业的最佳落地实践
MySQL六十六问,两万字+五十图详解!复习必备
Shangtang technology crash: a script written at the time of IPO
9. Use of better scroll and ref
spark源码(五)DAGScheduler TaskScheduler如何配合提交任务,application、job、stage、taskset、task对应关系是什么?
SAP 智能机器人流程自动化(iRPA)解决方案分享
6. Wiper part
Flow management technology
Flutter SQLite使用
Analysis report on the development trend and Prospect of new ceramic materials in the world and China Ⓐ 2022 ~ 2027
MySQL statistical bill information (Part 2): data import and query
Social distance (cow infection)
网络中的listen
Investment analysis and prospect prediction report of global and Chinese dimethyl sulfoxide industry Ⓦ 2022 ~ 2028