Jetpack使用(一)Lifecycles核心原理

写在前面:Jetpack的更新速度非常快,可能你一个月前看WorkManager是这样用的,下个月这个使用方法就有可能被废弃了(我看源码的时候是遇到过的,而且源码也变了,但核心原理是不变的),所以我们这一系列文章偏重讲原理,使用就一带而过(因为讲了也没用啊,会变的。。。。。,读者使用最好看官方文档官方文档
,当然我这里讲的也是截止到目前的最新用法)。

Jetpack使用(一)Lifecycles核心原理
Jetpack使用(二)LiveData核心原理
Jetpack使用(三)DataBinding核心原理
Jetpack使用(四)ViewModel核心原理
Jetpack使用(五)Navigation核心原理
Jetpack使用(六) WorkManager的4种用法

首先,我们要知道Jetpack是什么?引用谷歌官方的一段话:Jetpack 是一套库、工具和指南,可帮助开发者更轻松地编写优质应用。这些组件可帮助您遵循最佳做法、让您摆脱编写样板代码的工作并简化复杂任务,以便您将精力集中放在所需的代码上。
Jetpack 包含与平台 API 解除捆绑的 androidx.* 软件包库。这意味着,它可以提供向后兼容性,且比 Android 平台的更新频率更高,以此确保您始终可以获取最新且最好的 Jetpack 组件版本。jetpack组件国内官网地址

所以简单一句话来概括:Jetpack组件是很多库和组件的集合(其中包含了androidx),可以加速我们开发app的速度,并且设计稳健减少崩溃和内存泄漏。

首先读者需要注意的是:我们这一系列的文章着重点是源码分析其中的原理,所以只会讲基本的使用,后面最后会出一篇文章统一来讲实际项目中的使用。

谷歌推出Jetpack框架就是想统一架构,就像web开发现在基本都统一使用mvc架构了,谷歌也想把移动端的架构统一起来,估计以后2年市场上的项目都会用Jetpack这一套架构来写了。也就是说你不学Jetpack,以后的安卓代码你可能会看不懂了

从这篇文章开始,到往后的几篇文章,我们会来介绍Jetpack一些常用的组件和库的核心原理,下图给出了Jetpack所有的组件和库


Jetpack所有的组件和库

这篇文章我们先来介绍一下Lifecycles的使用及其内部首先的源码解析。

Lifecycles介绍

Lifecycles中文意思就是生命周期感知型组件,用来感知activity和fragment的生命周期的组件,主要运用观察者模式,Jetpack里很多组件都是基于Lifecycles来实现的,可以毫不夸张的说,Lifecycles是Jetpack的基础、是Jetpack组件库的重中之重。

Lifecycles基本使用

  • 被观察者:主要是activity和fragment,实现LifecycleOwner接口(Support Library 26.1.0 及更高版本中的 Fragment 和 Activity 已实现 LifecycleOwner接口),并且在初始化方法里添加观察者就行了
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {
public class MainActivity extends BaseActivity implements IGoodsView {



    ListView listView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=findViewById(R.id.listView);

        presenter.fetch();
        

    }
    @Override
    protected GoodsPresenter createPresenter() {
        return new GoodsPresenter();
    }
    @Override
    public void showGoodsView(List goods) {
        listView.setAdapter(new GoodsAdapter(this,goods));
    }

    @Override
    public void showErrorMessage(String msg) {

    }

    @Override
    protected void init() {
        super.init();
        getLifecycle().addObserver(presenter);
    }
}
  • 观察者:实现LifecycleObserver接口,就能观测到被观察者的生命周期了,并且想观测哪些生命周期就运用哪个注解
public class BasePresenter implements LifecycleObserver {
    WeakReference iGoodsView;
    /**
     * 绑定view
     */
    public void attachView(T view){
        iGoodsView=new WeakReference<>(view);
    }
    /**
     * 解绑
     */
    public void detachView(){
        if(iGoodsView!=null){
            iGoodsView.clear();
            iGoodsView=null;
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreateX(LifecycleOwner owner) {

    }


    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onStartX(LifecycleOwner owner) {
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void onStop(LifecycleOwner owner) {
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void onResume(LifecycleOwner owner) {
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void onPause(LifecycleOwner owner) {
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestory(LifecycleOwner owner) {
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onAny(LifecycleOwner owner) {
    }
}

我们现在只监听create和destroy,然后运行下代码看看结果:

public class GoodsPresenter extends BasePresenter{

    IGoodsModel iGoodsModel=new GoodsModel();

    /**
     * 执行业务逻辑
     */
    public void fetch(){
        if(iGoodsView !=null && iGoodsModel!=null){
            iGoodsModel.loadGoodsData(new IGoodsModel.OnLoadListener() {
                @Override
                public void onComplete(List goods) {
                    ((IGoodsView)iGoodsView.get()).showGoodsView(goods);
                }

                @Override
                public void onError(String msg) {

                }
            });
        }
    }

    @Override
    void onCreateX(LifecycleOwner owner) {
        super.onCreateX(owner);
        Log.i("xiaosanye","执行了create");
    }

    @Override
    void onDestory(LifecycleOwner owner) {
        super.onDestory(owner);
        Log.i("xiaosanye","执行了destroy");
    }
}

结果打印

2020-03-28 13:50:49.034 16007-16007/com.example.mvp/xiaosanye: 执行了create
2020-03-28 13:50:51.550 16007-16007/com.example.mvp/xiaosanye: 执行了destroy

注意:本文用的是mvp的架构,对mvp不了解的小伙伴请自行谷歌

打印结果和我们预期的也是一样的,到这里,我们Lifecycles的基本用法讲完了,那么Lifecycles是怎么实现监听生命周期变化的呢?其实内部和glide的生命周期监听也是类似的,其实就是在当前Activity或者fragment中绑定一个空的fragment来实现监听的。

Lifecycles源码分析

我们上面说过Support Library 26.1.0 及更高版本中的 Activity 已经实现 LifecycleOwner接口,所以先找实现LifecycleOwner接口的Activity的父类

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

我们先进入接口LifecycleOwner看看

/**
 * A class that has an Android lifecycle. These events can be used by custom components to
 * handle lifecycle changes without implementing any code inside the Activity or the Fragment.
 *
 * @see Lifecycle
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

我们发现里面就一个Lifecycle变量声明的方法getLifecycle,所有我们直接进入Lifecycle类,Lifecycle是个抽象类,我们查看里面的方法和变量

image.png

我们看到有Event,它里面包含了生命周期的一些事件的枚举,然后是State,它里面是一些状态的枚举。
构成 Android Activity 生命周期的状态和事件

您可以将状态State看作图中的节点,将事件Event看作这些节点之间的边,比如你执行ON_CREATE事件的时候,你的状态就会从INITIALIZED变为CREATED。
还有addObserver添加和removeObserver删除观察者的方法,还有一个getCurrentState获取当前状态的方法,我们现进入addObserver方法看下

  @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

首先会获得初始状态值,如果是第一次进入肯定不等于DESTROYED,所以初始状态会是INITIALIZED,再把这个状态initialState和observer观察者放入ObserverWithState类型的变量statefulObserver里,最后再把statefulObserver和observer放进一个Map数组里mObserverMap,addObserver我们先看到这一步,因为再看下去我怕你们会懵逼,所以我们先直接到ComponentActivity的onCreate方法看

/**
     * {@inheritDoc}
     *
     * If your ComponentActivity is annotated with {@link ContentView}, this will
     * call {@link #setContentView(int)} for you.
     */
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if (mContentLayoutId != 0) {
            setContentView(mContentLayoutId);
        }
    }

我看进入ReportFragment.injectIfNeededIn(this)的方法里看下

    public static void injectIfNeededIn(Activity activity) {
        // ProcessLifecycleOwner should always correctly work and some activities may not extend
        // FragmentActivity from support lib, so we use framework fragments for activities
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

我们看到injectIfNeededIn的作用就是把ReportFragment通过beginTransaction().add添加到Fragment管理器manager里面,我们再进入ReportFragment里看看

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    public static void injectIfNeededIn(Activity activity) {
        // ProcessLifecycleOwner should always correctly work and some activities may not extend
        // FragmentActivity from support lib, so we use framework fragments for activities
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }

    private ActivityInitializationListener mProcessListener;

    private void dispatchCreate(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onCreate();
        }
    }

    private void dispatchStart(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onStart();
        }
    }

    private void dispatchResume(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onResume();
        }
    }

    @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);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

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

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}

我们看到ReportFragment的生命周期里对应分发了Lifecycle里的那些枚举事件,所以activity生命周期发生变化的时候就会走ReportFragment的生命周期里的一些方法,所以我们再进入dispatch()方法

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

dispatch方法里前面就是判断了activity是否有实现LifecycleRegistryOwner接口或者是LifecycleOwner接口(LifecycleRegistryOwner其实也是派生于LifecycleOwner的),如果是的话就进入执行handleLifecycleEvent方法,

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

一开始先通过getStateAfter获取当前状态的下一个状态


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

看过前面那张状态和事件的枚举图现在来看这个getStateAfter方法就很好理解了把,例如如果你当前正在ON_CREATE或者ON_STOP,下一个状态就会走到CREATED状态。我们再把获得的下一个状态传到moveToState方法里,去真正移动到下一个状态


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

如果下一个状态和当前状态相同就直接返回,否则执行sync()同步操作,我们再进入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 newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

在看这个同步方法之前,我们再来理解下那张状态图,


构成 Android Activity 生命周期的状态和事件

我们知道我们的activity随着用户的操作,状态会不断的改变,状态改变就会遵循上面这张图,比如onCreate跑完,状态就会变成created,如果执行完onStart,状态就会从created变成started,执行完onResune状态就会从started变成resumed以此类推。我们在前面代码知道,我们的观察者刚刚进来的初始换状态是INITIALIZED状态,所以观察者的状态可能和我们的activity的状态不一样,所以sync方法就是来让观察者和activity的状态同步的,我们再看到代码,里面主要是两个方法backwardPass和forwardPass,一个是向前移动,一个是向后移动,
如果activity的状态是started,观察者的状态是created,那就要把观察者往后推;如果activity的状态是started,观察者的状态是resumed,那就要把观察者往前推。我们进入其中一个方法看看,我们进入backwardPass

 private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> descendingIterator =
                mObserverMap.descendingIterator();
        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();
            }
        }
    }

一开始就是拿到mObserverMap(所有观察者的map)的迭代器,然后循环每一个观察者,然后把被观察者lifecycleOwner和观察者的执行event 传入到dispatchEvent执行,我们进入dispatchEvent方法


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

我们发现dispatchEvent是静态内部类ObserverWithState其中的一个方法,ObserverWithState类还记得么?就是前面我们把所有观察者和状态存起来的类,
所以我们先看ObserverWithState的构造方法里的lifecycleEventObserver,我们发现lifecycleEventObserver最后都 return new ReflectiveGenericLifecycleObserver(object)到这里,所以我们直接进入

/**
 * An internal implementation of {@link LifecycleObserver} that relies on reflection.
 */
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}

  CallbackInfo getInfo(Class klass) {
        CallbackInfo existing = mCallbackMap.get(klass);
        if (existing != null) {
            return existing;
        }
        existing = createInfo(klass, null);
        return existing;
    }

  private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
        Class superclass = klass.getSuperclass();
        Map handlerToEvent = new HashMap<>();
        if (superclass != null) {
            CallbackInfo superInfo = getInfo(superclass);
            if (superInfo != null) {
                handlerToEvent.putAll(superInfo.mHandlerToEvent);
            }
        }

        Class[] interfaces = klass.getInterfaces();
        for (Class intrfc : interfaces) {
            for (Map.Entry entry : getInfo(
                    intrfc).mHandlerToEvent.entrySet()) {
                verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
            }
        }

        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            if (annotation == null) {
                continue;
            }
            hasLifecycleMethods = true;
            Class[] params = method.getParameterTypes();
            int callType = CALL_TYPE_NO_ARG;
            if (params.length > 0) {
                callType = CALL_TYPE_PROVIDER;
                if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
                    throw new IllegalArgumentException(
                            "invalid parameter type. Must be one and instanceof LifecycleOwner");
                }
            }
            Lifecycle.Event event = annotation.value();

            if (params.length > 1) {
                callType = CALL_TYPE_PROVIDER_WITH_EVENT;
                if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
                    throw new IllegalArgumentException(
                            "invalid parameter type. second arg must be an event");
                }
                if (event != Lifecycle.Event.ON_ANY) {
                    throw new IllegalArgumentException(
                            "Second arg is supported only for ON_ANY value");
                }
            }
            if (params.length > 2) {
                throw new IllegalArgumentException("cannot have more than 2 params");
            }
            MethodReference methodReference = new MethodReference(callType, method);
            verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
        }
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }

其实一步步追踪进去ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());就是通过反射拿到带有那些注解的方法, mInfo.invokeCallbacks(source, event, mWrapped);就是最后真正执行那些注解方法的地方。

至此,我们已经分析完Lifecycles全部源码的,了解了Lifecycles的实际具体执行过程。

总结:1、通过在被观察者的activity里套一个空的fragment来监听被观察者的生命周期,观察者实现LifecycleObserver然后通过注解获取一些和被观察者生命周期的一些监听方法,来实现观察者和被观察者的生命周期的统一。

2、一开始通过addObserver把观察者和它的初始状态放进一个数组里(因为观察者可能有好多个),然后在fragment的生命周期里会去调一个dispatch方法,把Event事件传进去,然后获取activity的下一个状态,(这个很好理解吧,因为随着用户的操作,actvity的状态是会不断改变的,比如你当前处于Created状态,如果用户操作了onCreate事件,actvity就从Created到达resumed状态了),然后会去同步观察者和activity的状态,然后去通过反射执行你注解了的方法,就可以在观察者里获取actvity的状态了

你可能感兴趣的:(Jetpack使用(一)Lifecycles核心原理)