Lifecycle

Lifecycle 组件指的是 android.arch.lifecycle 包下提供的各种类与接口,可以让开发者构建能感知其他组件(主要指Activity 、Fragment)生命周期(lifecycle-aware)的类。

使用

引用依赖
def lifecycle_version = "2.1.0"
compile "android.arch.lifecycle:runtime:$lifecycle_version"
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"
使用步骤
1.新建类实现LifecycleObserver接口,通过注解关联生命周期方法。
public class ActivityLifeObserver implements BasePresenter,LifecycleObserver {

    private final static String TAG = "ActivityLifeObserver";
    
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    @Override
    public void onCreate() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    @Override
    public void onStart() {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    @Override
    public void onResume() {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    @Override
    public void onPause() {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    @Override
    public void onStop() {
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    @Override
    public void onDestroy() {
    }
}

BasePresenter是回调方法可以随意,OnLifecycleEvent的参数是枚举类Lifecycle.Event,对应生命周期方法。

2.Activity实现LifecycleOwner接口,声明全局变量LifecycleRegistry,并重写getLifecycle方法返回。通过LifecycleRegistry注册监听。详细代码如下:
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
    private LifecycleRegistry mRegistry;
    private LifecycleObserver mLifecycleObserver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (mRegistry == null){
            mRegistry = new LifecycleRegistry(this);
        }
        //绑定
        mRegistry.addObserver(mLifecycleObserver = new ActivityLifeObserver());
    }
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        //getLifecycle在oncreate前,因此需要判断
        if (null == mRegistry){
            mRegistry = new LifecycleRegistry(this);
        }
        return mRegistry;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mRegistry){
            //解绑
            mRegistry.removeObserver(mLifecycleObserver);
        }
    }
}

此时运行就可以监听声明周期了,效果如下:

D/ActivityLifeObserver: onCreate
D/ActivityLifeObserver: onStart: 
D/ActivityLifeObserver: onResume: 
D/ActivityLifeObserver: onPause: 
D/ActivityLifeObserver: onStop: 
D/ActivityLifeObserver: onDestroy: 

原理

Lifecycle是如何感知生命周期的?
Lifecycle是如何完成注解与生命周期方法绑定的?

带着这两个问题我们来看一下Lifecycle源码。

首先我们来看一下Lifecycle是如何感知生命周期的?
从MainActivity来看一共做了三件事

1.初始化LifecycleRegistry
2.绑定LifecycleObserver
3.通过getLifecycle返回LifecycleRegistry

第一二步是基础的数据绑定操作,那么涉及生命周期感知的应该就是第三步了。点击getLifecycle方法跳出引用的地方,我们发现有个类叫ReportFragment。有过glide分析经验的同志应该记得Glide就是向Activity添加无界面的Fragment从而感知生命周期,那么Lifecycle是否如此,我们来看一下ReportFragment源码:

@SuppressWarnings("UnknownNullness") // TODO https://issuetracker.google.com/issues/112197238
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";
    ...
    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        dispatch(Lifecycle.Event.ON_RESUME);
    }
    ...
    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);
            }
        }
    }
}

我们发现ReportFragment的确是用来感知生命周期的,在对应的生命周期方法中调用dispatch将生命周期状态分发下去。最后事件走到LifecycleRegistry的handleLifecycleEvent方法里面。我们看一下ReportFragment是在哪里被添加的:

    //向activity添加ReportFragment
    public static void injectIfNeededIn(Activity activity) {
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }

injectIfNeededIn是ReportFragment添加进Activity的方法,调用的地方在ComponentActivity中,而ComponentActivity是AppCompatActivity的父类:

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

所以在activity刚刚被创建的时候,ReportFragment就已经同步添加了。这时候第一个问题就可以回答了:Lifecycle是通过向Activity添加ReportFragment从而达到感知生命周期的作用。
下面我们来看第二个问题,上面我们看到ReportFragment生命周期方法走到LifecycleRegistry的handleLifecycleEvent方法里面,下面我们来看下该方法:

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        sync();
        mHandlingEvent = false;
    }

handleLifecycleEvent会依据Event找到下一个状态,并将同步至该状态,核心方法是 sync():

    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;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

sync方法对比此状态与map最后一个状态,如果小于则回退,对比最新的状态,如果大于则前进状态,则前进,以下是backwardPass代码:

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

代码核心为ObserverWithState ,调用其dispatchEvent完成状态分发,ObserverWithState 是内部类代码为:

    static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }

可以看到ObserverWithState 将LifecycleObserver封装为LifecycleEventObserver ,然后调用onStateChanged了,下面我们看下封装的代码Lifecycling.lifecycleEventObserver(observer):

    static LifecycleEventObserver lifecycleEventObserver(Object object) {
        boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
        boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
        if (isLifecycleEventObserver && isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                    (LifecycleEventObserver) object);
        }
        if (isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
        }

        if (isLifecycleEventObserver) {
            return (LifecycleEventObserver) object;
        }

        final Class<?> klass = object.getClass();
        int type = getObserverConstructorType(klass);
        if (type == GENERATED_CALLBACK) {
            List<Constructor<? extends GeneratedAdapter>> 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);
    }

lifecycleEventObserver有4层判定:

1、FullLifecycleObserver的子类,返回FullLifecycleObserverAdapter,FullLifecycleObserver是官方实现,默认有生命周期方法。不用注解。
2、LifecycleEventObserver子类,返回LifecycleEventObserver子类本身,改类提供了onStateChanged回调方法,用于检测生命周期变换。
3、如果APT生成了对应的类,则返回CompositeGeneratedAdaptersObserver,其内部也是调用反射执行对应的注解方法。
4、如都不满足则返回ReflectiveGenericLifecycleObserver,内部onStateChanged调用CallbackInfo的invokeCallbacks方法。

我们来看下invokeCallbacks方法:

 void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
         invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
         invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                    target);
}
private static void invokeMethodsForEvent(List<MethodReference> handlers,
                LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
            if (handlers != null) {
                for (int i = handlers.size() - 1; i >= 0; i--) {
                    handlers.get(i).invokeCallback(source, event, mWrapped);
                }
            }
        }
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
            //noinspection TryWithIdenticalCatches
            try {
                switch (mCallType) {
                    case CALL_TYPE_NO_ARG:
                        mMethod.invoke(target);
                        break;
                    case CALL_TYPE_PROVIDER:
                        mMethod.invoke(target, source);
                        break;
                    case CALL_TYPE_PROVIDER_WITH_EVENT:
                        mMethod.invoke(target, source, event);
                        break;
                }
            } catch (InvocationTargetException e) {
                throw new RuntimeException("Failed to call observer method", e.getCause());
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

一路追寻,发现最终是通过反射来完成方法的执行的。那么Method是如下关联的呢?我们发现在前面的lifecycleEventObserver方法中有个代码语句:

int type = getObserverConstructorType(klass);

private static int getObserverConstructorType(Class<?> klass) {
        Integer callbackCache = sCallbackCache.get(klass);
        if (callbackCache != null) {
            return callbackCache;
        }
        int type = resolveObserverCallbackType(klass);
        sCallbackCache.put(klass, type);
        return type;
    }

该代码块是判断是否是APT还是默认的反射方式,其中resolveObserverCallbackType做了一些操作:

...
ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
...
hasLifecycleMethods方法:
...
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
        OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
        if (annotation != null) {
                // Optimization for reflection, we know that this method is called
                // when there is no generated adapter. But there are methods with @OnLifecycleEvent
                // so we know that will use ReflectiveGenericLifecycleObserver,
                // so we createInfo in advance.
                // CreateInfo always initialize mHasLifecycleMethods for a class, so we don't do it
                // here.
         createInfo(klass, methods);
         return true;
  }
}
...

hasLifecycleMethods获取被OnLifecycleEvent 注解的方法,然后一一创建CallbackInfo对象:

for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            ....
            Class<?>[] params = method.getParameterTypes();
            int callType = CALL_TYPE_NO_ARG;
            Lifecycle.Event event = annotation.value();
           ....
            MethodReference methodReference = new MethodReference(callType, method);
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
        CallbackInfo info = new CallbackInfo(handlerToEvent);

到这里我们就可以知道,原来onStateChanged执行的CallbackInfo对象实际上就是封装了OnLifecycleEvent 注解方法的对象。所以当状态变更时,对应的方法也会调用。

总结:

Lifecycle是如何感知生命周期的?

Lifecycle向Activity添加ReportFragment,然后通过ReportFragment感知生命周期。

Lifecycle是如何完成注解与生命周期方法绑定的?

生命周期分发时,最终会执行ObserverWithState的dispatchEvent方法,dispatchEvent方法会调用LifecycleEventObserver的onStateChanged方法。
ObserverWithState通过Lifecycling获取不同类型的LifecycleEventObserver,获取过程中会遍历被OnLifecycleEvent 注解修饰的方法,并保存。
当onStateChanged执行时,通过反射执行对应状态的方法,从而完成注解与生命周期方法的绑定。
如果配置了APT依赖,APT分支在于默认反射分支前。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,723评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,003评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,512评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,825评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,874评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,841评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,812评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,582评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,033评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,309评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,450评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,158评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,789评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,409评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,609评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,440评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,357评论 2 352

推荐阅读更多精彩内容