当前位置:网站首页>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@OnLifecycleEventMyDefaultLifecycleObserver Inherited from 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())
}
}


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 ?
边栏推荐
- 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
- Go整合Logrus实现日志打印
- [安网杯 2021] REV WP
- 陈宇(Aqua)-安全->云安全->多云安全
- Summary of 20 practical typescript single line codes
- Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its
- Fiori 应用通过 Adaptation Project 的增强方式分享
- 算网融合赋能行业转型,移动云点亮数智未来新路标
- Animesr: learnable degradation operator and new real world animation VSR dataset
- 【剑指 Offer】55 - II. 平衡二叉树
猜你喜欢

MySQL六十六问,两万字+五十图详解!复习必备

玩转gRPC—不同编程语言间通信

Self cultivation of open source programmers who contributed tens of millions of lines of code to shardingsphere and later became CEO

Terminal identification technology and management technology

spark源码(五)DAGScheduler TaskScheduler如何配合提交任务,application、job、stage、taskset、task对应关系是什么?
![[flask] flask starts and implements a minimal application based on flask](/img/45/77df241c85c4916914a37bb78275a5.png)
[flask] flask starts and implements a minimal application based on flask

Introduction to distributed transactions (Seata)

What is the future development direction of people with ordinary education, appearance and family background? The career planning after 00 has been made clear

Learning to use livedata and ViewModel will make it easier for you to write business

分布式事务简介(seata)
随机推荐
Liu Dui (fire line safety) - risk discovery in cloudy environment
6. Wiper part
Sign APK with command line
LeetCode重建二叉树详解[通俗易懂]
C语言订餐管理系统
[Jianzhi offer] 54 The k-th node of binary search tree
开源实习经验分享:openEuler软件包加固测试
佩服,阿里女程序卧底 500 多个黑产群……
[Jianzhi offer] 55 - ii balanced binary tree
QT learning management system
Etcd 概要 机制 和使用场景
一文读懂TDengine的窗口查询功能
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
Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"
[sword finger offer] 55 - I. depth of binary tree
Arthas use
9. Use of better scroll and ref
leetcode 322. Coin Change 零钱兑换(中等)
leetcode622.设计循环队列(C语言)
[241. Design priority for operation expression]