Android--Jetpack--Lifecycle详解

富贵本无根,尽从勤里得

一,定义

Lifecycle 是一个具备宿主生命周期感知能力的组件。它持有组件(Activity/Fragment)生命周期状态信息,并且允许其观察者监听宿主生命周期状态变化。

顾名思义,Lifecycle的主要作用其实就是帮助我们监听Activity或者Fragment的生命周期,不需要我们自己去定义回调接口来监听了,这样就使我们的代码更加简洁,逻辑更加清晰。

二,角色介绍

1,Lifecycle(生命周期) :一个核心抽象类,用于存储有关组件(如 activity/fragment )的生命周期状态的信息,并允许其他对象观察此状态。继承该类的子类,表示本身是一个 具有Android生命周期特性的对象。

2,LifecycleOwner:核心接口,Lifecycle 持有者,该接口的实现类表示能够为外部提供Lifecycle实例。具有 Android 生命周期的类。这些事件可以被自定义组件用来处理生命周期的变化,而不需要在 Activity/Fragment 中实现任何代码。

3,LifecycleRegistry:核心类,Lifecycle 的实现类,可以处理多个观察者。实现 Lifecycle 定义生命周期观察订阅,生命周期查询的方法。还实现了架构中,生命周期变化时触发的自身状态处理和相关对观察者的订阅回调的逻辑。

4,LifecycleObserver:观察者,将一个类标记为生命周期观察者。实现该接口的类,通过注解的方式,可以通过被 LifecycleOwner 类的 addObserver() 方法注册,LifecycleObserver 便可以观察到 LifecycleOwner 的生命周期事件。

5,State :当前生命周期所处的状态。

6,Event :当前生命周期改变对应的事件。从框架和 Lifecycle 类分派的生命周期事件。这些事件对应到 activity/fragment 中的回调事件。

三,基本使用

第一张使用方式非常简单:

1,添加依赖:

implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.5.1"
implementation "androidx.lifecycle:lifecycle-common:2.5.1"

2,自定义一个类,这个类就是观察者,实现上面我们提到的LifecycleObserver 接口

定义方法,实现需要监控的生命周期,最主要的是注解

 @OnLifecycleEvent

以及上面提到的生命周期所处的状态:

public class YuanZhenLifecycleObserver implements LifecycleObserver {@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)void onCreate(){System.out.println("yz-----onCreate");}@OnLifecycleEvent(Lifecycle.Event.ON_START)void onStart(){System.out.println("yz-----onStart");}@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)void onResume(){System.out.println("yz-----onResume");}@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)void onPause(){System.out.println("yz-----onPause");}@OnLifecycleEvent(Lifecycle.Event.ON_STOP)void onStop(){System.out.println("yz-----onStop");}@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)void onDestory(){System.out.println("yz-----onDestory");}}

 3,在需要被观察的宿主中,注册刚刚我们创建的观察者:

public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);getLifecycle().addObserver(new YuanZhenLifecycleObserver());View viewById = findViewById(R.id.txt);viewById.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent =new Intent(MainActivity.this,SecondActivity.class);startActivity(intent);finish();}});}}

SecondActivity代码如下:

public class SecondActivity extends AppCompatActivity {@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_second);}
}

最后,运行后点击按钮,输出如下日志:

 至此,MainActivity的生命周期,就被我们轻松的观察到了。

第二种实现方式:

上一种实现方式方法已经过时了,所以我们推荐这种实现方式,直接实现接口DefaultLifecycleObserver 

然后我们重写它的生命周期方法即可:

public class YuanZhenFullObserver implements DefaultLifecycleObserver {@Overridepublic void onCreate(@NonNull LifecycleOwner owner) {DefaultLifecycleObserver.super.onCreate(owner);System.out.println("yz-----onCreate");}@Overridepublic void onStart(@NonNull LifecycleOwner owner) {DefaultLifecycleObserver.super.onStart(owner);System.out.println("yz-----onStart");}@Overridepublic void onResume(@NonNull LifecycleOwner owner) {DefaultLifecycleObserver.super.onResume(owner);System.out.println("yz-----onResume");}@Overridepublic void onPause(@NonNull LifecycleOwner owner) {DefaultLifecycleObserver.super.onPause(owner);System.out.println("yz-----onPause");}@Overridepublic void onStop(@NonNull LifecycleOwner owner) {DefaultLifecycleObserver.super.onStop(owner);System.out.println("yz-----onStop");}@Overridepublic void onDestroy(@NonNull LifecycleOwner owner) {DefaultLifecycleObserver.super.onDestroy(owner);System.out.println("yz-----onDestroy");}
}

然后再MainActivity使用:

public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);getLifecycle().addObserver(new YuanZhenFullObserver());View viewById = findViewById(R.id.txt);viewById.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Intent intent =new Intent(MainActivity.this,SecondActivity.class);startActivity(intent);finish();}});}}

运行后输出:

使用方式都非常的简单高效。

四,基本原理

从上面的使用中我们就可以看出,lifecycle显然是使用了观察者模式,如果对于观察者模式不清楚的,建议看下文章Android设计模式--观察者模式-CSDN博客

 我们看源码,只能是先从使用入手:

getLifecycle().addObserver(new YuanZhenFullObserver());

通过addObserver方法,我们找到了Lifecycle这个抽象类:

public abstract class Lifecycle {//使用的入口@MainThreadpublic abstract void addObserver(@NonNull LifecycleObserver observer);@MainThreadpublic abstract void removeObserver(@NonNull LifecycleObserver observer);。。。。}

它的实现类LifecycleRegistry 中addObserver方法:

@Override
public void addObserver(@NonNull LifecycleObserver observer) {enforceMainThreadIfNeeded("addObserver");//判断当前的生命周期,将当前生命周期保存State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;//将YuanZhenLifecycleObserver这个观察者对象保存起来ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);if (previous != null) {return;}//获取到当前的被观察者 也就是MainActivityLifecycleOwner lifecycleOwner = mLifecycleOwner.get();if (lifecycleOwner == null) {// it is null we should be destroyed. Fallback quicklyreturn;}boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;//计算当前生命周期State targetState = calculateTargetState(observer);mAddingObserverCounter++;while ((statefulObserver.mState.compareTo(targetState) < 0&& mObserverMap.contains(observer))) {pushParentState(statefulObserver.mState);final Event event = Event.upFrom(statefulObserver.mState);if (event == null) {throw new IllegalStateException("no event up from " + statefulObserver.mState);}statefulObserver.dispatchEvent(lifecycleOwner, event);popParentState();// mState / subling may have been changed recalculatetargetState = calculateTargetState(observer);}if (!isReentrance) {// we do sync only on the top level.sync();}mAddingObserverCounter--;
}

上面的 LifecycleOwner lifecycleOwner = mLifecycleOwner.get();是怎么来的呢?

再MainActivity中使用getLifecycle()方法,就进入到了它的父类ComponentActivity:

public class ComponentActivity extends androidx.core.app.ComponentActivity implementsContextAware,LifecycleOwner,ViewModelStoreOwner,HasDefaultViewModelProviderFactory,SavedStateRegistryOwner,OnBackPressedDispatcherOwner,ActivityResultRegistryOwner,ActivityResultCaller {//创建LifecycleRegistry 实例private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);//获取到创建的LifecycleRegistry 实例@NonNull@Overridepublic Lifecycle getLifecycle() {return mLifecycleRegistry;}@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {// Restore the Saved State first so that it is available to// OnContextAvailableListener instancesmSavedStateRegistryController.performRestore(savedInstanceState);mContextAwareHelper.dispatchOnContextAvailable(this);super.onCreate(savedInstanceState);//创建一个透明的fragmentReportFragment.injectIfNeededIn(this);if (mContentLayoutId != 0) {setContentView(mContentLayoutId);}}。。。。}

ComponentActivity实现了LifeCyclerOwern接口,在ComponentActivity这个类中,创建了LifecycleRegistry,并将它本省传递给了LifecycleRegistry。

在这个类的onCreate方法中,有一个非常重要的方法,ReportFragment.injectIfNeededIn(this);它创建了一个透明的fragment。我们看看这个fragment里面干了什么。

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends android.app.Fragment {private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"+ ".LifecycleDispatcher.report_fragment_tag";public static void injectIfNeededIn(Activity activity) {if (Build.VERSION.SDK_INT >= 29) {//注册回调LifecycleCallbacks.registerIn(activity);}//绑定fragmentandroid.app.FragmentManager manager = activity.getFragmentManager();if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();manager.executePendingTransactions();}}@SuppressWarnings("deprecation")static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {if (activity instanceof LifecycleRegistryOwner) {//如果activity实现了LifecycleOwner接口 调用handleLifecycleEvent((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);return;}if (activity instanceof LifecycleOwner) {Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();if (lifecycle instanceof LifecycleRegistry) {((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);}}}static ReportFragment get(Activity activity) {return (ReportFragment) activity.getFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG);}private ActivityInitializationListener mProcessListener;private void dispatchCreate(ActivityInitializationListener listener) {if (listener != null) {listener.onCreate();}}private void dispatchStart(ActivityInitializationListener listener) {if (listener != null) {listener.onStart();}}private void dispatchResume(ActivityInitializationListener listener) {if (listener != null) {listener.onResume();}}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);dispatchCreate(mProcessListener);dispatch(Lifecycle.Event.ON_CREATE);}@Overridepublic void onStart() {super.onStart();dispatchStart(mProcessListener);dispatch(Lifecycle.Event.ON_START);}@Overridepublic void onResume() {super.onResume();dispatchResume(mProcessListener);dispatch(Lifecycle.Event.ON_RESUME);}@Overridepublic void onPause() {super.onPause();dispatch(Lifecycle.Event.ON_PAUSE);}@Overridepublic void onStop() {super.onStop();dispatch(Lifecycle.Event.ON_STOP);}@Overridepublic void onDestroy() {super.onDestroy();dispatch(Lifecycle.Event.ON_DESTROY);// just want to be sure that we won't leak reference to an activitymProcessListener = null;}private void dispatch(@NonNull Lifecycle.Event event) {if (Build.VERSION.SDK_INT < 29) {// Only dispatch events from ReportFragment on API levels prior// to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks// added in ReportFragment.injectIfNeededIndispatch(getActivity(), event);}}void setProcessListener(ActivityInitializationListener processListener) {mProcessListener = processListener;}interface ActivityInitializationListener {void onCreate();void onStart();void onResume();}// this class isn't inlined only because we need to add a proguard rule for it (b/142778206)// In addition to that registerIn method allows to avoid class verification failure,// because registerActivityLifecycleCallbacks is available only since api 29.@RequiresApi(29)static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {static void registerIn(Activity activity) {activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());}@Overridepublic void onActivityCreated(@NonNull Activity activity,@Nullable Bundle bundle) {}@Overridepublic void onActivityPostCreated(@NonNull Activity activity,@Nullable Bundle savedInstanceState) {dispatch(activity, Lifecycle.Event.ON_CREATE);}@Overridepublic void onActivityStarted(@NonNull Activity activity) {}@Overridepublic void onActivityPostStarted(@NonNull Activity activity) {dispatch(activity, Lifecycle.Event.ON_START);}@Overridepublic void onActivityResumed(@NonNull Activity activity) {}@Overridepublic void onActivityPostResumed(@NonNull Activity activity) {dispatch(activity, Lifecycle.Event.ON_RESUME);}@Overridepublic void onActivityPrePaused(@NonNull Activity activity) {dispatch(activity, Lifecycle.Event.ON_PAUSE);}@Overridepublic void onActivityPaused(@NonNull Activity activity) {}@Overridepublic void onActivityPreStopped(@NonNull Activity activity) {dispatch(activity, Lifecycle.Event.ON_STOP);}@Overridepublic void onActivityStopped(@NonNull Activity activity) {}@Overridepublic void onActivitySaveInstanceState(@NonNull Activity activity,@NonNull Bundle bundle) {}@Overridepublic void onActivityPreDestroyed(@NonNull Activity activity) {dispatch(activity, Lifecycle.Event.ON_DESTROY);}@Overridepublic void onActivityDestroyed(@NonNull Activity activity) {}}
}

从这个fragment中我们可以看出,ReportFragment的生命周期函数都调用了dispatch()方法,而dispatch()方法则会判断Activity是否实现了LifecycleOwner接口,如果实现了该接口就调用LifecycleRegister的handleLifecycleEvent()。再来看看handleLifecycleEvent:

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {enforceMainThreadIfNeeded("handleLifecycleEvent");moveToState(event.getTargetState());
}
private void moveToState(State next) {if (mState == next) {return;}if (mState == INITIALIZED && next == DESTROYED) {throw new IllegalStateException("no event down from " + mState);}mState = next;if (mHandlingEvent || mAddingObserverCounter != 0) {mNewEventOccurred = true;// we will figure out what to do on upper level.return;}mHandlingEvent = true;sync();mHandlingEvent = false;if (mState == DESTROYED) {mObserverMap = new FastSafeIterableMap<>();}
}private void sync() {LifecycleOwner lifecycleOwner = mLifecycleOwner.get();if (lifecycleOwner == null) {throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"+ "garbage collected. It is too late to change lifecycle state.");}while (!isSynced()) {mNewEventOccurred = false;// no need to check eldest for nullability, because isSynced does it for us.if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {backwardPass(lifecycleOwner);}Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();if (!mNewEventOccurred && newest != null&& mState.compareTo(newest.getValue().mState) > 0) {forwardPass(lifecycleOwner);}}mNewEventOccurred = false;
}

事件发生的时候,先得到当前activity应该出现的下一个状态,

moveToState(next); mState = next;更新现在的状态

sync();

backwardPass(lifecycleOwner);逆推

forwardPass(lifecycleOwner);正推

看看这两个方法:

private void forwardPass(LifecycleOwner lifecycleOwner) {Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =mObserverMap.iteratorWithAdditions();while (ascendingIterator.hasNext() && !mNewEventOccurred) {Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();ObserverWithState observer = entry.getValue();while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred&& mObserverMap.contains(entry.getKey()))) {pushParentState(observer.mState);final Event event = Event.upFrom(observer.mState);if (event == null) {throw new IllegalStateException("no event up from " + observer.mState);}observer.dispatchEvent(lifecycleOwner, event);popParentState();}}
}
private void backwardPass(LifecycleOwner lifecycleOwner) {Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =mObserverMap.descendingIterator();while (descendingIterator.hasNext() && !mNewEventOccurred) {Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();ObserverWithState observer = entry.getValue();while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred&& mObserverMap.contains(entry.getKey()))) {Event event = Event.downFrom(observer.mState);if (event == null) {throw new IllegalStateException("no event down from " + observer.mState);}pushParentState(event.getTargetState());observer.dispatchEvent(lifecycleOwner, event);popParentState();}}
}

大致原理请看下图:

然后就调用 observer.dispatchEvent(lifecycleOwner, event); 生成观察者适配器:

static class ObserverWithState {State mState;LifecycleEventObserver mLifecycleObserver;ObserverWithState(LifecycleObserver observer, State initialState) {//创建观察者adapter 并将观察者传入adapter mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);mState = initialState;}void dispatchEvent(LifecycleOwner owner, Event event) {State newState = event.getTargetState();mState = min(mState, newState);mLifecycleObserver.onStateChanged(owner, event);mState = newState;}
}

mLifecycleObserver.onStateChanged(owner, event);将状态的变化通知给了观察者,来看看具体实现:

class FullLifecycleObserverAdapter implements LifecycleEventObserver {private final FullLifecycleObserver mFullLifecycleObserver;private final LifecycleEventObserver mLifecycleEventObserver;FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,LifecycleEventObserver lifecycleEventObserver) {mFullLifecycleObserver = fullLifecycleObserver;mLifecycleEventObserver = lifecycleEventObserver;}@Overridepublic void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {switch (event) {case ON_CREATE:mFullLifecycleObserver.onCreate(source);break;case ON_START:mFullLifecycleObserver.onStart(source);break;case ON_RESUME:mFullLifecycleObserver.onResume(source);break;case ON_PAUSE:mFullLifecycleObserver.onPause(source);break;case ON_STOP:mFullLifecycleObserver.onStop(source);break;case ON_DESTROY:mFullLifecycleObserver.onDestroy(source);break;case ON_ANY:throw new IllegalArgumentException("ON_ANY must not been send by anybody");}if (mLifecycleEventObserver != null) {mLifecycleEventObserver.onStateChanged(source, event);}}
}

FullLifecycleObserverAdapter 在创建时,会持有LifecycleOwner ,当调用onStateChanged时,会调用具体观察者LifecycleOwner 的具体生命周期方法。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/238222.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SRE-架构框架-可靠性

Google-架构框架-可靠性 可靠性概览 Google Cloud 架构框架中的此类别介绍如何在云平台上构建和运营可靠的服务。此外&#xff0c;您还将了解一些支持可靠性的 Google Cloud 产品和功能。 该架构框架介绍了最佳实践&#xff0c;提供了实现建议&#xff0c;并说明了一些可用的…

UPDF 已集成 ChatGPT,AI 赋能注入新动能!

ChatGPT 掀起全球AI热潮,引发了世界范围内对AIGC未来会如何重塑各行各业的讨论与畅想。近日,由赛博爱思(上海)软件科技有限公司独立自主研发的国产 PDF 软件 UPDF完成版本更新,正式上线 AI 功能。据悉,UPDF AI完美集成了ChatGPT 的技术,可帮助用户智能阅读、总结、翻译、问答PD…

百度文心一言AI大模型,解读徐礼昭提出的“三体零售”模型

徐礼昭提出的“三体零售”模型是一种创新的零售理论模型&#xff0c;该模型将零售基础物质、零售商业能量和零售数字化系统视为一个相互作用的复杂有机体。这一理论模型为零售行业的发展提供了全新的视角和更高维度的认知。 首先&#xff0c;零售基础物质是零售行业的基石&…

目标检测——Fast R-CNN算法解读

论文&#xff1a;Fast R-CNN 作者&#xff1a;Ross Girshick 链接&#xff1a;https://arxiv.org/abs/1504.08083 代码&#xff1a;https://github.com/rbgirshick/fast-rcnn 目录 1、算法概述2、Fast R-CNN细节2.1The RoI pooling layer2.2 Fine-tuning for detection2.3 Fast…

2024 年综合网络安全审计清单

在网络威胁不断演变的时代&#xff0c;确保组织数据和系统的安全至关重要。 全面的网络安全审核清单可以在实现这一目标方面发挥关键作用。但是&#xff0c;什么才是有效的网络安全审核清单呢&#xff1f;以及如何对其进行定制以满足您组织的独特需求&#xff1f; 了解网络安…

cpu版本的torch可以用清华镜像源安装

一、来到pytroch官网找到如下代码 官方提供的默认的安装cpu版本的torch的命令 pip3 install torch torchvision torchaudio二、使用清华镜像安装 pip3 install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple

python高级练习题库实验1(B)部分

文章目录 题目1代码实验结果题目2代码实验结果题目3代码实验结果题目4代码实验结果题目5代码实验结果题目总结题目1 打包糖果小游戏,用户输入糖果品牌与个数,还有一个盒子里面可以装多少个糖果,输出一些打印信息,如下图所示: 代码 print("Packaging lollies into…

Java实现socket编程案例

以下是一个基本的Java socket编程案例&#xff1a; 服务端代码&#xff1a; import java.net.*; import java.io.*;public class Server {public static void main(String[] args) throws IOException {ServerSocket serverSocket null;try {serverSocket new ServerSocket…

C/C++ 内存管理(1)

文章目录 C/C 内存划分静态和动态内存C语言的动态内存分配函数mallocfreecallocrealloc 常见内存使用错误 C/C 内存划分 栈区&#xff08;stack&#xff09;&#xff1a;在执行函数时&#xff0c;函数内局部变量的存储单元都可以在栈上创建&#xff0c;函数执行结 束时这些存储…

Windows环境 dockertopdesk 部署gitlab

1.在dockertopdesk里搜索 gitlab镜像 (pull)拉取镜像 2.运行镜像到容器 mkdir gitlab gitlab/etc gitlab/log gitlab/opt docker run -id -p 3000:80 -p 9922:22 -v /root/gitlab/etc:/etc/gitlab -v /root/gitlab/log:/var/log/gitlab -v /root/gitlab/opt:/var/opt/gitla…

R语言实验三

1、读取一个文件并进行如下操作。 ①使用命令清空工作空间&#xff0c;使用read.table读取exam_1.txt文件&#xff0c;将文件保存到data变量中&#xff0c;数据第一行设置为列名&#xff0c;第一列是行名。 ②判断对象data是否为矩阵。 ③将对象转换为矩阵&#xff0c;记为d…

canvas基础:渲染文本

canvas实例应用100 专栏提供canvas的基础知识&#xff0c;高级动画&#xff0c;相关应用扩展等信息。 canvas作为html的一部分&#xff0c;是图像图标地图可视化的一个重要的基础&#xff0c;学好了canvas&#xff0c;在其他的一些应用上将会起到非常重要的帮助。 文章目录 示例…