当前位置: 代码迷 >> 综合 >> Android Jetpack -- Lifecycles篇
  详细解决方案

Android Jetpack -- Lifecycles篇

热度:29   发布时间:2023-11-22 10:12:46.0
  • Android Jetpack架构组件
    • Android Jetpack – ViewModel篇
    • Android Jetpack – LiveDate篇
    • Android Jetpack – DataBinding篇
    • Android Jetpack – Navigation篇
    • Android Jetpack – Lifecycles篇

基本概念

Lifecycles其实从名字看肯定是与生命周期相关,那它与生命周期又有什么联系?
先参考一下官方文档:
Lifecycles是一个生命周期感知组件,当Activity或者Fragment的生命周期发生改变的时会,Lifecycles也会做出相应的生命周期状态的改变,它保存关于组件生命周期状态的信息(比如活动或片段),并允许其他对象观察这种状态。
可以看出Lifecycles是一个组件,具有感知生命周期的功能,既然是个组件,那就说明可以嵌入到其他地方,比如VewModel便是其中之一。
我们知道,当我们需要处理与生命周期相关的组件的时候,在没有Lifecycles提供的时候,需要设置各种回调,如下所示:

class MyLocationListener {
    public MyLocationListener(Context context, Callback callback) {
    // ...}void start() {
    // connect to system location service}void stop() {
    // disconnect from system location service}
}class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;@Overridepublic void onCreate(...) {
    myLocationListener = new MyLocationListener(this, (location) -> {
    // update UI});}@Overridepublic void onStart() {
    super.onStart();myLocationListener.start();// manage other components that need to respond// to the activity lifecycle}@Overridepublic void onStop() {
    super.onStop();myLocationListener.stop();// manage other components that need to respond// to the activity lifecycle}
}

当组件数目过多的时候,便会需要在生命周期回调中管理多个组件从而徒增代码量,使得项目难以维护,而且在生命周期中执行过多的耗时操作极易引起内存泄漏,而这些都可以通过Lifecycles来解决。
看下Lifecycles的源码吧,反正也不长

public abstract class Lifecycle {
    /*** Lifecycle coroutines extensions stashes the CoroutineScope into this field.** @hide used by lifecycle-common-ktx*/@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)@NonNullAtomicReference<Object> mInternalScopeRef = new AtomicReference<>();//添加生命周期状态的观察者@MainThreadpublic abstract void addObserver(@NonNull LifecycleObserver observer);//这个也就是移除观察者@MainThreadpublic abstract void removeObserver(@NonNull LifecycleObserver observer);//获得当前生命周期状态@MainThread@NonNullpublic abstract State getCurrentState();//再熟悉不过的生命周期回调//是从框架和生命周期类分派的生命周期事件,这些事件映射到活动和片段中的回调事件。@SuppressWarnings("WeakerAccess")public enum Event {
    /*** Constant for onCreate event of the {@link LifecycleOwner}.*/ON_CREATE,/*** Constant for onStart event of the {@link LifecycleOwner}.*/ON_START,/*** Constant for onResume event of the {@link LifecycleOwner}.*/ON_RESUME,/*** Constant for onPause event of the {@link LifecycleOwner}.*/ON_PAUSE,/*** Constant for onStop event of the {@link LifecycleOwner}.*/ON_STOP,/*** Constant for onDestroy event of the {@link LifecycleOwner}.*/ON_DESTROY,/*** An {@link Event Event} constant that can be used to match all events.*/ON_ANY}//这个也就此当前所处于的状态了@SuppressWarnings("WeakerAccess")public enum State {
    /*** Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch* any more events. For instance, for an {@link android.app.Activity}, this state is reached* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.*/DESTROYED,/*** Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is* the state when it is constructed but has not received* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.*/INITIALIZED,/*** Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state* is reached in two cases:* <ul>* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.* </ul>*/CREATED,/*** Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state* is reached in two cases:* <ul>* <li>after {@link android.app.Activity#onStart() onStart} call;* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.* </ul>*/STARTED,/*** Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state* is reached after {@link android.app.Activity#onResume() onResume} is called.*/RESUMED;/*** Compares if this State is greater or equal to the given {@code state}.** @param state State to compare with* @return true if this State is greater or equal to the given {@code state}*/public boolean isAtLeast(@NonNull State state) {
    return compareTo(state) >= 0;}}
}

使用示例

以Chronometer为例子来示范生命周期监听

public class MyChronometer extends Chronometer implements LifecycleObserver {
    private long time;public MyChronometer(Context context) {
    super(context);}public MyChronometer(Context context, AttributeSet attrs) {
    super(context, attrs);}public MyChronometer(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);}//以注解的形式完成监听@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)private void stopMeter(){
    time = SystemClock.elapsedRealtime() - getBase();stop();}@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)private void resumeMeter(){
    setBase(SystemClock.elapsedRealtime() - time);start();}
}

然后Activity如下:只需要添加观察者即可

public class LifecyclesActivity extends AppCompatActivity {
    MyChronometer chronometer;@Overrideprotected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);setContentView(R.layout.activity_lifecycles);chronometer = findViewById(R.id.meter);getLifecycle().addObserver(chronometer);}}

是不是感觉Activity与Chronometer之间解耦了,Chrononmeter自我实现了良好的封装,也方便了移植。
这也就是使用Lifecycles带来的好处。

  相关解决方案