前言
从本篇开始我将跟大家一起来学习Android JetPack系列。JetPack是谷歌推出的一款非常非常重要且有用的库,它可以极大地提高开发者的开发效率,并且减少代码崩溃率和内存泄漏的问题。因此,学习并掌握JetPack系列是我们所有Android开发者的必修课,本文会跟大家一起学习一下关于Lifecycle的知识。
什么是Lifecycle
Lifecycle是一套专门用来感知Activity或Fragment生命周期变化的组件,当Activity或Fragment的生命周期发生的变化的时候,将会通知到Lifecycle的订阅者。这样我们可以把原本需要卸载Activity或Fragment的代码抽出来,使Activity或Fragment更加精简并且易于维护,也可以减少内存泄漏。
Lifecycle的工作流程
话不多说,直接开搞。如果我们想要使用JetPack组件,需要在Androidx的环境下,因为Androidx默认导入了JetPack所有的包,关于Androidx的好处我就不多说了,现在几乎各大主流App都迁移Androidx了。
Lifecycle的工作流程.jpg
在Androidx下的Actvity或Fragment内部有个Lifecycle对象,需要观察Actvity或Fragment的生命周期的观察者订阅Lifecycle,当Actvity或Fragment的生命周期发生变化时Lifecycle就对通知对所有订阅它的观察者,大体流程就是这样,很好理解。
Lifecycle的使用
关于Lifecycle的使用,一般有三种
实现LifecycleObserver接口
无论哪种使用方式,都需要跟Actvity或Fragment建立订阅关系,这里以Activity为例
(注:当前演示项目处于Androidx环境下)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLifecycle().addObserver(new MyLifeCycleObserver());//建立订阅关系
}
}
public class MyLifeCycleObserver implements LifecycleObserver {
private static final String TAG = "MyLifeCycleObserver";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
private void test1() {
Log.d(TAG, "onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void test2() {
Log.d(TAG, "onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private void test3() {
Log.d(TAG, "onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
private void test4() {
Log.d(TAG, "onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void test5() {
Log.d(TAG, "onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private void test6() {
Log.d(TAG, "onDestroy");
}
}
关于@OnLifecycleEvent注解我觉得不必多说,基本看一眼就知道啥意义,当Actvity或Fragment的生命周期发生变化的时候,对应注解标注的方法会得到调用,我们可以在这些方法中实现我们的业务代码。这种使用方式是我们最主流也是最常用的。
传入Lifecycle对象
public class MyLifeCycleObserver2 implements LifecycleObserver {
private Lifecycle lifecycle;
public MyLifeCycleObserver2(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
}
/**
* onStart()或onStart()以后执行
*/
private void doAfterStart() {
if (lifecycle != null) {
if (lifecycle.getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
//do something
}
}
}
}
一般这种情况是我们当前观察者需要根据Activity或Fragment的当前处于哪个生命周期并执行相应的操作,如代码中的例子所示,当Activity或Fragment处于onStart()以后的生命周期我们执行某些操作,相对来说用的情况比较少
自定义实现Lifecyele
这种情况就极少了,而且也不推荐大家使用
public class MyActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry lifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.markState(Lifecycle.State.CREATED);
lifecycleRegistry.addObserver(new MyLifeCycleObserver2());
}
@Override
public void onStart() {
super.onStart();
lifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
}
相当于给自己找麻烦,大家知道这种情况就好
Lifecycle的源码分析
知其然更知其所以然,源码分析是必不可少的。
刚才跟大家提到过Androidx环境下的Activity内部有一个现成的Lifecycle对象,我们直接从MainActivity里面跟到androidx.core.app.ComponentActivity
@RestrictTo(LIBRARY_GROUP_PREFIX)
public class ComponentActivity extends Activity implements
LifecycleOwner,
KeyEventDispatcher.Component {
......................
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
.................
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
这里我们只看跟Lifecycle相关的代码,ComponentActivity实现了LifecycleOwner重写getLifecycle()方法,这里返回的是LifecycleRegistry对象。LifecycleRegistry继承自Lifecycle,我们先看一下Lifecycle
public abstract class Lifecycle {
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
}
关键的就这三个方法,订阅、取消观察者以及获取当前状态
我们在看看Lifecycle的实现子类LifecycleRegistry
public class LifecycleRegistry extends Lifecycle {
//使用map来存储所有的订阅者以及订阅者的状态
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =new FastSafeIterableMap<>();
//当Activity或Fragment的生命周期发生变化时会调用该方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);//再跟到这个方法里面,这里会调用 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;
// no need to check eldest for nullability, because isSynced does it for us.
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);//
}
}
mNewEventOccurred = false;
}
这里再跟到backwardPass()或forwardPass()方法里面,这两个方法都是通知观察者相应生命周期变化,看一个就行
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();
}
}
}
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);//调用观察者的onStateChanged(),整个流程结束
mState = newState;
}
}
以上源码就是Lifecycle的核心内容,再看一张图会更加清晰
Lifecycle源码调用流程.jpg
关于Lifecycle内部的源码我们分析得差不多了,我们在看看Activity或者Fragment是如何通知Lifecycle生命周期变化的
先看Activity的,还是回到androidx.core.app.ComponentActivity中去
public class ComponentActivity extends Activity implements
LifecycleOwner,
KeyEventDispatcher.Component {
@SuppressLint("RestrictedApi")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);//这里注入了一个ReportFragment,跟进去
}
}
public class ReportFragment extends Fragment {
@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);
}
@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;
}
}
看到这里就非常清晰了,原来是ReportFragment帮助ComponentActivity完成的事件通知,点开dispatch(Lifecycle.Event event)看一下
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);
}
}
}
到这里就跟我们刚才的Lifecycle分析连在一起了,清晰明了
接着我们看看Fragment,这里点开androidx.fragment.app.Fragment,注意是Androidx下来的哦
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner {//这里同样实现了LifecycleOwner接口
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
void performCreate(Bundle savedInstanceState) {
..................
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
}
void performStart() {
......................
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
}
......................
}
这里源码就不全部放出来,在Fragment就更加简单,直接就是在生命周期被调用的时候调用mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event event)
源码分析到这里,你可能还有一个疑问,就是我们订阅者实现LifecycleObserver接口时并没有重写onStateChanged(),那么在最后调用mLifecycleObserver.onStateChanged(owner, event);我们的观察者中的方法是被通知到的呢?答案就在LifecycleRegistry的addObserver()方法中
public void addObserver(@NonNull LifecycleObserver observer) {
.......
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);//跟进去看一下
..........
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);//再跟进去
mState = initialState;
}
}
}
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
final Class<?> klass = object.getClass();
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> constructors =
sClassToAdapters.get(klass);
if (constructors.size() == 1) {
GeneratedAdapter generatedAdapter = createGeneratedAdapter(
constructors.get(0), object);
return new SingleGeneratedAdapterObserver(generatedAdapter);
}
GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
for (int i = 0; i < constructors.size(); i++) {
adapters[i] = createGeneratedAdapter(constructors.get(i), object);
}
return new CompositeGeneratedAdaptersObserver(adapters);
}
return new ReflectiveGenericLifecycleObserver(object);
}
我们传入的Observer对象会在Lifecycling的getCallback()方法中一顿加工操作一个GenericLifecycleObserver对象,而我们点开GenericLifecycleObserver会发现它定义了 void onStateChanged(LifecycleOwner source, Lifecycle.Event event)方法,也就是虽然我们自定义的LifeObserver没有实现onStateChanged(),但是Lifecycling最终帮我们实现了,至此,整个Lifecycle的工作流程串联完毕。
总结
本文给大家介绍了Lifecycle使用以及源码分析,相对来说Lifecycle是Jetpack推出的组件中比较简单,大家只要认真读一遍就能把知识完全掌握,在下一篇文章中我将给大家带来关于ViewModel的介绍。如果您觉得本文还不错,记得给个赞,谢谢~
网友评论