Android lifecyle 源码解剖,android应用开发

2022/1/28 14:04:41

本文主要是介绍Android lifecyle 源码解剖,android应用开发,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

public class CustomLifecycleActivity extends FragmentActivity implements LifecycleOwner {

private LifecycleRegistry mLifecycleRegistry;

private static final String TAG = “CustomLifecycleActivity”;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_custom_lifecycle);

mLifecycleRegistry = new LifecycleRegistry(this);

mLifecycleRegistry.markState(Lifecycle.State.CREATED);

getLifecycle().addObserver(new GenericLifecycleObserver() {

@Override

public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {

Log.d(TAG, "onStateChanged: event = " + event);

}

});

}

@Override

protected void onStart() {

super.onStart();

mLifecycleRegistry.markState(Lifecycle.State.STARTED);

}

@Override

protected void onResume() {

super.onResume();

mLifecycleRegistry.markState(Lifecycle.State.RESUMED);

}

@Override

protected void onDestroy() {

super.onDestroy();

mLifecycleRegistry.markState(Lifecycle.State.DESTROYED);

}

@NonNull

@Override

public Lifecycle getLifecycle() {

return mLifecycleRegistry;

}

}

  1. 第一步:先实现 LifecycleOwner 接口,并返回 mLifecycleRegistry

  2. 第二步:在 Activity 生命周期变化的时候,调用 mLifecycleRegistry.markState() 方法标记相应的状态

  3. 如果想添加 observer,调用 addObserver 方法添加观察者,这样会在 activity 生命周期变化的时候,回调 observer 的 onchange 方法。

我们先来看一下 getLifecycle() 方法, getLifecycle() 它返回的是一个 Lifecycle 的实例,sdk 中默认的实现类为 LifecycleRegistry。

接下来,我们一起来看一下它的 observer 方法。

public void addObserver(@NonNull LifecycleObserver observer) {

// 判断是否是 DESTROYED,如果是将初始状态置为 DESTROYED,否则为 INITIALIZED

State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;

// ObserverWithState 包装

ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);

// 将 observer 作为key,在缓存的 mObserverMap 中查找是否存在

ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

// 存在,直接返回回去,证明该 observer 已经添加过了。否则,证明还没有添加过该 observer

if (previous != null) {

return;

}

LifecycleOwner lifecycleOwner = mLifecycleOwner.get();

if (lifecycleOwner == null) {

// it is null we should be destroyed. Fallback quickly

return;

}

// 这里 mAddingObserverCounter 为 0 ,mHandlingEvent 为 false

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–;

}

在 addObserver 方法中,它主要干这几件事情

  1. 首先,先初始化状态, 判断当前 mState 是否是 DESTROYED,如果是将初始状态置为 DESTROYED,否则为 INITIALIZED,接着用 ObserverWithState 包装 observer 和 初始化状态 initialState

  2. 将 observer 作为 key,在缓存的 mObserverMap 中查找是否存在,如果存在,证明该 observer 已经添加过,直接返回回去,不必再进行处理。

  3. addObserver 方法中第 21 行 , isReentrance 一般情况下为 false,什么情况 为 true,暂时未想到,

接下来我们先来看 calculateTargetState 方法。

private State calculateTargetState(LifecycleObserver observer) {

// 取出 mObserverMap 的上一个 entry,previous

Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);

// 如果不为空,获取它的状态

State siblingState = previous != null ? previous.getValue().mState : null;

// 判断 mParentStates 是否为 null,不为 null,去最后的一个状态,否则,为 null

State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
null;

// 取最小的状态

return min(min(mState, siblingState), parentState);

}

  1. 首先,取出 mObserverMap 中上一个的 entry,该 LifecycleRegistry 实例如果是第一次调用 addObserver 实例的话,那么是 null,否则是上一个 observer 的 entry

  2. 根据 previous 是否为 null,设置 siblingState 的值

  3. 判断 mParentStates 是否为 null,不为 null,取 mParentStates 最后一次的状态

  4. 取 mState, siblingState 最小的状态 a,再取 a 与 parentState 的状态 b

public enum State {

DESTROYED,

INITIALIZED,

CREATED,

STARTED,

RESUMED;

public boolean isAtLeast(@NonNull State state) {

return compareTo(state) >= 0;

}

}

State 中,他们排序的顺序是 DESTROYED < INITIALIZED < CREATED < STARTED < RESUMED。

我们知道,我们在 activity 的 onCreate 方法中初始化 LifecycleRegistry,并标记它的状态为 CREATED。当我们第一次在 onCreate 方法调用 addObserver 的时候,在 calculateTargetState 方法中,若是首次调用 previous 为 null,则 siblingState,parentState 为 null, 而 mState 为 CREATED,所以最终的状态为 CREATED,即 State targetState = calculateTargetState(observer); 中 targetState 为 CREATED

// 取最小的状态

return min(min(mState, siblingState), parentState);

看完 calculateTargetState 方法,我们回过头再来看一下 addObserver 方法。

public void addObserver(@NonNull LifecycleObserver observer) {

// 省略若干行

// 这里 mAddingObserverCounter 为 0 ,mHandlingEvent 为 false

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–;

}

这里 statefulObserver.mState 为 DESTROYED 或者 INITIALIZED,肯定比 CREATED 小。而 mObserverMap.contains(observer) 必定为 true,除非我们手动移除掉 mObserverMap。因而,会走进 while循环。

private void pushParentState(State state) {

mParentStates.add(state);

}

private ArrayList mParentStates = new ArrayList<>();

pushParentState(statefulObserver.mState); 很简单,只是将 statefulObserver 的状态添加到 mParentStates 集合中。

继续往下走,接着会调用 statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));

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);

}

upEvent 方法也很简单,只是返回它的下一个 event。这里因为他们的 state为 INITIALIZED,所以它会返回 ON_CREATE。

void dispatchEvent(LifecycleOwner owner, Event event) {

State newState = getStateAfter(event);

mState = min(mState, newState);

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);

}

这里 event 为 ON_CREATE,所以 newState 也为 CREATED。 mState = min(mState, newState); mState newState,两者状态相同,所以 mState 也为 CREATED。接着回调 mLifecycleObserver 的 onStateChanged 方法。所以,这里,会收到我们的 onCreate 事件,与我们的预想相符。

但是我们并没有在 onStart,onResume, onPause , onStop 和 onDestroy 方法中调用 mLifecycleRegistry.handleLifecycleEvent 方法,它又是怎样促发 Observer 的 onStateChanged 方法的。这里先不揭晓,我们先来看一下 26.1.0 以后的 AppCompatActivity,待会你就明白了,会感叹 google 真的牛逼!


从 26.1.0 以后 AppCompatActivity 的设计说起


我们知道,在 26.1.0 以后,如果我们要使用 lifecycle,我们只需要调用以下的方法即可。

SupportActivity

getLifecycle().addObserver(new GenericLifecycleObserver() {

@Override

public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {

Log.d(TAG, “onStateChanged: event =” + event);

}

});

跟踪 getLifecycle() 方法,它会跳转到 SupportActivity 的 getLifecycle 方法 中。

public class SupportActivity extends Activity implements LifecycleOwner, Component {

private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

ReportFragment.injectIfNeededIn(this);

}

@Override

public Lifecycle getLifecycle() {

return mLifecycleRegistry;

}

}

在 SupportActivity 中,它默认为我们初始化 mLifecycleRegistry,作为一个成员变量。接着,他在

onCreate 方法中调用了 ReportFragment.injectIfNeededIn(this); 方法。

public class ReportFragment extends Fragment {

private static final String REPORT_FRAGMENT_TAG = “android.arch.lifecycle”

  • “.LifecycleDispatcher.report_fragment_tag”;

public static void injectIfNeededIn(Activity activity) {

// ProcessLifecycleOwner should always correctly work and some activities may not extend

// FragmentActivity from support lib, so we use framework fragments for activities

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();

}

}

在 injectIfNeededIn 方法中,它会判断我们是否已经添加 ReportFragment,没有的话,添加进去。

public class ReportFragment extends Fragment {

private static final String REPORT_FRAGMENT_TAG = “android.arch.lifecycle”

  • “.LifecycleDispatcher.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();

}

}

@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

onListener listener) {

if (listener != null) {

listener.onStart();

}

}

private void dispatchResume(ActivityInitializationListener listener) {

if (listener != null) {

listener.onResume();

}

}

@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



这篇关于Android lifecyle 源码解剖,android应用开发的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程