Google 推出的 Jetpack组件架构 其对开发编码生态的统一,从这套组件开发,避免开发中常遇到的诸多问题。对代码的开发逻辑与ViewUI层的实现进行解耦,从模型驱动转向为数据驱动。
Lifecycle的使用
Lifecycle是一个具有持有组件生命周期状态的组件类,并且允许其他对象注册观察状态。
几个重要的对象(观察者模式):
- LifecycleOwner
- LifecycleObserver
- LifecycleOwner.add( LifecycleObserver )
实现 LifecycleOwner
在**Activity、Fragmen **其父类间接或者直接帮忙实现LifecycleOwner
,不然需要在监听的活动页面自动实现,例如低版本的sdk
Activity
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
// ...
}
Fragment
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner, SavedStateRegistryOwner {
// ...
}
当旧版本需要自己实现 LifecycleRegistry 手动在生命周期进行通知事件
public class MainActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
mLifecycleRegistry.addObserver(new TestObserver());
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
@Override
public void onStart() {
super.onStart();
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
super.onPause();
}
@Override
public void onStop() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
super.onStop();
}
@Override
public void onDestroy() {
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
super.onDestroy();
}
}
MainActivity 实现注册
package com.example.lifecycle
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
val TAG = javaClass.name;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.e(TAG, "MainActivity: onCreate")
initMain()
}
fun initMain() {
val preasent = BasePresenterLifecycle(); //获取观察者对象实例
lifecycle.addObserver(preasent) // lifecycle:默认实现了被观察者 add注册(观察者)
}
}
业务Present
package com.example.lifecycle
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
class BasePresenterLifecycle : LifecycleObserver {
private val TAG = this.javaClass.canonicalName;
//通过注解的方式接收相关生命周期,方法名可以自定义
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Log.e(TAG, "onCreate: Lifecycle")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
Log.e(TAG, "onStart: Lifecycle")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
Log.e(TAG, "onResume: Lifecycle")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
Log.e(TAG, "onPause: Lifecycle")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
Log.e(TAG, "onStop: Lifecycle")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
Log.e(TAG, "onDestroy: Lifecycle")
}
//每次生命周执行前先执行一次
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onAny() {
Log.e(TAG, "onAny: Lifecycle 执行")
}
}
运行启动后看到的日志输出:
源码分析
-
执行流程时序图
- 源码ComponentActivity中在onCreate注册感知生命周期:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this); //注册生命周期感知
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
- ReportFragment 注册一个无UI的Fragmen
- dispatch(Lifecycle.Event.ON_XXX);
package androidx.lifecycle;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import androidx.annotation.RestrictTo;
@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";
public static void injectIfNeededIn(Activity activity) {
//通过一个没有UI的Fragmen进行管理
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//注册监听器
dispatchCreate(mProcessListener);
//分发onCrate事件
dispatch(Lifecycle.Event.ON_CREATE);
}
//....
@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);
}
}
}
}
- LifecycleRegistry
// 核心逻辑机制,状态机的同步
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
//得到Activity的生命状态
State next = getStateAfter(event);
//注册的组件观察者Observe对应更改相应的状态
moveToState(next);
}
//状态机存放当期的状态, 判断逻辑
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);
}
// enum State 枚举
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;
}
//Activity 生命周期
enum Event
//组件感知的生命周期
enum State
- 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;
//Activity 销毁 回推
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
//Activity 显示 正向推
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
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();
//迭代注册相应的Observe
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
//Observe@函数方法
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();
}
}
}
获取class执行相应的事件,通过CLass反射机制
- onStateChanged(owner, event);
- invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target)
- handlers.get(i).invokeCallback(source, event, mWrapped);
- Method.invoke(Object obj, Object... args)
总结梳理
Lifecycle 在 onCreate 中注入 ReportFragment 来感知发生命周期;
Lifecycle 对生命周期的抽象,定义了生命周期事件以及状态,通过它可以获取当前的生命周期状态
LifecycleOwner 一个拥有生命周期的组件,可以自己定义,目前版本已经Api实现好了
LifecycleRegistry 是Lifecycle的实现类,它负责接管生命周期事件,同时也负责Observer` 的注册以及通知
ObserverWithState 是 Observer 的一个封装类,通过 ReflectiveGenericLifecycleObserve 调用了注解修饰的方法
LifecycleObserver Lifecycle 的观察者,可以接受生命周期回调
ReflectiveGenericLifecycleObserver 它存储了我们在 Observer 里注解的方法,通过反射的方式调用对应的方法