背景
从今天开始整理一些之前学过的jetpack的组件
基本概念
Livecycle
是一个表示android生命周期及状态的对象LivecycleOwner
(可以理解为被观察者) 用于连接有生命周期的对象,如activity,fragmentLivecycleObserver
(可以理解为观察者) 用于观察LifecycleOwner
可以解决什么问题
- 可以有效的避免内存泄漏和解决android生命周期的常见难题。
- Glide里面就是通过LifeCycle而免除了很多这样的代码:“onDestroy(){xxx.destroy()}”
使用
第一步(引入androidx相关的库,如果你还是support,迁移吧)
自己引入依赖(不是必须的),因为有很多默认的库都已经有相关依赖了,如果不确定,可以通过命令查看,或者干脆直接复制去依赖。
总之会merge的,具体原理可看我之前写的这篇文章红色字体部分—>看依赖关系命令:
dependencies {
implementation "androidx.lifecycle:lifecycle-runtime:2.0.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
implementation "androidx.lifecycle:lifecycle-common-java8:2.0.0"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0"
}
第二步(定义被观察者)
通过实现LifecycleOwner接口
如果是ComponentActivity
的子类则省略这一步,因为系统已经帮我们实现了。
第三步(定义观察者)
通过实现LifecycleObserver接口
通过注解在观察者类中定义需要监听的生命周期,通过注释可以看到观察者的类里面没有需要实现的方法,而是通过注解来的
/**
* Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
* {@link OnLifecycleEvent} annotated methods.
* <p>
* @see Lifecycle Lifecycle - for samples and usage patterns.
*/
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {
}
public class BasePresenter<T extends IBaseView> implements LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreateX(LifecycleOwner owner){
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onStartX(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onPause(LifecycleOwner owner) {
}
//你想监听哪个生命周期,就写个方法在方法上写上相关的状态,就可以得到回调
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestory(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onAny(LifecycleOwner owner) {
}
}
第三步(完成订阅)
在activity中
//添加观察者
getLifecycle().addObserver(presenter);
可以愉快的在业务处理完或者SDK需要创建、保存、销毁等时候对用户无感知的操作了,彻底丢掉类似以前百度或者友盟SDK等需要手动在某些生命周期里去写一些xxx.onXXX()。
原理
ComponentActivity
的onCreate()
中通过反射新建一个Fragment用于监听当前Activity的生命周期,这样对开发者而言,是无感知的,Glide也有相关操作。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
跟到ReportFragment
里面可以发现
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
而dispatch()中就是一连串的状态推导并通过onStateChanged
回调出来
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);
}
}
}
/**
* Sets the current state and notifies the observers.
* <p>
* Note that if the {@code currentState} is the same state as the last call to this method,
* calling this method has no effect.
*
* @param event The event that was received
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
xxxxx
sync();
xxxxxx
}
private void sync() {
while (!isSynced()) {
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
}
private void forwardPass(LifecycleOwner lifecycleOwner) {
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()))) {
xxxxxx
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
xxxxxx
}
}
}
void dispatchEvent(LifecycleOwner owner, Event event) {
xxxxxx
mLifecycleObserver.onStateChanged(owner, event);
xxxxxx
}
最后附上jett大佬画的生命周期和状态转换图:
具体代码逻辑是这样的:
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);
}