網(wǎng)站首頁 編程語言 正文
提綱
1,什么是Lifecycle?
2,如何使用Lifecycle?
3,LifecycleOwner,Lifecycle,LifecycleObserver之間是什么關(guān)系?
3,Activity是如何實(shí)現(xiàn)Lifecycle的?
4,F(xiàn)ragment是如何實(shí)現(xiàn)Lifecycle的?
5,Lifecycle是如何下發(fā)宿主生命周期給觀察者的?
什么是Lifecycle
Lifecycle是Jetpack組件庫(kù)中的架構(gòu)組件,顧名思義就是一個(gè)生命周期組件,它可感知宿主的生命周期,并根據(jù)生命周期反推出生命周期所屬的狀態(tài)下發(fā)給觀察者。
如何使用Lifecycle
1,實(shí)現(xiàn)其生命周期回調(diào)接口,成為生命周期觀察者
2,在Activity/Fragment中獲取Lifecycle實(shí)例并添加觀察者
3,實(shí)例代碼如下,個(gè)人比較推薦第一種方式,第二種方式比較繁瑣,需要在方法上通過注解來表明想要觀察的生命周期事件
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
//訂閱生命周期
lifecycle.addObserver(MyLifecycleEventObserver())
lifecycle.addObserver(MyLifecycleObserver())
}
/**
* 方式一(個(gè)人比較推薦)
*/
class MyLifecycleEventObserver : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
when (event) {
Lifecycle.Event.ON_CREATE -> println("onCreate")
Lifecycle.Event.ON_START -> println("onStart")
Lifecycle.Event.ON_RESUME -> println("onResume")
Lifecycle.Event.ON_PAUSE -> println("onPause")
Lifecycle.Event.ON_STOP -> println("onStop")
Lifecycle.Event.ON_DESTROY -> println("onDestroy")
}
}
}
/**
* 方式二
*/
class MyLifecycleObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(event: Lifecycle.Event) {
println("onCreate")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart(event: Lifecycle.Event) {
println("onStart")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume(event: Lifecycle.Event) {
println("onResume")
}
}
}
關(guān)系梳理
LifecycleOwner,Lifecycle,LifecycleObserver之間是什么關(guān)系?
1,LifecycleOwner:生命周期持有者,我們的Activity/Fragment都實(shí)現(xiàn)了這個(gè)接口并重寫了它的抽象方法getLicycle()返回一個(gè)Licycle實(shí)例。
2,Lifecycle:LifecycleRegsitry是它的唯一實(shí)現(xiàn)類,主要用來負(fù)責(zé)注冊(cè)觀察者,下發(fā)宿主狀態(tài)給觀察者
3,LicycleObserver:是一個(gè)接口,主要用來接收宿主的生命周期狀態(tài),實(shí)現(xiàn)該接口即可成為一個(gè)生命周期觀察者
4,他們之間的持有關(guān)系如下圖:
Activity是如何實(shí)現(xiàn)Lifecycle的
CompatActivity
如果我們的Activity是繼承自CompatActivity,那么CompatActivity需要在Activity上添加一個(gè)ReportFragment來實(shí)現(xiàn)生命周期下發(fā)
(1)在CompatActivity中創(chuàng)建LifecycleRegistry類型的成員變量mLifecycleRegistry
(2)在CompatActivity的onCreate()方法中往Activity中添加一個(gè)ReportFragment來下發(fā)命周期
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
//創(chuàng)建Lifecycle實(shí)例
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
//往Activity添加一個(gè)ReportFragment來達(dá)到下發(fā)生命周期的目的
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
}
(3) 將Fragment與Activity進(jìn)行綁定,添加到Activity中,用于感知Activity生命周期變化
(4)當(dāng)Activity生命周期發(fā)生變化,對(duì)應(yīng)的生命周期回調(diào)方法被調(diào)用,下發(fā)生命周期給觀察者
public class ReportFragment extends Fragment {
public static void injectIfNeededIn(Activity activity) {
//往Activity中存放一個(gè)ReportFragment
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
// just want to be sure that we won't leak reference to an activity
mProcessListener = null;
}
/**
* 下發(fā)生命周期事件
*/
private void dispatch(Lifecycle.Event event) {
//獲取Activity的Lifecycle實(shí)例,下發(fā)生命周期事件
Activity activity = getActivity();
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
}
AppCompatActivity
如果我們的Activity是繼承自AppCompatActivity ,不需要往Activity中添加一個(gè)ReportFragment來感知生命周期并下發(fā)生命周期事件,AppCompatActivity 繼承自FragmentActivity,下發(fā)生命周期事件都在FragmentActivity的生命周期回調(diào)方法中進(jìn)行
(1)創(chuàng)建LifecycleRegistry類型的變量mFragmentLifecycleRegistry
(2)在其生命周期回調(diào)方法中調(diào)用mFragmentLifecycleRegistry的handlerLifecycleEvent()方法進(jìn)行下發(fā)生命周期事件
public class FragmentActivity extends ComponentActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
ActivityCompat.RequestPermissionsRequestCodeValidator {
//創(chuàng)建Lifecycle實(shí)例
final LifecycleRegistry mFragmentLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
//下發(fā)生命周期事件
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
mFragments.dispatchDestroy();
//下發(fā)生命周期事件
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
}
@Override
protected void onPause() {
super.onPause();
mResumed = false;
mFragments.dispatchPause();
//下發(fā)生命周期事件
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
protected void onResumeFragments() {
//下發(fā)生命周期事件
mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mFragments.dispatchResume();
}
}
Fragment是如何實(shí)現(xiàn)Lifecycle的
其實(shí)Fragment實(shí)現(xiàn)Lifecycle,下發(fā)其生命周期的操作跟AppCompatActivity 是一樣的套路,在其生命周期回調(diào)方法中進(jìn)行生命周期事件下發(fā)
(1)創(chuàng)建Fragment時(shí)調(diào)用initLifecycle()方法給LifecycleRegistry類型的mLifecycleRegistry變量賦值
(2)在其生命周期回調(diào)方法中調(diào)用mLifecycleRegistry的handlerLifecycleEvent()方法下發(fā)生命周期事件給觀察者
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner, SavedStateRegistryOwner {
LifecycleRegistry mLifecycleRegistry;
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
//創(chuàng)建Lifecycle實(shí)例
mLifecycleRegistry = new LifecycleRegistry(this);
}
void performCreate(Bundle savedInstanceState) {
onCreate(savedInstanceState);
//下發(fā)生命周期事件給觀察者
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
void performStart() {
onStart();
//下發(fā)生命周期事件給觀察者
mChildFragmentManager.dispatchStart();
}
void performResume() {
onResume();
//下發(fā)生命周期事件給觀察者
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
}
Lifecycle是如何下發(fā)宿主生命周期給觀察者的
(1)在我們調(diào)用Lifecycle的addObserver()方法時(shí)就已經(jīng)開始下發(fā)生命周期事件了,接下來讓我們先從addObserver()這個(gè)入口看看其實(shí)現(xiàn)邏輯,大致邏輯如下
public class LifecycleRegistry extends Lifecycle {
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//首次添加觀察者,如果宿主狀態(tài)不是DESTROYED,那么觀察者初始狀態(tài)都是INITIALIZED
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//把傳進(jìn)去的生命周期觀察者以及初始狀態(tài)包裝成ObserverWithState對(duì)象
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//把包裝好的ObserverWithState對(duì)象存放到觀察者集合中,如果此前已經(jīng)添加過則會(huì)返回此前添加的值,否則返回null
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//判斷此前是否添加過,如果添加過則直接結(jié)束方法
if (previous != null) {
return;
}
//獲取宿主實(shí)例
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
//計(jì)算觀察者的目標(biāo)狀態(tài)
State targetState = calculateTargetState(observer);
//循環(huán)比對(duì)觀察者的狀態(tài)和宿主的狀態(tài),如果沒有對(duì)齊則下發(fā)對(duì)應(yīng)的生命周期事件
//拿觀察者的狀態(tài)和宿主的狀態(tài)做比較 如果小于0代表狀態(tài)還沒有對(duì)齊,需要繼續(xù)下發(fā)生命周期狀態(tài)給觀察者
//假設(shè)是在Activity的onResume()方法中注冊(cè)的觀察者,那么就需要給觀察者下發(fā)onCreate,onStart,onResume這些事件
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
}
}
(2)分析完addObserver()做了哪些事,那么我們?cè)賮矸治鱿耯andlerLifecycleEvent()方法做了什么事
public class LifecycleRegistry extends Lifecycle {
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
//根據(jù)生命周期事件推算出其狀態(tài)
State next = getStateAfter(event);
//移動(dòng)到新狀態(tài)
moveToState(next);
}
private void moveToState(State next) {
//如果當(dāng)前狀態(tài)和新狀態(tài)相等 結(jié)束方法
if (mState == next) {
return;
}
//記錄新狀態(tài)
mState = next;
//如果當(dāng)前正在下發(fā)生命周期事件 或 當(dāng)前正在添加觀察者 結(jié)束方法
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
return;
}
//同步新狀態(tài)給觀察者
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
private void sync() {
//獲取宿主實(shí)例
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
//停止循環(huán)的條件是已經(jīng)同步狀態(tài)完成 或 沒有觀察者
while (!isSynced()) {
mNewEventOccurred = false;
//獲取觀察者集合中最先添加的那個(gè)元素 拿當(dāng)前狀態(tài)和觀察者狀態(tài)作比較 判斷當(dāng)前是不是向后移動(dòng)狀態(tài) STARTED -> ON_STOP
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
//獲取觀察者集合中最新添加的那個(gè)元素 拿當(dāng)前狀態(tài)和觀察者狀態(tài)作比較 判斷當(dāng)前是不是向前移動(dòng)狀態(tài) STARTED -> ON_RESUME
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
/**
* 向前移動(dòng)狀態(tài)
*/
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
//遍歷所有觀察者
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
//拿觀察者的狀態(tài)和宿主的狀態(tài)做比較 如果小于0代表狀態(tài)還沒有對(duì)齊
//假設(shè)當(dāng)前宿主在RESUMED狀態(tài) 觀察者在CREATED狀態(tài) 則需要下發(fā):ON_START,ON_RESUME生命周期事件 需要循環(huán)兩次
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
//根據(jù)觀察者狀態(tài)反推向前移動(dòng)事件 下發(fā)生命周期事件
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
/**
* 通過觀察者狀態(tài)反推向前移動(dòng)事件
*/
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
/**
* 向后移動(dòng)狀態(tài)
*/
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
//遍歷所有觀察者
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
//拿觀察者的狀態(tài)和宿主的狀態(tài)做比較 如果大于0代表狀態(tài)還沒有對(duì)齊
//假設(shè)當(dāng)前觀察者在RESUMED狀態(tài) 宿主在DESTROYED狀態(tài) 那么需要下發(fā):ON_PAUSE,ON_STOP,ON_DESTROY這些生命周期事件 循環(huán)三次
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
//根據(jù)觀察者狀態(tài)反推出向后移動(dòng)事件
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
//下發(fā)該生命周期事件給觀察者
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
/**
* 通過觀察者狀態(tài)反推向后移動(dòng)的事件
*/
private static Event downEvent(State state) {
switch (state) {
case INITIALIZED:
throw new IllegalArgumentException();
case CREATED:
return ON_DESTROY;
case STARTED:
return ON_STOP;
case RESUMED:
return ON_PAUSE;
case DESTROYED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
}
(3)接下來我們看看ObserverWitchState的dispatchEvent()方法是如何下發(fā)生命周期事件給觀察者的,我們知道在調(diào)用Lifecycle的addObserver()方法時(shí)就把我們傳進(jìn)去的LifecycleObserver封裝成了一個(gè)ObserverWitchState對(duì)象,并存放到生命周期觀察者集合中
static class ObserverWithState {
//記錄當(dāng)前狀態(tài)
State mState;
//生命周期觀察者
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
//下發(fā)生命周期事件給生命周期觀察者
void dispatchEvent(LifecycleOwner owner, Event event) {
//根據(jù)生命周期事件推算出生命周期狀態(tài)
State newState = getStateAfter(event);
mState = min(mState, newState);
//調(diào)用生命周期觀察者的onStateChanged()方法通知生命周期觀察者生命周期發(fā)生變化
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
static State getStateAfter(Event event) {
switch (event) {
case ON_CREATE:
case ON_STOP:
return CREATED;
case ON_START:
case ON_PAUSE:
return STARTED;
case ON_RESUME:
return RESUMED;
case ON_DESTROY:
return DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException("Unexpected event value " + event);
}
(4)到此結(jié)束,希望對(duì)讀者有所幫助
原文鏈接:https://blog.csdn.net/qq_42359647/article/details/125866374
相關(guān)推薦
- 2022-07-19 Docker容器內(nèi)存占用過高解決方法
- 2022-04-04 react安裝報(bào)錯(cuò)ReactDOM.render is no longer supported in
- 2022-11-08 Go讀取文件與寫入文件的三種方法操作指南_Golang
- 2022-06-15 go語言定時(shí)器Timer及Ticker的功能使用示例詳解_Golang
- 2022-07-26 Python基礎(chǔ)之模塊詳解_python
- 2022-07-22 Android 舊項(xiàng)目打包 api-versions.xml Stream closed
- 2022-09-25 Clion配置STM32開發(fā)環(huán)境printf函數(shù)打印浮點(diǎn)數(shù)快速設(shè)置方法
- 2022-07-15 go使用consul實(shí)現(xiàn)服務(wù)發(fā)現(xiàn)及配置共享實(shí)現(xiàn)詳解_Golang
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支