美文网首页
Android 架构组件 —— Lifecycle-aware

Android 架构组件 —— Lifecycle-aware

作者: 佐以言 | 来源:发表于2018-01-04 16:27 被阅读48次

    上篇文章主要介绍了Lifecycle-aware Components的使用方法,本文将对Lifecycle-aware Components的三大组件之一的Lifecycle进行分析。

    Talk is cheap. Show me the code

    添加Observer

    首先从添加Observer入口函数开始了解Lifecycle

    //SupportActivity.java
    public class SupportActivity extends Activity implements LifecycleOwner {
        ...
    
        private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    
        ...
    
        @Override
        public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
        }
    }
    
    //LifecycleRegistry.java
        @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);
    
            if (previous != null) {
                return;
            }
            LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
            if (lifecycleOwner == null) {
                // it is null we should be destroyed. Fallback quickly
                return;
            }
    
            ...
        }
    

    从上述代码可以看出:当我们调用addObserver()时,LifecycleRegistry将自定义的Observer封装为ObserverWithState类型再存储到mObserverMap中:

    static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;
    
        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }
    
        void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }
    }
    

    State用于存放当前Observer的状态,而传递进来的observer通过Lifecycling.getCallback(Object obj)被封装成了一个GenericLifecycleObserver对象:

    @NonNull
    static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }
    
        if (object instanceof GenericLifecycleObserver) {
            return (GenericLifecycleObserver) object;
        }
    
        final Class<?> klass = object.getClass();
        //type 有两种类型:
        //GENERATED_CALLBACK -> 通过annotationProcessor生成的类(为对应类名后加上"__LifecycleAdapter"的类,在build/generated/source/apt下可以找到)
        //REFLECTIVE_CALLBACK -> 通过反射获取其中有包含生命周期感知的方法所生成的类(例如用Kotlin编写的代码,annotationProcessor无法自动生成对应类,只有运行时通过反射其中有`@OnLifecycleEvent`注解的方法进行获取)
        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);
    }
    

    在封装完Observer之后,addObserver会调用sync()方法将mObserverMap中所有observer的状态进行同步:

    private void sync() {
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                    + "new events from it.");
            return;
        }
        while (!isSynced()) {
            mNewEventOccurred = false;
            // 如果当前状态在mObserver的状态之前,则调用backwardPass同步所有observer状态
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            // 如果当前状态在mObserver的状态之后,则调用forwardPass同步所有observer状态
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }
    
    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 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 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);
    }
    

    至此,addObserver方法就完全结束,自定义Observer也被添加到Lifecycle中可以接收到生命周期变化。

    生命周期改变

    LifecycleRegistry中用于生命周期方法有两个markState(@NonNull State state)handleLifecycleEvent(@NonNull Lifecycle.Event event),但最终都调用了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()方法将mObserverMap中的observer状态同步到当前状态同时通知状态变更。

    生命周期变更实现方式

    在代码中,并没有手动调用两个生命周期变化函数,那在生命周期变化时是什么触发了变更通知呢?
    反编译项目后发现在Androidmanifest文件中多了如下一个tag(在build/outputs/logs/manifest-merge-**-report.text中可以找到添加的代码):

    <provider
                android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
                android:exported="false"
                android:multiprocess="true"
                android:authorities="com.xu.crease.archtest.lifecycle-trojan" />
    

    根据类名找到对应的类:

    //ProcessLifecycleOwnerInitializer.java
    public class ProcessLifecycleOwnerInitializer extends ContentProvider {
        @Override
        public boolean onCreate() {
            //Activity生命周期监听者
            LifecycleDispatcher.init(getContext());
            //当前应用的生命周期监听者
            ProcessLifecycleOwner.init(getContext());
            return true;
        }
    
        ...
    }
    //LifecycleDispatcher.java
    class LifecycleDispatcher {
        ...
    
        static void init(Context context) {
            if (sInitialized.getAndSet(true)) {
                return;
            }
            ((Application) context.getApplicationContext())
                    .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
        }
    
        @SuppressWarnings("WeakerAccess")
        @VisibleForTesting
        static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
            private final FragmentCallback mFragmentCallback;
    
            DispatcherActivityCallback() {
                mFragmentCallback = new FragmentCallback();
            }
    
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if (activity instanceof FragmentActivity) {
                    ((FragmentActivity) activity).getSupportFragmentManager()
                            .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
                }
                ReportFragment.injectIfNeededIn(activity);
            }
    
            @Override
            public void onActivityStopped(Activity activity) {
                if (activity instanceof FragmentActivity) {
                    markState((FragmentActivity) activity, CREATED);
                }
            }
    
            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                if (activity instanceof FragmentActivity) {
                    markState((FragmentActivity) activity, CREATED);
                }
            }
        }
    
        ...
    
        private static void markState(FragmentManager manager, State state) {
            Collection<Fragment> fragments = manager.getFragments();
            if (fragments == null) {
                return;
            }
            for (Fragment fragment : fragments) {
                if (fragment == null) {
                    continue;
                }
                markStateIn(fragment, state);
                if (fragment.isAdded()) {
                    markState(fragment.getChildFragmentManager(), state);
                }
            }
        }
    
        private static void markStateIn(Object object, State state) {
            if (object instanceof LifecycleRegistryOwner) {
                LifecycleRegistry registry = ((LifecycleRegistryOwner) object).getLifecycle();
                registry.markState(state);
            }
        }
    
        private static void markState(FragmentActivity activity, State state) {
            markStateIn(activity, state);
            markState(activity.getSupportFragmentManager(), state);
        }
    
        private static void dispatchIfLifecycleOwner(Fragment fragment, Lifecycle.Event event) {
            if (fragment instanceof LifecycleRegistryOwner) {
                ((LifecycleRegistryOwner) fragment).getLifecycle().handleLifecycleEvent(event);
            }
        }
    
        @SuppressWarnings("WeakerAccess")
        @VisibleForTesting
        static class FragmentCallback extends FragmentManager.FragmentLifecycleCallbacks {
    
            @Override
            public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
                dispatchIfLifecycleOwner(f, ON_CREATE);
    
                if (!(f instanceof LifecycleRegistryOwner)) {
                    return;
                }
    
                if (f.getChildFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
                    f.getChildFragmentManager().beginTransaction().add(new DestructionReportFragment(),
                            REPORT_FRAGMENT_TAG).commit();
                }
            }
    
            @Override
            public void onFragmentStarted(FragmentManager fm, Fragment f) {
                dispatchIfLifecycleOwner(f, ON_START);
            }
    
            @Override
            public void onFragmentResumed(FragmentManager fm, Fragment f) {
                dispatchIfLifecycleOwner(f, ON_RESUME);
            }
        }
    }
    

    首先设置Activity的生命周期监听器DispatcherActivityCallback,若Activity继承自v4包中的FragmentActivity则把Fragment生命周期监听器同时注册。这样在两者生命周期有变化的同时,通过调用markStatemarkStateIn方法对所有监听器发出生命周期变化通知,从而达到对全局生命周期的控制。

    public class ProcessLifecycleOwner implements LifecycleOwner {
    
        @VisibleForTesting
        static final long TIMEOUT_MS = 700; //mls
    
        // ground truth counters
        private int mStartedCounter = 0;
        private int mResumedCounter = 0;
    
        private boolean mPauseSent = true;
        private boolean mStopSent = true;
    
        private Handler mHandler;
        private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
    
        private Runnable mDelayedPauseRunnable = new Runnable() {
            @Override
            public void run() {
                dispatchPauseIfNeeded();
                dispatchStopIfNeeded();
            }
        };
    
        private ActivityInitializationListener mInitializationListener =
                new ActivityInitializationListener() {
                    @Override
                    public void onCreate() {
                    }
    
                    @Override
                    public void onStart() {
                        activityStarted();
                    }
    
                    @Override
                    public void onResume() {
                        activityResumed();
                    }
                };
    
        private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
    
        /**
         * The LifecycleOwner for the whole application process. Note that if your application
         * has multiple processes, this provider does not know about other processes.
         *
         * @return {@link LifecycleOwner} for the whole application.
         */
        public static LifecycleOwner get() {
            return sInstance;
        }
    
        static void init(Context context) {
            sInstance.attach(context);
        }
    
        void activityStarted() {
            mStartedCounter++;
            if (mStartedCounter == 1 && mStopSent) {
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
                mStopSent = false;
            }
        }
    
        void activityResumed() {
            mResumedCounter++;
            if (mResumedCounter == 1) {
                if (mPauseSent) {
                    mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
                    mPauseSent = false;
                } else {
                    mHandler.removeCallbacks(mDelayedPauseRunnable);
                }
            }
        }
    
        void activityPaused() {
            mResumedCounter--;
            if (mResumedCounter == 0) {
                mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
            }
        }
    
        void activityStopped() {
            mStartedCounter--;
            dispatchStopIfNeeded();
        }
    
        private void dispatchPauseIfNeeded() {
            if (mResumedCounter == 0) {
                mPauseSent = true;
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
            }
        }
    
        private void dispatchStopIfNeeded() {
            if (mStartedCounter == 0 && mPauseSent) {
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
                mStopSent = true;
            }
        }
    
        private ProcessLifecycleOwner() {
        }
    
        void attach(Context context) {
            mHandler = new Handler();
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
            Application app = (Application) context.getApplicationContext();
            app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
                @Override
                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                    ReportFragment.get(activity).setProcessListener(mInitializationListener);
                }
    
                @Override
                public void onActivityPaused(Activity activity) {
                    activityPaused();
                }
    
                @Override
                public void onActivityStopped(Activity activity) {
                    activityStopped();
                }
            });
        }
    
        @NonNull
        @Override
        public Lifecycle getLifecycle() {
            return mRegistry;
        }
    }
    

    ProcessLifecycleOwner的作用主要是通过前面LifecycleDispatcher注入的ReportFragment准确获取Activity启动数量从而通知observer变化(使用Fragment原因是因为在Activity创建完成之后才会对Fragment进行创建,销毁之前会现将Fragment销毁来保证Activity数目的正确性)
    同理,同样具有LifecycleService类来协助Service处理中生命周期变化,此处略过。

    小结

    通过如上分析可以看出,通过LifecycleDispatcherProcessLifecycleOwner产生通知,通过LifecycleRegistry将对应生命周期变化告知对应监听者从而达到生命周期再监听者类中的统一。

    代码源自android.arch.lifecycle1.0.0版本
    参考:chaosleong的博客

    相关文章

      网友评论

          本文标题:Android 架构组件 —— Lifecycle-aware

          本文链接:https://www.haomeiwen.com/subject/vxtrvxtx.html