Android Lifecycle 生命週期組件詳解

轉載請標明出處:https://blog.csdn.net/zhaoyanjun6/article/details/99695779
本文出自【趙彥軍的博客】

一、Lifecycle簡介

爲什麼要引進Lifecycle

我們在處理Activity或者Fragment組件的生命週期相關時,不可避免會遇到這樣的問題:

我們在ActivityonCreate()中初始化某些成員(比如MVP架構中的Presenter,或者AudioManagerMediaPlayer等),然後在onStop中對這些成員進行對應處理,在onDestroy中釋放這些資源,這樣導致我們的代碼也許會像這樣:

class MyPresenter{
    public MyPresenter() {
    }

    void create() {
        //do something
    }

    void destroy() {
        //do something
    }
}

class MyActivity extends AppCompatActivity {
    private MyPresenter presenter;

    public void onCreate(...) {
        presenter= new MyPresenter ();
        presenter.create();
    }

    public void onDestroy() {
        super.onDestroy();
        presenter.destory();
    }
}

代碼沒有問題,關鍵問題是,實際生產環境中 ,這樣的代碼會非常複雜,你最終會有太多的類似調用並且會導致 onCreate()onDestroy()方法變的非常臃腫。

二、解決方案

Lifecycle 是一個類,它持有關於組件(如 ActivityFragment)生命週期狀態的信息,並且允許其他對象觀察此狀態。

第1步:IPresenter 繼承 LifecycleObserver

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.OnLifecycleEvent;
import org.jetbrains.annotations.NotNull;

public interface IPresenter extends LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate(@NotNull LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(@NotNull LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onLifecycleChanged(@NotNull LifecycleOwner owner,
                            @NotNull Lifecycle.Event event);
}

第2步:BasePresenter 實現 LifecycleObserver

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.OnLifecycleEvent;
import org.jetbrains.annotations.NotNull;

public interface IPresenter extends LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate(@NotNull LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(@NotNull LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onLifecycleChanged(@NotNull LifecycleOwner owner,
                            @NotNull Lifecycle.Event event);
}

第3步:MainPresenter 繼承 BasePresenter

package com.yanjun;

public class MainPresenter extends BasePresenter {
      
}

第4步:在Activity/Fragment容器中添加Observer

package com.yanjun

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log

class MainActivity : AppCompatActivity() {

    lateinit var iPresenter: IPresenter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        iPresenter = MainPresenter()
        lifecycle.addObserver(iPresenter)

        Log.e("zhaoyanjun", "MainActivity.onCreate")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e("zhaoyanjun", "MainActivity.onDestroy")
    }
}

如此,每當Activity發生了對應的生命週期改變,Presenter就會執行對應事件註解的方法:
onCreateonDestroy事件之外,Lifecycle一共提供了所有的生命週期事件,只要
通過註解進行聲明,就能夠使LifecycleObserver觀察到對應的生命週期事件:

//當應用進入時
E/zhaoyanjun: MainActivity.onCreate
E/zhaoyanjun: BasePresenter.onCreateclass com.yanjun.MainPresenter
E/zhaoyanjun: BasePresenter.onLifecycleChanged owner ON_CREATE
E/zhaoyanjun: BasePresenter.onLifecycleChanged owner ON_START
E/zhaoyanjun: BasePresenter.onLifecycleChanged owner ON_RESUME

//當應用退出時
E/zhaoyanjun: BasePresenter.onLifecycleChanged owner ON_PAUSE
E/zhaoyanjun: BasePresenter.onLifecycleChanged owner ON_STOP
E/zhaoyanjun: BasePresenter.onDestroyclass com.yanjun.MainPresenter
E/zhaoyanjun: BasePresenter.onLifecycleChanged owner ON_DESTROY
E/zhaoyanjun: MainActivity.onDestroy

三、Lifecycle.Event

Lifecycle 是一個抽象類

public abstract class Lifecycle {

       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
    }

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

四、原理分析

我們先將重要的這些類挑選出來:

  • LifecycleObserver接口( Lifecycle觀察者):

實現該接口的類,通過註解的方式,可以通過被LifecycleOwner類的addObserver(LifecycleObserver o)方法註冊,被註冊後,LifecycleObserver便可以觀察到LifecycleOwner的生命週期事件。

  • LifecycleOwner接口 Lifecycle持有者)

實現該接口的類持有生命週期(Lifecycle對象),該接口的生命週期(Lifecycle對象)的改變會被其註冊的觀察者LifecycleObserver觀察到並觸發其對應的事件。

  • Lifecycle(生命週期):

LifecycleOwner不同的是,LifecycleOwner本身持有Lifecycle對象,LifecycleOwner通過其Lifecycle getLifecycle()的接口獲取內部Lifecycle對象。

  • State(當前生命週期所處狀態):如圖所示。

  • Event(當前生命週期改變對應的事件):

Lifecycle發生改變,如進入onCreate,會自動發出ON_CREATE事件。

下面我們將換一種方式在Fragment 中實現 Lifecycle 的功能,來探究它的內部實現原理:

1、Fragment:LifecycleOwner

Fragment(Activity同理,我們 本文以Fragment爲例,下同):實現了LifecycleOwner接口,這意味着Fragment對象持有生命週期對象(Lifecycle),並可以通過Lifecycle getLifecycle()方法獲取內部的Lifecycle對象:

public class Fragment implements xxx, LifecycleOwner {
    
    //...省略其他

   LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

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

public interface LifecycleOwner {
    @NonNull
    Lifecycle getLifecycle();
}

可以看到,實現的getLifecycle()方法,實際上返回的是 LifecycleRegistry 對象,LifecycleRegistry對象實際上繼承了 Lifecycle,這個下文再講。
持有Lifecycle有什麼作用呢?實際上在Fragment對應的生命週期內,都會發送對應的生命週期事件給內部的 LifecycleRegistry對象處理:

public class Fragment implements xxx, LifecycleOwner {
    //...
    void performCreate(Bundle savedInstanceState) {
        onCreate(savedInstanceState);  //1.先執行生命週期方法
        //...省略代碼
        //2.生命週期事件分發
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }

    void performStart() {
        onStart();
        //...
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    void performResume() {
         onResume();
        //...
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
    }

    void performPause() {
        //3.注意,調用順序變了
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        //...
        onPause();
    }

    void performStop() {
       mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        //...
        onStop();
    }

    void performDestroy() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
        //...
        onDestroy();
    }
}

隨着Fragment不同走到不同的生命週期,除了暴露給我們的生命週期方法onCreate/onStart/…/onDestroy等,同時,Fragment內部的Lifecycle對象(就是mLifecycleRegistry)還將生命週期對應的事件作爲參數傳給了 handleLifecycleEvent() 方法。

同時,你會發現FragmentperformCreate()、performStart()、performResume()會先調用自身的onXXX()方法,然後再調用LifecycleRegistryhandleLifecycleEvent()方法;而在performPause()、performStop()、performDestroy()中會先LifecycleRegistry的handleLifecycleEvent()方法 ,然後調用自身的onXXX()方法。

在這裏插入圖片描述

FullLifecycleObserver

LifecycleObserver有一個子類是 :FullLifecycleObserver ,下面我們看看它的實現:


package android.arch.lifecycle;

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

不過可惜的是 FullLifecycleObserver 不是 public , 我們也用不了。

參考資料

Android官方架構組件Lifecycle:生命週期組件詳解&原理分析

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章