Jetpack--Lifecycle使用和源码解析

Jetpack--Lifecycle使用和源码解析,第1张

Lifecycle 是什么?
Google官方解释Lifecycle:
生命周期感知型组件可执行 *** 作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。
说白了就是可以监听Activity/Fragment的生命周期。

古老的生命周期监听做法:
class MainActivity : AppCompatActivity() {
    private var mainActivityLifeListener : MainActivityLifeListener ?= null
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    mainActivityLifeListener = MainActivityLifeListener();
}

override fun onResume() {
    super.onResume()
    mainActivityLifeListener?.onResume()
}

override fun onDestroy() {
    super.onDestroy()
    mainActivityLifeListener?.onDestroy()
}

}



class MainActivityLifeListener {
    private val TAG = "MainActivityLifeListener"

    fun onResume() = Log.d(TAG,"onResume ...");

    fun onDestroy() = Log.d(TAG,"onDestroy ...");
}

上面的实例代码实现监听MainActivity的生命周期,但是存在以下问题:

1.若需要监听的Activity/Fragment 比较多,就需要多次重复的调用MainActivityLifeListener.kt中的方法,而且容易出现遗漏

2.被监听的Activity/Fragment 代码冗余

采用Lifecycle监听生命周期

方法一:继承LifecycleObserver的自定义监听器实现

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //继承LifecycleObserver的自定义监听器实现
    lifecycle.addObserver(Myoberver())
    }
}
class Myoberver:LifecycleObserver {

    private val TAG = "Myoberver"

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connect() = Log.d(TAG,"vivivd Onresume")

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun disconnect() = Log.d(TAG,"vivivd Ondestroy")

}

方法二:内部类继承LifecycleObserver

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //内部类 实现监听
    lifecycle.addObserver(Myoberver())
}

inner class Myoberver:LifecycleObserver{
    private val TAG = "Myoberver"

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connect() = Log.d(TAG,"vivivd Onresume")

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun disconnect() = Log.d(TAG,"vivivd Ondestroy")
    }
}

方法三:采用接口继承LifecycleObserver

interface IPresenter :LifecycleObserver{

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun connect()

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun disconnect()
}
class MyObserver :IPresenter {
    private val TAG ="MyObserver"
    override fun connect() {
        Log.d(TAG, "connect: vivid ")
    }

    override fun disconnect() {
        Log.d(TAG, "disconnect: vivid ")
    }
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //使用接口继承LifecycleObserver 实现接口从而实现监听
    lifecycle.addObserver(MyObserver())
    }

}

通过实例代码可以看出Lifecycle采用了观察者设计模式,简单来说就是MyObserver长了眼睛一直盯着MainActivity,只要MainActivity的生命周期发生变化MyObserver就可以感知到。

但是MyObserver是怎么感知MainActivity的生命周期?

不管采用上述那种方式,最终都要执行:

lifecycle.addObserver(MyObserver())

问题1:lifecycle是怎么来的?

问题2:addObserver做了什么?

问题3:怎么实现监听MainActivity生命周期?

MainActivity-->AppCompatActivity-->FragmentActivity-->ComponentActivity

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
    ContextAware,
    LifecycleOwner,
    ViewModelStoreOwner,
    HasDefaultViewModelProviderFactory,
    SavedStateRegistryOwner,
    OnBackPressedDispatcherOwner,
    ActivityResultRegistryOwner,
    ActivityResultCaller {
    ....
}

public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
    @NonNull
    Lifecycle getLifecycle();
}

问题1答:

可以看出MainActivity继承了ComponentActivity,而ComponentActivity实现了LifecycleOwner 接口

所以lifecycle是从LifecycleOwner接口中的getLifecycle方法获取。

问题2答:

addObserver(MyObserver())执行(两眼一闭,只关心observer的去向)

LifecycleRegistry.java实现如下:

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

    ObserverWithState(LifecycleObserver observer, State initialState) {
    mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
    mState = initialState;
}
//注意:上面参数都是Observer 这里往后都转成了Object
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
......

    return new ReflectiveGenericLifecycleObserver(object);

}
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

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

最后mInfo 拿到了我们传进来的MyObserver的字节码内容。至此无法继续往下查看

所以addObserver执行会让ReflectiveGenericLifecycleObserver.java文件中的mInfo拿到我们实际的字节码文件。

问题3答:

重新打开ComponentActivity.java中的onCreate()

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    // Restore the Saved State first so that it is available to
    // OnContextAvailableListener instances
    mSavedStateRegistryController.performRestore(savedInstanceState);
    mContextAwareHelper.dispatchOnContextAvailable(this);
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);//借鉴Glide实现原理
    if (mContentLayoutId != 0) {
        setContentView(mContentLayoutId);
    }
}
public static void injectIfNeededIn(Activity activity) {
    if (Build.VERSION.SDK_INT >= 29) {
        // On API 29+, we can register for the correct Lifecycle callbacks directly
        LifecycleCallbacks.registerIn(activity);
    }
// Prior to API 29 and to maintain compatibility with older versions of
// ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
// need to support activities that don't extend from FragmentActivity from support lib),
// 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();
    }
}

其实就是在MainActivity上面覆盖了一层空白的ReportFragment,二者进行了绑定,所以可以感知到MainActivity的生命周期。

ReportFragment和MainActivity绑定了,那到底是怎么实现MainActivity生命周期监听的?

既然二者已经绑定了,那么MainActivity进入了onResume,同样ReportFragment也会进入onResume

@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    dispatch(Lifecycle.Event.ON_RESUME);
}

上面通过dispatch分发了Lidecycle的ON_RESUME事件。

private void dispatch(@NonNull Lifecycle.Event event) {
    if (Build.VERSION.SDK_INT < 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);
    }
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
    //SDK > 29
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

//SDK < 29 
//activity 就是MainActivity,上面追了MainActivity实现了LifecycleOwner
if (activity instanceof LifecycleOwner) {
    Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    enforceMainThreadIfNeeded("handleLifecycleEvent");
    moveToState(event.getTargetState()); //这里是关键点
    //moveToState的参数是根据event事件转化为对应的State
    //也就是说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;
}

 handleLifecycleEvent中执行moveToState但参数是通过Lifecycle.Event事件转化而来,

具体如下:

@NonNull
public State getTargetState() {
    switch (this) {
        case ON_CREATE:
        case ON_STOP:
            return State.CREATED;
        case ON_START:
        case ON_PAUSE:
            return State.STARTED;
        case ON_RESUME:
            return State.RESUMED;
        case ON_DESTROY:
            return State.DESTROYED;
        case ON_ANY:
            break;
    }
    throw new IllegalArgumentException(this + " has no target state");
}

接下来看一下具体State有那些状态

public enum State{
    DESTROTED,
    INIRIALIZED,
    CREATED,
    STARTED,
    RESUMED;
......

}

这里一共6种生命周期5种状态,先由Lifecycle.Event事件推动状态,后由状态调整对应的Lifecycle.Event 

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); //关键步骤
    }
    Map.Entry newest = mObserverMap.newest();
    if (!mNewEventOccurred && newest != null
    && mState.compareTo(newest.getValue().mState) > 0) {
        forwardPass(lifecycleOwner);//关键步骤
    }
    }
    mNewEventOccurred = false;
}

 可以看出是通过被观察者的状态和观察者当前的状态的枚举大小来判断是执行backwardPass/forwardPass方法。

private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator> ascendingIterator =
    mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Map.Entry entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
    while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
        && mObserverMap.contains(entry.getKey()))) {
    pushParentState(observer.mState);
    final Event event = Event.upFrom(observer.mState);//通过状态获取对应的事件
    if (event == null) {
        throw new IllegalStateException("no event up from " + observer.mState);
    }
        observer.dispatchEvent(lifecycleOwner, event);//回调执行事件
        popParentState();
       }
    }
}
//LifecycleRegistry.java
void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = event.getTargetState();
    mState = min(mState, newState);
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}

 onStateChanged最终回到了问题2中的ReflectiveGenericLifecycleObserver.java文件

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(@NonNull LifecycleOwner source, @NonNull Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}

由于mInfo已经获取到了MyObserver.kt的字节码,所以通过反射执行对应的event事件的注解,从而执行对应的MyObserver.kt中的方法,这就是为什么MainActivity.kt中执行onResume(),MyObserver.kt可以感知到对应的onResume()。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/721948.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存