本文已收录到GitHub/Android-Notes中,这儿有 Android 进阶成长常识系统笔记,有志同道合的朋友,关注大众号 [小尘Android专栏] 跟我一同成长。
前言
Jetpack 是一个由多个库组成的套件,可帮助开发者遵循最佳做法,削减样板代码。假如项目采用 MVVM 架构,那么 Jetpack 里边的架构相关的组件便是为MVVM 量身定制的,并且现在面试Jetpack也是必问项,但是许多开发者对Jetpack中的一些中心组件都只停留在会用的阶段,对其原理及源码却是一知半解乃至底子没了解过,因此整理了一个系列来帮助有需要的小伙伴理解Jetpack规划思维和原理。
正文
什么是Lifecycle?Lifecycle处理了开发中的什么问题?
咱们先来一段Lifecycle出现之前的Activity生命周期监听代码:
1、先界说一个接口:
package com.kuer.ke_livedata;
public interface LifecycleInterface {
void onCreate();
void onResume();
void onStart();
void onStop();
void onDestroy();
//...
}
2、界说完成类
package com.kuer.ke_livedata;
import android.util.Log;
public class LifecycleImpl implements LifecycleInterface {
@Override
public void onCreate() {
Log.e("LifecycleImpl------>","onCreate");
}
@Override
public void onResume() {
Log.e("LifecycleImpl------>","onResume");
}
@Override
public void onStart() {
Log.e("LifecycleImpl------>","onStart");
}
@Override
public void onStop() {
Log.e("LifecycleImpl------>","onStop");
}
@Override
public void onDestroy() {
Log.e("LifecycleImpl------>","onDestroy");
}
//...
}
3、生命周期监听(绑定)
package com.kuer.ke_livedata;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
LifecycleImpl lifecycle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lifecycle = new LifecycleImpl();
lifecycle.onCreate();
}
@Override
protected void onResume() {
super.onResume();
lifecycle.onResume();
}
@Override
protected void onStart() {
super.onStart();
lifecycle.onStart();
}
@Override
protected void onDestroy() {
super.onDestroy();
lifecycle.onDestroy();
}
@Override
protected void onStop() {
super.onStop();
lifecycle.onStop();
}
}
从以上代码能够看出,在以前监听Activity的生命周期改动是一件很费事的工作,并且假如逻辑杂乱的话会显得代码特别的臃肿,耦合非常严峻。
咱们再来一段基于Lifecycle的Activity生命周期监听代码:
1、界说一个完成类完成LifecycleOwner接口(GenericLifecycleObserver是LifecycleOwner的子类,由于LifecycleOwner是空的,所以一般都是完成GenericLifecycleObserver)
package com.kuer.ke_livedata;
import android.annotation.SuppressLint;
import android.util.Log;
import androidx.lifecycle.GenericLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
@SuppressLint("RestrictedApi")
public class Feel implements GenericLifecycleObserver {
//每当组件的生命周期产生改动的时分都会进行回调
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
Log.e("Feel----------->",event.name());
}
}
2、将这个接口作为观察者经过Lifecycle与Activity绑定起来
package com.kuer.ke_livedata;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity.this.getLifecycle().addObserver(new Feel());
}
}
简略的代码就能经过Feel目标监听MainActivity的生命周期改动,并且一切的处理逻辑不需要写在MainActivity中。Lifecycle中有多种观察者写法,这儿就不一一例举了。
概念总结: Lifecycle其实便是一个生命周期中转站,当组件的生命周期产生改动时,会告诉该组件所持有的Lifecycle(Lifecycle中采取了观察者形式,能够增加观察者),Lifecycle又会告诉一切的观察者,观察者就能够做出相对应的逻辑处理。在整个进程中,观察者与MainActivity的耦合很低,并且不会给MainActivity形成剩余的负担,达到了一个很好的解耦和瘦身的作用。
Lifecycle源码剖析
以下是Lifecycle的源码:
public abstract class Lifecycle {
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
//比照的办法 比方:State.RESUMED.isAtLeast(State.CREATED),
//比照State.RESUMED的序数值是否大于State.CREATED的序数值(序数值不懂百度)
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
经过源码咱们能够看出,Lifecycle
是一个抽象类,其内部不仅包含了增加和移除观察者的办法,还包含了Event
和State
枚举,这两个枚举中Event
指向组件生命周期对应的事情,这些事情会映射到 Activity
和Fragment
中的事情分发,而State
是用来合作Event
来保存组件的生命周期履行轨道的(这个概念会在下面的状况机中详细讲解)。
既然Lifecycle
是一个抽象类,那么必定会提供有具体的完成,它的完成类便是LifecycleRegistry
,以下是LifecycleRegistry
的源码:
public class LifecycleRegistry extends Lifecycle {
private static final String LOG_TAG = "LifecycleRegistry";
//一切观察者的容器
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
//当时状况
private State mState;
private final WeakReference<LifecycleOwner> mLifecycleOwner;
private int mAddingObserverCounter = 0;
private boolean mHandlingEvent = false;
private boolean mNewEventOccurred = false;
private ArrayList<State> mParentStates = new ArrayList<>();
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
//当LifecycleRegistry目标被创立的好 初始化状况
mState = INITIALIZED;
}
//改动状况的办法1
@SuppressWarnings("WeakerAccess")
@MainThread
public void markState(@NonNull State state) {
moveToState(state);
}
//改动状况的办法2
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
//新状况和当时状况一样就返回
if (mState == next) {
return;
}
//更新当时状况
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
//同步
sync();
mHandlingEvent = false;
}
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
private State calculateTargetState(LifecycleObserver observer) {
Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
State siblingState = previous != null ? previous.getValue().mState : null;
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
: null;
return min(min(mState, siblingState), parentState);
}
//增加观察者的办法
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//将观察者和Lifecycle的状况进行包装,方便观察者回调
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//将包装类放入map容器中
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
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);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
private void popParentState() {
mParentStates.remove(mParentStates.size() - 1);
}
private void pushParentState(State state) {
mParentStates.add(state);
}
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
mObserverMap.remove(observer);
}
/**
* The number of observers.
*
* @return The number of observers.
*/
@SuppressWarnings("WeakerAccess")
public int getObserverCount() {
return mObserverMap.size();
}
@NonNull
@Override
public State getCurrentState() {
return mState;
}
//获取状况 ,当时组件的生命周期事情分发过来后
//Lifecycle的状况机要处于的状况
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);
}
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);
}
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);
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
//将数组的Entry拿出来,Entry中key便是观察者,Value便是Lifecycle的状况
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
//回调观察者
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
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();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
//回调观察者
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
+ "new events from it.");
return;
}
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);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//在里边会回调一切观察者
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
static State min(@NonNull State state1, @Nullable State state2) {
return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1;
}
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
}
经过以上的代码咱们能够大约猜出组件生命周期产生改动的适合是怎么告诉Lifecycle
的,如下图:
那么,咱们经过源码来看一看,组件的生命周期改动的时分是怎么告诉Lifecycle的。
Lifecycle
的完成类LifecycleRegistry
是在Activity
的父类ComponentActivity
中被实例化的,所以咱们开去ComponentActivity
中看看,一下是ComponentActivity
相关代码:
@RestrictTo(LIBRARY_GROUP)
public class ComponentActivity extends Activity implements LifecycleOwner {
private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap =
new SimpleArrayMap<>();
//1、
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@RestrictTo(LIBRARY_GROUP)
public void putExtraData(ExtraData extraData) {
mExtraDataMap.put(extraData.getClass(), extraData);
}
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//2、
ReportFragment.injectIfNeededIn(this);
}
@CallSuper
@Override
protected void onSaveInstanceState(Bundle outState) {
//3、
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
super.onSaveInstanceState(outState);
}
@RestrictTo(LIBRARY_GROUP)
public <T extends ExtraData> T getExtraData(Class<T> extraDataClass) {
return (T) mExtraDataMap.get(extraDataClass);
}
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
@RestrictTo(LIBRARY_GROUP)
public static class ExtraData {
}
}
在注释1处LifecycleRegistry
被创立了,在注释3处,将LifecycleRegistry
的State设置为CREATED,注释2处的将ComponentActivity
注入到ReportFragment中。正常来说,从以上结构来看,组件的生命周期事情应该是在ComponentActivity
中被分发给LifecycleRegistry
的,但实际上,并不是,而是由ReportFragment
来进行分发的,所以接下来咱们要进入ReportFragment
中看看:
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
public static void injectIfNeededIn(Activity activity) {
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
...
@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);
}
//...
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
//判别当时组件是否完成了LifecycleRegistryOwner接口
//LifecycleRegistryOwner是LifecycleOwner的子类
//两者区别的它们的getLifecycle()办法返回的类型不一样
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
//判别当时组件是否完成了LifecycleOwner接口
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
//...
}
经过以上代码咱们能够看出,在ReportFragment
的各个生命周期的办法中,会调用dispatch()
办法,而dispatch办法中就会将组件相对应的事情分发给Lifecycle
,最终会在LifecycleRegistry
进行状况更新以及告诉一切的观察者。
以上便是Lifecycle
感知组件生命周期,并告诉观察者的流程。
Lifecycle中的状况机概念
为什么会存在状况机的概念呢?由于Lifecycle
中的观察者或许会在Activity
的任意一个生命周期中增加进来,所以为了防止后面增加的观察者错失组件前面的生命周期,就用状况机中的状况合作组件的生命周期的事情来记载Activity
的生命周期轨道。大家还记得Lifecycle
中的两个枚举类吗,那便是状况机用来记载Activity
的生命周期记载轨道的。咱们能够先来看一下这张图**(紫色字体为Lifecycle.State枚举类中的常量,黑色字为Lifecycle.EVENT中的常量,对应的是组件的生命周期):
当Activity
等组件的生命周期产生改动的后,就会把相对应的生命周期传到Lifecycle
中**,Lifecycle
会将组件的生命周期和State枚举类中的枚举常量对应保存起来并与每个观察者进行绑定,具体对应如上图。在Lifecycle
中,为了更好的了解组件的生命周期轨道,将组件的生命周期分为两个概念,第一个概念叫“生命周期的行进”,指的是onCreate->onStart->onResume
这个进程,第二个概念叫 “生命周期的倒退” ,指的是onPause->onStop->onDestroy
这个进程(注意,行进和后退不需要三个办法都调用,两个办法调用也能够)。接下来咱们聊聊Lifecycle.State
的作用:
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
//比较枚举常量的序数巨细的办法
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
Lifecycle.State
会保存在观察者中去的,其意义是,当咱们在onStart
办法中注册一个观察者时,为了让这个观察者不错失之前履行过了的onCreate
生命周期,在增加观察者的时分会经过一段代码来补偿:
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//观察者刚注册的时分,初始化的状况INITIALIZED
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//把观察者和状况封装在一同,这样能更好的绑定
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
//假如观察者的状况和Lifecycle不同步,就先同步,在同步的好就会进行回调观察者
//假如咱们是在onStart中注册的观察者,必定不同步(这儿建议去自行断点测验下)
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);
}
//...
}
在以上代码中会比照观察者和Lifecycle
保存的组组件的生命周期是否同步,假如不同步,就先进行同步,同步的时分就会回调观察者。以下是代码测验:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
MainActivity.this.getLifecycle().addObserver(new Feel());
}
}
@SuppressLint("RestrictedApi")
public class Feel implements GenericLifecycleObserver {
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
Log.e("Feel----------->","Activity:"+event.name()+"------Lifecycle.State:------->"+source.getLifecycle().getCurrentState());
}
}
一下是输出日志:
2022-08-04 16:01:23.745 26582-26582/com.kuer.ke_livedata E/Feel----------->: Activity:ON_CREATE------Lifecycle.State:------->STARTED
2022-08-04 16:01:23.745 26582-26582/com.kuer.ke_livedata E/Feel----------->: Activity:ON_START------Lifecycle.State:------->STARTED
2022-08-04 16:01:23.745 26582-26582/com.kuer.ke_livedata E/Feel----------->: Activity:ON_RESUME------Lifecycle.State:------->RESUMED
总结:经过以上代码,就能够了解到Lifecycle
的状况机的作用了,其实便是用来同步组件和Lifecycle
和观察者的生命周期状况的。
假如你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙: 点赞,转发,有你们的 『点赞和谈论』,才是我发明的动力。微信搜索大众号 [小尘Android专栏] ,第一时间阅读更多干货常识!