Lifecycle简介
Lifecycle是一个生命周期感知组件,一般用来响应Activity、Fragment等组件的生命周期变化,并将变化通知到已注册的观察者。有助于更好地组织代码,让代码逻辑符合生命周期规范,减少内存泄漏,增强稳定性。
使用方法
1、在app或者相关module下的build.gradle文件下添加如下依赖:
- androidX项目:直接使用
- 非androidX项目:
//运行时
implementation "android.arch.lifecycle:runtime:1.1.1"
// 编译期
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
2、生命周期观察者组件实现LifecycleObserver接口
public class LocationUtil implements LifecycleObserver {
private static final String TAG = "LocationUtil";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void createLocation(){
Log.d(TAG,"lifecycle:onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void startLocation(){
Log.d(TAG,"lifecycle:onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void resumeLocation(){
Log.d(TAG,"lifecycle:onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void pauseLocation(){
Log.d(TAG,"lifecycle:onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void stopLocation(){
Log.d(TAG,"lifecycle:onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void destoryLocation(){
Log.d(TAG,"lifecycle:onDestory");
}
}
3、将组件添加到Lifecycle的观察者列表
-
假如你使用新版本的AppcompatActivity(>26.1.0)[我使用的是27.1.1],因为AppcompatActivity继承的ComponentActivity实现了LifecycleOwner接口,所以写法如下:
public class LifeCycleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_life_cycle);
getLifecycle().addObserver(new LocationUtil());
}
}
如此,LocationUtil便可以关联到Activity的生命周期
- AppcompatActivity<26.1.0,这种情况下也可以自己实现LifecycleOwner接口:
1、实现LifecycleOwner 接口的方法:getLifecycle()
2、注册Lifecycle new LifecycleRegistry(this)
3、在Activity生命周期函数中分发事件
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();
}
}
源码分析
Lifecycle相关类图:
回顾LocationUtil代码:
public class LocationUtil implements LifecycleObserver {
private static final String TAG = "LocationUtil";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void createLocation(){
Log.d(TAG,"lifecycle:onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void startLocation(){
Log.d(TAG,"lifecycle:onStart");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void resumeLocation(){
Log.d(TAG,"lifecycle:onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void pauseLocation(){
Log.d(TAG,"lifecycle:onPause");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void stopLocation(){
Log.d(TAG,"lifecycle:onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void destoryLocation(){
Log.d(TAG,"lifecycle:onDestory");
}
}
可以很清楚地知道Lifecycle是通过@OnLifecycleEvent(参数)注解来关联生命周期的。
我们从引用代码处出发:
public class LifeCycleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_life_cycle);
getLifecycle().addObserver(new LocationUtil());
}
}
发现仅仅一行getLifecycle().addObserver(new LocationUtil());代码。从这行代码我们可以知道Lifecycle使用了观察者模式,通过通过关联生命周期通知订阅的观察者。那么这行代码是如何使Lifecycle关联上Activity的生命周期的呢?
带着这个疑问,我们查看getLifecycle()的源码:
ComponentActivity(AppCompatActivity的父类)
-----------------------------
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
获取一个mLifecycleRegistry实例
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry是LifecycleRegistry类的一个实例,
查看ComponentActivity的生命周期onCreate方法:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
继续查看 ReportFragment.injectIfNeededIn(this):
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();
}
}
发现injectIfNeededIn()方法其实就是给当前Activity添加一个Fragment,如此ReportFragment便能感知到当前Activity的生命周期。
再看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);
}
@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);
}
}
}
发现全都调用了dispatch()方法,而dispatch()方法则会判断activity是否实现了LifecycleOwner接口,如果实现了该接口接调用LifecycleRegister的handleLifecycleEvent(),这样生命周期的状态就会借由LifecycleRegister通知给各个LifecycleObserver从而调用其中对应Lifecycle.Event的方法。
这是Activity的声明周期感知,那么Fragment呢?看一下Fragment源码你会发现Fragment也实现了LifecycleOwner接口,也关联了一个LifecycleRegistry对象。
我们接着看handleLifecycleEvent()方法:
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
getStateAfter(event):
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);
}
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) {
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 newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
这里可以看到
如果ObserverWithState的state小于当前state,那么就调用forwardPass方法,
如果大于当前state,那么就调用backwardPass方法。
继续看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();
}
}
}
上面的observer其实是一个ObserverWithState对象,它是一个静态内部类
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);
mState = newState;
}
}
通过lifecycleEventObserver()方法获取mLifecycleObserver实例,调用onStateChanged(owner,event)通知实现了 LifecycleObserver的类,生命周期发生了变化。至此Lifecycle的原理实现就分析完了。
Q:为什么要使用ReportFragment?
我认为应该是为了降低侵入性,所以封装一个具有同样生命周期的Fragment来给Lifecycle分发生命周期事件。
这样只需要在onCreate方法里面调用ReportFragment.injectIfNeededIn(this);即可