Android的Lifecycle源码分析

1. 简介

很早就听说了Google的Lifecycle组件,因为项目没有使用过,所以并没有过多的接触。不过最近看到了一篇文章,其中的一条评论提到了LiveData。恰巧这两天工作内容不多,所以赶紧研究一波!
不过在看LiveData之前,我觉得还是先看下Lifecycle吧(Lifecycle更像是LiveData的基础,LiveData就不写了,感觉没啥东西)。

2. Lifecycle的简单介绍

Lifecycle的介绍,我们还是拿Google的官方文档作为参考吧。
Lifecycle主要解决的是业务和Activity/Fragment生命周期相关的问题。例如:我们在onResume()/onStart()中请求定位,在onPause()/onStop()中停止定位。那么我们一般的做法:

Google Simple Code
class MyLocationListener {
    public MyLocationListener(Context context, Callback callback) {
        // ...
    }

    void start() {
        // connect to system location service
    }

    void stop() {
        // disconnect from system location service
    }
}

class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    @Override
    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, (location) -> {
            // update UI
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        myLocationListener.start();
        // manage other components that need to respond
        // to the activity lifecycle
    }

    @Override
    public void onStop() {
        super.onStop();
        myLocationListener.stop();
        // manage other components that need to respond
        // to the activity lifecycle
    }
}

上面的代码虽然看起来还可以,但在真实的应用程序中,可能会有很多的方法都需要根据当前Activity/Fragment的生命周期来进行不同的操作。因此其生命周期方法中可能会被放置大量代码,例如onStart()onStop()中,这使得它们难以维护。因此Lifecycle应运而生!

3. Lifecycle的使用

Lifecycle已经发布了release版,所以其中的一些默认支持已经包含到了support-v7:26.1.0以及更高。
添加依赖:

implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"

使用方式1:实现LifecycleObserver接口,使用@OnLifecycleEvent注解,通过编译时注解生成代码:

public class MyLifecycleObserver implements LifecycleObserver {

    private static final String TAG = MyLifecycleObserver.class.getSimpleName();

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void start(LifecycleOwner lifecycleOwner) {
        Lifecycle.State currentState = lifecycleOwner.getLifecycle().getCurrentState();
        Log.d(TAG, "start: " + currentState);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void stop(LifecycleOwner lifecycleOwner) {
        Log.d(TAG, "stop: " + lifecycleOwner.getLifecycle().getCurrentState());
    }
}

Android的Lifecycle源码分析_第1张图片
APT生成的代码

使用方式2: 实现GenericLifecycleObserver接口,实现其onStateChanged方法

public class MyLifecycleObserver implements GenericLifecycleObserver {

    private static final String TAG = MyLifecycleObserver.class.getSimpleName();

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        Log.d(TAG, event.name());
    }
}

创建完成后,我们需要将其添加:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getLifecycle().addObserver(new MyLifecycleObserver());
    }
}

结果图:


img_e23db37d9a9a8dfbfdd62acbbf32a7e2.png
方法1

img_ccc485ccc1e7ae3734ddd1eec93d6b64.png
方法2

4. 源码分析

  1. Lifecycle的获取
    根据源码追踪我们可以看到Lifecycle是在SupportActivity中:
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
    return mLifecycleRegistry;
}

这里还有个挺重要的代码:

SupportActivity.java
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
}
ReportFragment.java
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();
    }
}

这里在Activity中添加了一个Fragment,至于作用,留到后面在讲。

  1. addObserver
    addObserver方法的话,还是简单来看吧:
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);
    ......
    // 对状态的修正,这里会对已经过去的状态进行分发。也就是说如果添加observer时状态已经改变,那么也会被通知到!
}

// 有状态的Observer
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;
    }
}

我们将实现的接口通过装饰者(我认为是这样)模式转成ObserverWithState对象,并将该对象添加到mObserverMap中。
ObserverWithState的构造方法中,有对我们传入的LifecycleObserver进行包装:

Lifecycling.java
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
    // 这里应该算第三种实现方式,然而FullLifecycleObserver不是public,所以不能使用
    if (object instanceof FullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }
    // 我们的第一种方式
    if (object instanceof GenericLifecycleObserver) {
        return (GenericLifecycleObserver) object;
    }
    // 通过注解生成的
    final Class klass = object.getClass();
    // 将生成的MyLifecycleObserver_LifecycleAdapter放到Map中
    int type = getObserverConstructorType(klass);
    if (type == GENERATED_CALLBACK) {
        List> 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);
}

根据我们传入的对象进行解析,最终返回结果为:GenericLifecycleObserver或者GenericLifecycleObserver的实现类。附获取生成MyLifecycleObserver_LifecycleAdapter代码:

// 通过名称获取
public static String getAdapterName(String className) {
    return className.replace(".", "_") + "_LifecycleAdapter";
}

最终通过Class.forName方式获得Class

  1. 事件分发
    Lifecycle的事件分发在ObserverWithState类中:
// 事件分发
void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = getStateAfter(event);
    mState = min(mState, newState);
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}

看下哪里调用了dispatchEvent方法:

Android的Lifecycle源码分析_第2张图片
调用

我们看这个方法,其中一个在 addObserver中调用,另外的两个都会通过 sync()方法调用:

// 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) {
        Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                + "new events from it.");
        return;
    }
    // 最新的状态和当前状态不一致,则需要进行状态修改
    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;
}
// 是否状态同步的
private boolean isSynced() {
    if (mObserverMap.size() == 0) {
        return true;
    }
    // 最新的和最后添加的Observer状态一致,并且当前的状态和最新状态一致,则已经同步了
    State eldestObserverState = mObserverMap.eldest().getValue().mState;
    State newestObserverState = mObserverMap.newest().getValue().mState;
    return eldestObserverState == newestObserverState && mState == newestObserverState;
}

这里的同步方法用于同步当前Observer的状态,如果最新的和最老的Observer的状态不一致或者当前的状态和最新的状态不一致时,那么需要进行状态同步。同步包括了向前同步向后同步
调用sync()方法一共就两处,一处在addObserver方法,另一处是moveToState方法,而调用moveToState方法也有两处:

@SuppressWarnings("WeakerAccess")
@MainThread
public void markState(@NonNull State state) {
    moveToState(state);
}

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

handleLifecycleEvent方法有很多处调用:

Android的Lifecycle源码分析_第3张图片
handleLifecycleEvent调用

看图的话,就可以知道 Fragment在不同的生命周期调用了 handleLifecycleEvent方法,随便看一个吧:
Android的Lifecycle源码分析_第4张图片
ON_CREATE

还记得上面说的 ReportFragment吗?这里也出现了,我们看下 ReportFragment到底做什么的:

// 调用Activity的
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);
        }
    }
}

// 生命周期
@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;
}

可以看到,ReportFragment只是作为一个中间层,通过它来分发各种事件!
由于篇幅原因(已经啰嗦了很多了),这里就不写LifecycleDispatcherProcessLifecycleOwner了,这两个通过自定义的内容提供者ProcessLifecycleOwnerInitializer进行初始化,并且通过registerActivityLifecycleCallbacksregisterFragmentLifecycleCallbacks注册统一的观察回调。有兴趣的话,自己看看吧。

5 总结

Lifecycle简单来说就是用于处理和生命周期相关的业务,其原理以及实现还是很简单的。当然了,项目中并没有使用到Lifecycle,所以实际应用效果怎样只能靠猜想了。

你可能感兴趣的:(Android的Lifecycle源码分析)