Lifecycle

Lifecycle

  • 定义
  • Lifecycle使用
  • 源码中如何使用Lifecycle

定义

构建生命周期感知型组件,这些组件可以根据 Activity 或 Fragment 的当前生命周期状态调整行为。

Lifecycle使用 三种方式

LifecycleObserver, FullLifecycleObserver, LifecycleEventObserver (后面两个继承前者)

1. 自定义的LifecycleObserver观察者,用注解声明每个方法观察的宿主的状态

class LocationObserver extends LifecycleObserver{
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onStart(@NotNull LifecycleOwner owner){
      //开启定位
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void onStop(@NotNull LifecycleOwner owner){
       //停止定位
    }

     @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(@NotNull LifecycleOwner owner){
       //释放资源
    }
}
// 注册观察者,观察宿主生命周期状态变化
// 使用Fragment或者Activity中使用 (Activity使用,需要Activity继承CommontActivity)
class MyFragment extends Fragment{
  public void onCreate(Bundle bundle){
    
    MyLifecycleObserver observer =new MyLifecycleObserver()
    getLifecycle().addObserver(observer);
    
  }
}

使用FullLifecycleObserver

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);
}
// 使用DefaultLifecycleObserver 默认实现了所有接口 实现此接口,不需要所有的方法都要实现
class MyObserver implements DefaultLifecycleObserver {
    void onStart(LifecycleOwner owner) {
    // 开启定位
     }

     void onStop(LifecycleOwner owner) {
      // 停止定位
      }

     void onDestroy(LifecycleOwner owner) {
    // 释放资源
      }
}

// 使用Fragment或者Activity中使用 (Activity使用,需要Activity继承CommontActivity)
class MyFragment extends Fragment{
  public void onCreate(Bundle bundle){
    
    MyObserver observer =new MyObserver()
    getLifecycle().addObserver(observer);
    
  }
}

使用LifecycleEventObserver

public interface LifecycleEventObserver extends LifecycleObserver {
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}

class LocationObserver extends LifecycleEventObserver{
    @override
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event){
      //需要自行判断life-event是onStart, 还是onStop,亦或者是onDestroy
    }
}

Lifecycle 抽象类

  • 注册监听
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);
  • 移除监听
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);
  • 获取当前状态
    @MainThread
    @NonNull
    public abstract State getCurrentState();
  • Event
public enum Event {
        /**
         * Constant for onCreate event of the {@link LifecycleOwner}.
         */
        ON_CREATE, // 宿主发送onCreate事件
        /**
         * Constant for onStart event of the {@link LifecycleOwner}.
         */
        ON_START,// 宿主发送onStart事件
        /**
         * Constant for onResume event of the {@link LifecycleOwner}.
         */
        ON_RESUME,// 宿主发送onResume事件
        /**
         * Constant for onPause event of the {@link LifecycleOwner}.
         */
        ON_PAUSE,// 宿主发送onPause事件
        /**
         * Constant for onStop event of the {@link LifecycleOwner}.
         */
        ON_STOP,// 宿主发送onStop事件
        /**
         * Constant for onDestroy event of the {@link LifecycleOwner}.
         */
        ON_DESTROY,// 宿主发送onDestroy事件
        /**
         * An {@link Event Event} constant that can be used to match all events.
         */
        ON_ANY  // 宿主发送onCreate事件
    }
  • State
 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;
        }
    }
  • DESTROYED: Activity执行onDestroy的状态
  • INITIALIZED:当Activity执行onCreate之前会置为当前状态,也是Activity默认状态
  • CREATED: 当执行onCreate之后或者执行onStop后的状态
  • STARTED: 执行onStart或者onPause后的状态
  • RESUMED:执行onResume后的状态

LifecycleRegistry

  • LifecycleRegistry 继承Lifecycle,Activity/Fragment宿主生命周期分发主要的在此类中

LifecycleOwner、Lifecycle、LifecycleObserver

  • LifecycleOwner:宿主,一般Fragment和Activity实现LifecycleOwner,并实现getLifecycle()方法,宿主成员变量中创建Lifecycle(LifecycleRegistry)对象,用来事件的分发

  • Lifecycle:在宿主中创建,并提供LifecycleRegistry对象,便于外界获取并通知生命周期

  • LifecycleObserver: 创建的Observer对象,注册到宿主中LifecycleRegistry对象里,达到对应的生命周期时,做对应的业务

Activity/Fragment生命周期管理

 /**
     * Sets the current state and notifies the observers.
     * <p>
     * Note that if the {@code currentState} is the same state as the last call to this method,
     * calling this method has no effect.
     *
     * @param event The event that was received
     */
  //  Activity/ Fragment 生命周期分发都会走到LifecycleRegistry的当前方法 
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next); // 将当前状态与Activity/Fragment生命周期对其, 会调用到sysc()方法
    }
// 根据当前传入的event  获取对应的状态, 如果是Stop或者Pause 则状态回退
 static State getStateAfter(Event event) {
        switch (event) {
            case ON_CREATE: // 如果是create或者stop 则返回CREATED状态
            case ON_STOP:
                return CREATED;
            case ON_START: // 如果是Start或者Pause 则返回STARTED状态
            case ON_PAUSE:
                return STARTED;
            case ON_RESUME: // 如果是resume,则返回Resumed状态
                return RESUMED;
            case ON_DESTROY: // Destroy 返回Destoryed状态
                return DESTROYED;
            case ON_ANY:
                break;
        }
        throw new IllegalArgumentException("Unexpected event value " + event);
    }
    // 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) {
            throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
                    + "garbage collected. It is too late to change lifecycle state.");
        }
        while (!isSynced()) {
         // 判断条件为,当前宿主的Observer中如果有与宿主对象状态不一致,才会进入循环体,如果一致,则不处理
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                // 判断宿主当前的状态是否比 Observer的状态小,如果是,则原来注册的Observer状态回退
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                // 如果Observer状态新加入,则需要将新加进来的Observer对齐宿主状态
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
// 状态回退
 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();
            }
        }
    }
  // 状态前进,保持与宿主状态对齐
    private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            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 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);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354

推荐阅读更多精彩内容