Jetpack-Lifecycle

Lifecycle概述

Lifecycle是生命周期感知型组件,可感知组件(如 Activity、 Fragment、service)的生命周期状态的变化。并将生命周期变化的事件通知分发到已注册的观察者。它也是Jetpack组件库的核心基础。Lifecycle整个就是一个观察者模式,来监听activity或者fragment的生命周期。

引入依赖

  • kotlin
dependencies {
        val lifecycle_version = "2.3.1"
        val arch_version = "2.1.0"
 
        // ViewModel
        implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
        // LiveData
        implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")
        // 仅Lifecycles (没有 ViewModel 或 LiveData)
        implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version")
 
        // 为 ViewModel 保存状态模块
        implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version")
 
        // Annotation processor(注释处理器)
        kapt("androidx.lifecycle:lifecycle-compiler:$lifecycle_version")
        // 或者 - 如果使用 Java8,请使用以下代码代替生命周期编译器
        implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycle_version")
 
        // 可选 - 在服务中实现 LifecycleOwner 的助手
        implementation("androidx.lifecycle:lifecycle-service:$lifecycle_version")
 
        // 可选 - ProcessLifecycleOwner 为整个应用程序进程提供生命周期
        implementation("androidx.lifecycle:lifecycle-process:$lifecycle_version")
        // 可选 - 对 LiveData 的 ReactiveStreams 支持
        implementation("androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version")
 
        // 可选 - LiveData 的测试助手
        testImplementation("androidx.arch.core:core-testing:$arch_version")
    }
 
  • java
dependencies {
        val lifecycle_version = "2.3.1"
        val arch_version = "2.1.0"
 
        // ViewModel
        implementation("androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version")
        // LiveData
        implementation("androidx.lifecycle:lifecycle-livedata:$lifecycle_version")
        // Lifecycles only (without ViewModel or LiveData)
        implementation("androidx.lifecycle:lifecycle-runtime:$lifecycle_version")
 
        // Saved state module for ViewModel
        implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version")
 
        // Annotation processor
        annotationProcessor("androidx.lifecycle:lifecycle-compiler:$lifecycle_version")
        // alternately - if using Java8, use the following instead of lifecycle-compiler
        implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycle_version")
 
        // optional - helpers for implementing LifecycleOwner in a Service
        implementation("androidx.lifecycle:lifecycle-service:$lifecycle_version")
 
        // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
        implementation("androidx.lifecycle:lifecycle-process:$lifecycle_version")
 
        // optional - ReactiveStreams support for LiveData
        implementation("androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version")
 
        // optional - Test helpers for LiveData
        testImplementation("androidx.arch.core:core-testing:$arch_version")
    }
————————————————
版权声明:本文为CSDN博主「盛开的伤」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010217055/article/details/118315013

Lifecycle使用分两步

第一步构建观察者
//第一种实现 LifecycleObserver 接口,在对应的方法上面用配合注解声明,当感知到生命周期变化会通知相应事件对应的注解方法,OnLifecycle.Event 注解来接收生命周期回调。
public class MyLifecycle implements LifecycleObserver {
   
   @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
   void onCreate(LifecycleOwner owner) {
     //初始化业务
   }

   @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
   void onStop(LifecycleOwner owner) {
    //结束业务
   }
   ...
}

//第二中实现 LifecycleEventObserver 的onStateChanged 声明周期改变会回调onStateChanged,然后进行判断
public class TestLifecycle implements LifecycleEventObserver {

   @Override
   public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
       switch (event) {
           case ON_CREATE: { }
           break;
           case ON_START: {  }
           break;
           case ON_STOP: 
           break;
       }
   }
}
第二步注册观察者
//得到Lifecycle并注册观察者
public class MyActivity extends AppCompatActivity {

    MyLifecycle myLifecycle;
    TestLifecycle testLifecycle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myLifecycle =new MyLifecycle();
        testLifecycle=new TestLifecycle();
 
        //getLifecycle 返回的是LifecycleRegistry实例
        getLifecycle().addObserver(myLifecycle);   
        getLifecycle().addObserver(testLifecycle);
    }
}

原理分析

Lifecycle是用观察者模式实现,个人理解可以从四个方面(观察者、被观察者、注册、事件分发)来分析。

观察者:

LifecycleObserver、FullLifecycleObserver、FullLifecycleObserver 他们之间的关系,我们通常需要实现LifecycleObserver或者LifecycleEventObserver就可以作为观察者

public interface LifecycleObserver {
     
}


public interface LifecycleEventObserver extends LifecycleObserver {

    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}


interface FullLifecycleObserver extends LifecycleObserver {

    void onCreate(LifecycleOwner owner);

    void onStart(LifecycleOwner owner);

    void onResume(LifecycleOwner owner);

    void onPause(LifecycleOwner owner);

    void onStop(LifecycleOwner owner);

    void onDestroy(LifecycleOwner owner);
}


被观察者:

实现了LifecycleOwner接口的Activity、service和Fragment等组件,getLifecycle返回Lifecycle实现对象实例,

// Activity
public class ComponentActivity extends ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
    
       private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
 
       ...

       @Override
      public Lifecycle getLifecycle() {
          return mLifecycleRegistry;
      }
}

//Fragment
public class Fragment implements ComponentCallbacks, 
         OnCreateContextMenuListener, 
         LifecycleOwner,
         ViewModelStoreOwner,
         SavedStateRegistryOwner {

        LifecycleRegistry mLifecycleRegistry;
       ...
        
       public Fragment() {
           initLifecycle();
        }
 
      private void initLifecycle() {
         mLifecycleRegistry = new LifecycleRegistry(this);
         ...
      }

      @NonNull
      public Lifecycle getLifecycle() {
         return mLifecycleRegistry;
      }

}
//Service
public class LifecycleService extends Service implements LifecycleOwner {
    private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
       ...

    @Override
    public Lifecycle getLifecycle() {
        return mDispatcher.getLifecycle();
    }

}
注册:

注册需要获得Lifecycle 对象实例(activity、fragment、service默认实现Lifecycle接口类是LifecycleRegistry),Lifecycle 类中定义了添加观察者和移除观察者的方法,并定义了两个枚举类, Event - 对应了组件(Activity和Fragment)的生命周期事件,State - 组件生命周期的状态

 
public abstract class Lifecycle {
 
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    @NonNull
    AtomicReference mInternalScopeRef = new AtomicReference<>();
 
   //添加观察者LifecycleObserver,组件的状态变化可以通知LifecycleObserver
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);
   //从观察者列表中移除观察者
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    //返回当前的声明周期状态
    @MainThread
    @NonNull
    public abstract State getCurrentState();

  //Event:生命周期事件,只要通过注解进行声明,就能够使LifecycleObserver观察到对应的生命周期事件
    @SuppressWarnings("WeakerAccess")
    public enum Event { 
        ON_CREATE, 
        ON_START, 
        ON_RESUME, 
        ON_PAUSE, 
        ON_STOP, 
        ON_DESTROY, 
        ON_ANY
    }
 
    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
 
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}

 
 

当Lifecycle注册观察者(调用addObserver方法),就是调用Lifecycle接口 实现类LifecycleRegistry相关方法,这里注册调用的是addObserver,下面是LifecycleRegistry的主要方法

public class LifecycleRegistry extends Lifecycle {

   //保存 LifecycleObserver 及其对应的 State
   private FastSafeIterableMap mObserverMap =
           new FastSafeIterableMap<>();

   // 当前生命周期状态
   private State mState;
   private final WeakReference mLifecycleOwner;

   private ArrayList mParentStates = new ArrayList<>();

   public LifecycleRegistry(@NonNull LifecycleOwner provider) {
       mLifecycleOwner = new WeakReference<>(provider);
       mState = INITIALIZED;
   }

   @MainThread
   public void markState(@NonNull State state) {
       setCurrentState(state);
   }


   @MainThread
   public void setCurrentState(@NonNull State state) {
       moveToState(state);
   }

  ...

    // ObserverWithState
   @Override
   public void addObserver(@NonNull LifecycleObserver observer) {
        //假如当前状态为DESTROYED则设置为DESTROYED, 否则设置为INITIALIZED,在onResume()中调用 addObserver(),那么,观察者依然可以接收到 onCreate 和 onStart 事件。 
       State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
       ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
       // 将包装的observer添加到mObserverMap,以observer自身作为Key值
       ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
      //observer已添加,不进行后续操作
       if (previous != null) {
           return;
       }
       LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
       // 假如lifecycleOwner已销毁,不进行后续操作
       if (lifecycleOwner == null) {
           // it is null we should be destroyed. Fallback quickly
           return;
       }
    //mAddingObserverCounter: 记录正在初始化同步的新添加Observer的数量,大于0时,表示正在对新添加的Observer进行初始化同步。 防止addObserver()重入时,多次调用sync()。使sync()仅仅在最外层的addObserver()同步逻辑完成后执行一次。

    //mHandlingEvent:标记正在进行状态事件同步。 防止moveToState()重入时,多次调用sync()。
      // 判断是否重入
   // mHandlingEvent表示正在执行生命周期迁移导致的sync()同步
   // mAddingObserverCounter>0 表示addObserver()导致的单个Observer同步
       boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
       State targetState = calculateTargetState(observer);
       mAddingObserverCounter++;
       // 如果观察者的初始状态小于 targetState ,则同步到 targetState
     // 通过calculateTargetState获取当前目标需要迁移的目标状态
   State targetState = calculateTargetState(observer);

   // 正在添加Observer的记录自增
   mAddingObserverCounter++;

   // 使Observer迁移到目标状态
   //
   // 当Observer的状态小于目标状态时,升级到目标状态
   // Observer的初始状态时DESTROYED或INITIALIZED,且当初始状态为DESTROYED时,目标状态
   // 也应为DESTROYED,所以新添加的Observer在初始化同步的时候只需要考虑升级同步。
   // 
   // 这里同时做了mObserverMap.contains(observer)的判断,之所以要这么处理,是因为有时候
   // 用户会在observer的生命周期回调中removeObserver移除自身,当发生这种情况时,立即结束
   // 迁移操作
   while ((statefulObserver.mState.compareTo(targetState) < 0 && 
           mObserverMap.contains(observer))) {
       // 缓存observer的状态,用于remove+add问题
       pushParentState(statefulObserver.mState);
       // 派分事件
       statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
       // 移除状态缓存
       popParentState();
       // 由于可能存在的变更,重新调用calculateTargetState获取当前目标需要迁移的目标状态
       targetState = calculateTargetState(observer);
   }

   // 非重入状态执行sync同步
   if (!isReentrance) {
       sync();
   }

   // 正在添加Observer的记录自减
       mAddingObserverCounter--;
   }

   @Override
   public void removeObserver(@NonNull LifecycleObserver observer) {
       mObserverMap.remove(observer);
   }

   @Override
   public State getCurrentState() {
       return mState;
   }

  //对传入的Observer封装成LifecycleEventObserver对象,并同时保存对应的mState状态。
   static class ObserverWithState {
       State mState;
      //LifecycleEventObserver 是继承自LifecycleObserver的接口 声明了onStateChanged()函数
       LifecycleEventObserver mLifecycleObserver;

       ObserverWithState(LifecycleObserver observer, State initialState) {
          //将传入的observer封装成LifecycleEventObserver 对象
           mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
         //保存对应的mState状态
           mState = initialState;
       }
    ...
   }
}

observer转换LifecycleEventObserver源码分析

public class Lifecycling {

      ...

    @NonNull
    static LifecycleEventObserver lifecycleEventObserver(Object object) {
        //类型判断
        boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
       //类型判断
        boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;

       //如果Observer 实现的是LifecycleEventObserver或者FullLifecycleObserver 则不会处理注解信息,转换成LifecycleEventObserver对象然后返回

        if (isLifecycleEventObserver && isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                    (LifecycleEventObserver) object);
        }
      
        if (isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
        }

        if (isLifecycleEventObserver) {
            return (LifecycleEventObserver) object;
        }
        //到这里是生成LifecycleObserver实现类对象,获取observer类的类型,然后判断是需要解析注解信息,还是用反射的方式构建LifecycleEventObserver对象并返回
        final Class klass = object.getClass();
        int type = getObserverConstructorType(klass);
     // 获取 type
    // GENERATED_CALLBACK 表示注解生成的代码
    // REFLECTIVE_CALLBACK 表示使用反射
        if (type == GENERATED_CALLBACK) {
            List> constructors =
                    sClassToAdapters.get(klass);
            if (constructors.size() == 1) {
                GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                        constructors.get(0), object);
                return new SingleGeneratedAdapterObserver(generatedAdapter);
            }
            GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
            for (int i = 0; i < constructors.size(); i++) {
                adapters[i] = createGeneratedAdapter(constructors.get(i), object);
            }
            return new CompositeGeneratedAdaptersObserver(adapters);
        }
        return new ReflectiveGenericLifecycleObserver(object);
    }
 
    ...
}

事件分发:

Activity 注入了一个没有页面的 Fragment(ReportFragment) 。通过注入 Fragment 来代理权限请求。,ReportFragment 才是真正分发生命周期的地方。

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {

     ...

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }

     ...
}

ReportFragment 的各个生命周期函数中通过 dispatch() 方法来分发生命周期事件, 然后调用 LifecycleRegistry 的 handleLifecycleEvent() 方法来处理

public class ReportFragment extends Fragment {

     ...

    @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);
         ...
    }

    private void dispatch(Lifecycle.Event event) {
        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);
            }
        }
    }

   ...
 
}

public class LifecycleRegistry extends Lifecycle {

    ...

     // 设置当前状态并通知观察者
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
       // 通知观察者同步到此生命周期状态
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
    // 检查moveToState是否重入
    // 检查addObserver是否重入
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }

        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }

  // 根据 Event 获取事件之后处于的状态 
    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);
    }

  // 同步所有观察者的状态,比较 mState 和  mObserverMap 中观察者的 State 值,判断是需要向前还是向后同步状态
    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;
             // mState 是当前状态,如果 mState 小于 mObserverMap 中的状态值,调用 backwardPass()
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry newest = mObserverMap.newest();
            // 如果 mState 大于 mObserverMap 中的状态值,调用 forwardPass()
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = 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;
}

  //分发 mObserverMap 中的所有观察者到指定生命周期状态,如果跨度比较大,会依次分发中间状态。分发生命周期事件最终依赖 ObserverWithState 的 dispatchEvent() 方法 
    private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Entry entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            // 向上传递事件,直到 observer 的状态值等于当前状态值
            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> descendingIterator =
                mObserverMap.descendingIterator();
        // 向下传递事件,直到 observer 的状态值等于当前状态值
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry 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();
            }
        }
    }

//获取 state 降级所需要经历的事件。
    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);
    }

   //获取 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);
    }

State 和 Event 对应关系

image.png
image.png

同步 Observer 生命周期的 sync() 方法最终会调用 ObserverWithState 的 dispatchEvent() 方法。

    static class ObserverWithState {
       ...
        //在调用dispatchEvent的时候间接调用了LifecycleEventObserver的onStateChanged函数
        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

参考链接

https://www.jianshu.com/p/7087f1dae359
https://www.jianshu.com/p/375c7913ffb0
https://www.jianshu.com/p/4973c4b10f37
https://www.jianshu.com/p/dbc7a2350acc

你可能感兴趣的:(Jetpack-Lifecycle)