Jetpack 是一套库、工具和指南的集合,并不是一个框架或者组件。Jetpack 包含与平台 API 解除捆绑的 androidx.* 软件包库。Android Jetpack 组件是库的集合,这些库是为协同工作而构建的,不过也可以单独采用,可全部使用,也可混合搭配!Lifecycle 就是 Android Jetpack 组件之一。
Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.
翻译过来就是:生命周期是一个类,它保存关于组件生命周期状态的信息(比如Activity 或者 Fragment),并允许其他对象观察这种状态。
在开发中,Activity 经常要持有通过接口通知其他类,告诉它自身的生命周期,而其他类只要实现接口,就能接收到相应的消息。而在 Activity 的生命周期的不同方法中需要去执行对应接口的方法。而通过 LifeCycle 就不用这么麻烦,具体实现如下:
这里只是个简单的 MVP,只实现 Presenter:
Presenter 对应的接口:
package cn.zzw.lifecycledemo.mvp;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
/**
* @author 鹭岛猥琐男
* @create 2019/10/23 20:27
*/
public interface IPresenter extends LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onActivityCreate();
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onActivityDestory();
}
在 IPresenter 接口中,继承 LifecycleObserver ,并且定义接收生命周期的方法,并且在方法的头部加上接收哪个生命周期的方法。
具体的 Presenter:
package cn.zzw.lifecycledemo.mvp;
import android.app.Activity;
import android.util.Log;
import androidx.lifecycle.LifecycleOwner;
/**
* @author 鹭岛猥琐男
* @create 2019/10/23 20:34
*/
public class ActivityPresenter implements IPresenter {
Activity mActivity;
public ActivityPresenter(Activity mActivity) {
this.mActivity = mActivity;
}
@Override
public void onActivityCreate() {
Log.e("zzw", "ActivityPresenter: onActivityCreate()");
}
@Override
public void onActivityDestory() {
Log.e("zzw", "ActivityPresenter: onActivityDestory()");
mActivity = null;
}
}
这里只是简单的打印log。
Activity 代码如下:
package cn.zzw.lifecycledemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import cn.zzw.lifecycledemo.mvp.ActivityPresenter;
import cn.zzw.lifecycledemo.mvp.IPresenter;
public class MainActivity extends AppCompatActivity {
private IPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPresenter =new ActivityPresenter(this);
getLifecycle().addObserver(mPresenter);
}
@Override
protected void onDestroy() {
super.onDestroy();
getLifecycle().removeObserver(mPresenter);
}
}
在此 Activity 中,oncreate 方法中创建了 Presenter 对象,调用方法 getLifecycle().addObserver(mPresenter),并将Presenter 作为参数传入。onDestroy方法中,调用 getLifecycle().removeObserver(mPresenter) 将 Presenter 移除。
结果:
2019-10-23 21:08:54.145 5987-5987/cn.zzw.lifecycledemo E/zzw: ActivityPresenter: onActivityCreate()
2019-10-23 21:08:58.144 5987-5987/cn.zzw.lifecycledemo E/zzw: ActivityPresenter: onActivityDestory()
当 Activity 启动后,onActivityCreate() 方法中的 log 会被打印,直到退出后,onActivityDestory() 方法中的 log 会被打印。
MainActivity 中的继承关系如下所示:
在 接口中 getLifecycle 的返回值是 LifeCycle 类,而LifeCycle 是一个抽象类,它的实现类是 LifecycleRegistry。在 ComponentActivity 中存在存在如下代码:
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
而 ReportFragment 中 injectIfNeededIn() 方法中,把 Activity 对象传入 ReportFragment 中,通过一个未设置布局的 Fragment 来分发生命周期事件:
public static void injectIfNeededIn(Activity activity) {
// ProcessLifecycleOwner should always correctly work and some activities may not extend
// FragmentActivity from support lib, so we use framework fragments for activities
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();
}
}
在 ReportFragment 的生命中,列举其中一个:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
在这里看到希望看到关于Lifecycle 相关的方法 dispatch(Lifecycle.Event.ON_CREATE):
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);
}
}
}
在这里,传入的 event 最终进入方法 handleLifecycleEvent() 中,这个方法是 LifecycleRegistry 类中的方法:
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;
}
接着看方法 sync():
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;
}
这里不细究方法做了什么,只看方法怎么走,两条路,一条是 backwardPass,一条是 forwardPass,以 forwardPass 为例子:
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry entry = ascendingIterator.next();
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();
}
}
}
通过 mObserverMap 最终获取到一个 ObserverWithState 类型的 observer 对象,并调用它的 dispatchEvent 进行事件分发。ObserverWithState 是 LifecycleRegistry 的一个静态内部类,而在Activity 中,调用的 addObserver 传入的就是 LifecycleObserver 类型的对象。
@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);
...
...
}
LifeCycle 可以将 Activity/Fragment 中的生命周期传递出去,可以省略掉很多代码,让代码更加简洁。但是通过分析,似乎在传递生命周期的时候,并没有方法来传递参数,未免有些遗憾。