JetPack架构---Lifecycle生命周期相关与原理

一、概念

Lifecycle是JetPack提供的生命周期感知型组件。这也是JetPack系列架构的一个主要基础组件。LiveData、ViewModel都与之相关。

Lifecycle常用于感知Activity、Fragment的生命周期。通过它可以编写与生命周期相关的解耦的代码。将Lifecycle传入某个类中,可以让该类与外部组件的生命周期关联。

二、使用示例

2-0:添加依赖

参照官网提示,添加具体依赖(点击查看)

2-1:定义一个观察者

//定义一个观察者
public class MyObserver implements LifecycleObserver {
    private static final String TAG = "MyObserver";

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void whenOnCreated(){
        Log.d(TAG, "生命周期OnCreated");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void whenOnResumed(){
        Log.d(TAG, "生命周期OnResumed");
    }
}

2-2:在Activity的onCreate中添加观察者

//添加观察者
getLifecycle().addObserver(new MyObserver());

以上操作后,自定义的观察者MyObserver即可在activity的生命周期变换时,感知具体变换,并打印日志。

 

三、Lifecycle相关类

Lifecycle的机制,本质上是观察者模式,包含被观察者LifecycleOwner,观察者LifecycleObserver。

(1)LifecycleObserver:是一个空方法接口,用于标识观察者。

(2)LifecycleOwner: 是一个接口,持有方法Lifecycle getLifecycle()。

         2-1:Lifecycle 是一个抽象类,该类含有addObserver、removeObserver等方法,以及生命周期的定义。

         2-2:LifecycleRegistry 是Lifecycle的具体实现类,含有mObserverMap这样存储LifecycleObserver的集合。

 

四、源码分析

以前面的示例为例,在Activity中为何可以直接使用getLifecycle()方法并添加观察者-addObserver。

4-1:被观察者的定义与实现

ComponentActivity实现了LifecycleOwner接口以及该接口下的getLifecycle()方法。

//(1)ComponentActivity 实现LifecycleOwner接口
public class ComponentActivity extends Activity implements LifecycleOwner ...

//(2)getLifecycle()方法实现,返回Lifecycle类型对象
@NonNull
@Override
public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
}


//--------以下备注mLifecycleRegistry的实现------------
//(3)中的mLifecycleRegistry实例。其中LifecycleRegistry的构造方法,传入了ComponentActivity的
//     实例(也即是LifecycleOwner的实例)
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);


//(4)构造参数中传入的LifecycleOwner对象,会用于生命周期变动时的通知。
public class LifecycleRegistry extends Lifecycle {
   ....
   public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
   }
   ...
}

假设前面创建的Activity名为MainActivity。因MainActivity都是默认继承AppCompatActivity,而AppCompatActivity继承至ComponentActivity。则MainActivity默认实现了LifecycleOwner接口,是一个被观察者对象。

4-2:观察者的添加

此时通过getLifecycle().addObserver(new MyObserver());添加具体观察者对象,内部流程如下:

在4-1中,有说明getLifecycle()的具体实现,返回了Lifecycle的实现对象mLifecycleRegistry。因此,getLifecycle().addObserver实际会在mLifecycleRegistry中,进行添加观察者。

//mObserverMap 是LifecycleRegistry中定义的一个Map集合,用于存储观察者
@Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        ....
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        ....
}

至此,被观察者与观察者已被定义与添加完成。具体什么时候触发观察者的回调?见4-3

4-3:观察者回调触发时机

还是接着看ComponentActivity的onCreate方法。

//(1)ComponentActivity的onCreate中,ReportFragment.injectIfNeededIn(this)。将本activity的实
//例传入到了ReportFragment中
public class ComponentActivity extends Activity implements
        LifecycleOwner,
        KeyEventDispatcher.Component {

    ....
    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //此处是重点。
        ReportFragment.injectIfNeededIn(this);
    }
 
    ....

}

//(2)injectIfNeededIn该方法是ReportFragment中的静态方法

public class ReportFragment extends Fragment {

    public static void injectIfNeededIn(Activity activity) {
        //此处创建了一个新的Fragment(ReportFragment)
        //如果FragmentManager中已有该Fragment,则不会重复创建

        // use a framework fragment to get the correct timing of Lifecycle events
        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();
        }
    }
}

//(3)因ReportFragment绑定了ComponentActivity。ReportFragment的生命周期可通过下面方式对外通知
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //onCreate事件
        dispatch(Lifecycle.Event.ON_CREATE);
    }

    @Override
    public void onStart() {
        super.onStart();
        //onStart事件
        dispatch(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        //onResume事件
        dispatch(Lifecycle.Event.ON_RESUME);
    }

    @Override
    public void onPause() {
        //onPause事件
        dispatch(Lifecycle.Event.ON_PAUSE);
    }

    @Override
    public void onStop() {
        //onStop事件
        dispatch(Lifecycle.Event.ON_STOP);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //onDestroy事件
        dispatch(Lifecycle.Event.ON_DESTROY);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

//(4)dispatch的具体实现如下

private void dispatch(@NonNull Lifecycle.Event event) {
        if (Build.VERSION.SDK_INT < 29) {
            //该注释说明以上路线只针对SDK_INT < 29的情况,大于29的情况,会从另一条路线走,暂不
            //分析,原理类似
            // Only dispatch events from ReportFragment on API levels prior
            // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
            // added in ReportFragment.injectIfNeededIn
            dispatch(getActivity(), event);
        }
}

//(5)dispatch(getActivity(), event)具体内容

static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        ...
        //此时会走到该逻辑
        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                //最终还是会到LifecycleRegistry中,执行handleLifecycleEvent方法
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

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

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

//(7)同步观察者与被观察者sync()
private void sync() {
      
        while (!isSynced()) {
           
            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);
            }
        }
        
    }

//(8)无论是backwardPass或者forwardPass方法,最终都调用:observer.dispatchEvent(...),用于回调
// 观察者
observer.dispatchEvent(lifecycleOwner, event);
 
//以上的observer是经过ObserverWithState封装的,是ObserverWithState中LifecycleEventObserver的
//实例。

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



//(9)-----------以下备注(8)中LifecycleEventObserver对象mLifecycleObserver的定义----------

9-1:mLifecycleObserver实例
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
9-2:lifecycleEventObserver(Object object)

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

9-3:FullLifecycleObserverAdapter

class FullLifecycleObserverAdapter implements LifecycleEventObserver {

    private final FullLifecycleObserver mFullLifecycleObserver;
    private final LifecycleEventObserver mLifecycleEventObserver;

    FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
            LifecycleEventObserver lifecycleEventObserver) {
        mFullLifecycleObserver = fullLifecycleObserver;
        mLifecycleEventObserver = lifecycleEventObserver;
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        ....
        //回调onStateChanged
        if (mLifecycleEventObserver != null) {
            mLifecycleEventObserver.onStateChanged(source, event);
        }
    }
}





以上是Lifecycle的源码流程梳理。

Lifecycle做为一个android提供的生命周期组件,除了以上介绍的用法外,还可以用于传入你需要生命周期的自定义组件中。管理组件的资源释放、数据处理、UI是否刷新等,有助于整体的稳定性、减少内存泄漏、代码简洁化等。

 

你可能感兴趣的:(Android技巧)