current position:Home>Android Jetpack component Lifecycle

Android Jetpack component Lifecycle

2023-01-25 11:30:48Someone from Yungu Li

Lifecycle是什么

Lifecycle 是一个类,用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态.
Lifecycle概述https://developer.android.google.cn/topic/libraries/architecture/lifecycle

Lifecycle使用

public class MainActivity extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getLifecycle().addObserver(new LifecycleEventObserver() {
    
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
    
                Log.e("tag", "【onStateChanged】: " + event.name());
            }
        });
    }
}

运行如下:
在这里插入图片描述

Lifecycle原理

uml图总结:
在这里插入图片描述
This is not from a code point of view,直接画出addObserverExecution logic flow chart

LifecycleRegistry.addObserver
ObserverWithState.dispatchEvent
LifecycleEventObserver.onStateChanged
LifecycleRegistry.sync
LifecycleRegistry.backwardPass
LifecycleRegistry.forwardPass

The execution logic of each statement cycle:

MainActivity.onCreate
LifecycleRegistry.handleLifecycleEvent
LifecycleRegistry.moveToState
LifecycleRegistry.sync
LifecycleRegistry.backwardPass
LifecycleRegistry.forwardPass
ObserverWithState.dispatchEvent
LifecycleEventObserver.onStateChanged
MainActivity.onStart
MainActivity.onResume
MainActivity.onPause
MainActivity.onStop
MainActivity.onDestroy

copyright notice
author[Someone from Yungu Li],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2023/025/202301251120395729.html

Random recommended