当前位置:网站首页>2022. Let me take you from getting started to mastering jetpack architecture components - lifecycle
2022. Let me take you from getting started to mastering jetpack architecture components - lifecycle
2022-07-01 13:47:00 【InfoQ】
Preface
Introduce


Lifecycle
I Believe , When you first saw Lifecycle when , You will have the following four questions :
- Lifecycle What is it ?
- What is it used for ?
- What are its advantages ?
- How to use it ?
Lifecycle What is it? :
- life: life ,( Something ) The lifetime of
- cycle: cycle
Lifecycle What to do :
lifecycle What are the advantages ?
- Lifecycler It realizes the separation of execution logic and activities , Code decouples and increases the readability of the code
- Lifecycler Remove the listener at the end of the activity , Avoid the problem of declaration cycle
How to use Lifecycle Well ?
- Lifecycle
- Lifecycle Is an abstract class , The implementation subclass is LifecycleRegistry
class LifecycleRegistry extends Lifecycle{
.......
}
- lifecycleRegister
- lifecycle The only subclass of , Subscription callback logic used to trigger its own state and related observers when the life cycle changes
- LifecycleOwner
- Used to connect objects with a lifecycle
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
- LifecycleObserver
- Lifecycle The observer
- State(Lifecycle Inside the abstract class of )
- Indicates the current lifecycle state
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
- Event(Lifecycle Inside the abstract class of )
- The current life cycle changes the corresponding events
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
......
}
Lifecycle Use :
- gradle References to
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"
}
> Here we can find that we have imported lifecycle-service,lifecycle-process These two components , because , In the new edition of SDK in ,Activity/Fragment It has been implemented by default LifecycleOwner Interface , in the light of Service,Android Provided separately LifeCycleService, Not like it Activity、Fragment By default LifeCycleOwner. in the light of Application,Android Provides ProcessLifeCycleOwner For listening to the entire application lifecycle .
LifecycleObserver
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
//OnLifecycleEvent It's out of date
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())
}
}

- Use
DefaultLifecycleObserver
DefaultLifecycleObserver
@OnLifecycleEvent
MyDefaultLifecycleObserver Inherited from DefaultLifecycleObserver
import 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: ")
}
}
MyApplication
addObserver()
Observer
LifecycleRegistry
import android.app.Application
import androidx.lifecycle.ProcessLifecycleOwner
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(MyDefaultLifecycleObserver())
}
}


Several examples Lifecycle Usage scenarios of :
- Retrofit coordination Lifecycle management Http Life cycle
- Reading is recommended here :https://mp.weixin.qq.com/s/omCnmMX3XVq-vnKoDnQXTg
- Pause and resume animation
- Pause and play of video
- Handler Remove messages from
- ........
Here are a few questions :
- Lifecycle There are several ways to create ( What's the difference , Which one is recommended )?
- Lifecycle How to synchronize the lifecycle ?
- Event Events and State What is the relationship between the State ?
- Lifecycle Registration of , distributed , What is the process of perception ?
- What is a nested event ? When did it happen ?Lifecycle How to solve it ?
边栏推荐
- 7. Icons
- 佩服,阿里女程序卧底 500 多个黑产群……
- Listen in the network
- Station B was scolded on the hot search..
- 开源实习经验分享:openEuler软件包加固测试
- Analysis report on the development trend and Prospect of new ceramic materials in the world and China Ⓐ 2022 ~ 2027
- How much money do novices prepare to play futures? Is agricultural products OK?
- [安网杯 2021] REV WP
- 二传感器尺寸「建议收藏」
- 5. Use of ly tab plug-in of header component
猜你喜欢
焱融看 | 混合云时代下,如何制定多云策略
spark源码(五)DAGScheduler TaskScheduler如何配合提交任务,application、job、stage、taskset、task对应关系是什么?
Interpretation of R & D effectiveness measurement framework
奔涌而来的数字化浪潮,将怎样颠覆未来?
A new book by teacher Zhang Yujin of Tsinghua University: 2D vision system and image technology (five copies will be sent at the end of the article)
What is the future development direction of people with ordinary education, appearance and family background? The career planning after 00 has been made clear
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
minimum spanning tree
Computer network interview knowledge points
Self cultivation of open source programmers who contributed tens of millions of lines of code to shardingsphere and later became CEO
随机推荐
关于佛萨奇2.0“Meta Force原力元宇宙系统开发逻辑方案(详情)
二传感器尺寸「建议收藏」
分布式事务简介(seata)
LeetCode重建二叉树详解[通俗易懂]
Computer network interview knowledge points
用栈实现队列、用队列实现栈(C语言_leetcode_232+225)
2.15 summary
Applet - multiple text line breaks in view
“国防七子”经费暴增,清华足足362亿元,甩第二名101亿 |全国高校2022预算大公开...
1. Sum of two numbers: given an integer array num and an integer target value, please find the two integers whose sum is the target value target in the array and return their array subscripts
进入前六!博云在中国云管理软件市场销量排行持续上升
Introduction to distributed transactions (Seata)
【241. 为运算表达式设计优先级】
Etcd summary mechanism and usage scenarios
小程序- view中多个text换行
SAP 智能机器人流程自动化(iRPA)解决方案分享
2022年PMP项目管理考试敏捷知识点(6)
QT community management system
String input function
ArrayList capacity expansion mechanism and thread safety