版权声明:本文已授权微信公众号:Android必修课,转载请申明出处
众所周知,Android凡是需要展示给用户看的,都包含着生命周期这个概念,例如Activity、Fragment、View等都与生命周期息息相关,在生命周期函数里,它们各自完成创建、渲染、销毁等工作。
但是一旦我们往某个生命周期函数中,加入我们自己的逻辑,若是处理不当,就有可能破坏其原有的生命周期,造成内存泄漏甚至应用崩溃等问题。
Android官方似乎也注意到了这一点,因此在Google IO 2018大会上,推出了Android Jetpack开发工具包,其中就包含了一个非常重要的生命周期组件,即本篇的主角-Lifecycle
本文篇幅较长,请大家耐心阅读。
Lifecycle是什么?
Lifecycle是一个生命周期感知组件,一般用来响应Activity、Fragment等组件的生命周期变化,并将变化通知到已注册的观察者。有助于更好地组织代码,让代码逻辑符合生命周期规范,减少内存泄漏,增强稳定性。
Lifecycle已经纳入新版本的AppCompatActivity和Fragment中了,并且Lifecycle还是Android Jetpack中其他两个组件LiveData和ViewModel的基础,意味着这个库可能将持续伴随着我们后续的开发,因此有什么理由不学习一番呢?
按照国际规范,我们先讲使用,后解析源码。
一、使用
1.添加依赖:
在app或者module目录下的build.gradle中,添加依赖:
dependencies {
......
implementation "android.arch.lifecycle:runtime:1.1.1"
implementation "android.arch.lifecycle:extensions:1.1.1"
// 如果你使用java8开发,可以添加这个依赖,里面只有一个类
implementation "android.arch.lifecycle:common-java8:1.1.1"
}
2.实现LifecycleObserver接口
public class Java7Observer implements LifecycleObserver {
private static final String TAG = Java7Observer.class.getSimpleName();
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() { Log.d(TAG, "onCreate"); }
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() { Log.d(TAG, "onStart"); }
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() { Log.d(TAG, "onResume"); }
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() { Log.d(TAG, "onPause"); }
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() { Log.d(TAG, "onStop"); }
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() { Log.d(TAG, "onDestroy"); }
}
首先,我们需要实现LifecycleObserver这个接口,然后在我们的方法上加上@OnLifecycleEvent注解,注解值表示该方法对应生命周期的哪个函数,这里我们把所有生命周期函数都加上了,并简单地打印了一句Log。
我想有人会问,为什么这个class要命名Java7Observer ? 没错,因为Java8中,官方推荐用另外一种方式:
public class Java8Observer implements DefaultLifecycleObserver {
private static final String TAG = Java8Observer.class.getSimpleName();
@Override
public void onCreate(@NonNull LifecycleOwner owner) { Log.d(TAG, "onCreate"); }
@Override
public void onStart(@NonNull LifecycleOwner owner) { Log.d(TAG, "onStart"); }
@Override
public void onResume(@NonNull LifecycleOwner owner) { Log.d(TAG, "onResume"); }
@Override
public void onPause(@NonNull LifecycleOwner owner) { Log.d(TAG, "onPause"); }
@Override
public void onStop(@NonNull LifecycleOwner owner) { Log.d(TAG, "onStop"); }
@Override
public void onDestroy(@NonNull LifecycleOwner owner) { Log.d(TAG, "onDestroy"); }
}
理由很简单,Lifecycle源码中有一段注释:
/* .....
* </pre>
* If you use <b>Java 7 Language</b>, Lifecycle events are observed using annotations.
* Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between
* {@link DefaultLifecycleObserver} and annotations,
* you must always prefer {@code DefaultLifecycleObserver}.
* <pre>
* ......
*/
翻译一下就是:“如果你丫的用的是java7,那你就用注解呗,但是我告诉你,一旦java8上位了,你那些注解就过时了,我劝你最好用DefaultLifecycleObserver”
3.将LifecycleObserver添加到Lifecycle的观察者列表
如果你使用新版本的AppcompatActivity(>26.1.0),可以这么写:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 直接调用getLifecycle(),添加Observer
getLifecycle().addObserver(new Java7Observer());
getLifecycle().addObserver(new Java8Observer());
}
}
如果你的AppCompatActivity没有更新到最新,那么你需要自实现LifecycleOwner接口,并在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();
}
}
ok,完事儿了,咱们跑起来看一哈,已经成功和生命周期关联上了。
能举个熟悉点的例子吗?
MVP想必大家都用过,或者听说过,View层通过Presenter层和Model层进行通信,因此Presenter层如果做了什么超出View生命周期的事,又没有及时释放内存,就会造成内存泄漏。
所以,原来的Presenter,为了响应生命周期,我们可能会这么写:
先定义所有的生命周期函数
public class MainPresenter {
public void onCreate() { }
public void onStart() { }
public void onResume() { }
public void onPause() { }
public void onStop() { }
public void onDestroy() { }
}
然后再与Activity生命周期一一绑定,如果有多个类似的需要响应生命周期的类,Activity的生命周期函数就会变得非常臃肿
public class MainActivity extends AppCompatActivity {
private MainPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPresenter = new MainPresenter();
mPresenter.onCreate();
}
@Override
protected void onResume() {
super.onResume();
mPresenter.onCreate();
// VideoPlayer.onResume();
// ...
}
@Override
protected void onStart() {
super.onStart();
mPresenter.onStart();
// VideoPlayer.onStart();
// ...
}
@Override
protected void onPause() {
super.onPause();
mPresenter.onPause();
// VideoPlayer.onPause();
// ...
}
@Override
protected void onStop() {
super.onStop();
mPresenter.onStop();
// VideoPlayer.onStop();
// ...
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.onDestroy();
// VideoPlayer.onDestroy();
// ...
}
}
因此,Lifecycle就是为了解决这个痛点,将生命周期的响应分发到各个观察者中去,我们只需要在Activity中调用一行代码:
getLifecycle().addObserver(mPresenter);
代码量蹭蹭就下来了。诸如音视频播放、图片加载,这些吃内存大户,都应该响应生命周期,及时释放内存,否则很可能就会造成OOM。
二、知其然,还得知其所以然
在项目中引入一个库,却不懂是怎么实现的,是一件非常危险的行为,因此我们不仅要学会怎么用,还得知道其中的原理。
先看一张官方的图:
可以看到两个很显眼的单词:State和Event,这也是贯穿整个Lifecycle的两个概念:状态和事件。
Lifecycle将Activity的生命周期函数对应成State,生命周期改变,会造成State改变,而State变化将触发Event事件,从而被LifecycleObser接收。
State:状态,是Lifecycle中对应Activity生命周期的一种状态标识,从图中可以看到,它有INITIALIZED、DESTROYED、CREATED、STARTED、RESUMED这5中状态。
- INITIALIZED:对应Activity的onCreate之前的生命周期
- DESTROYED:对应Activity的onDestroy
- CREATED:对应Activity的onCreate到onStop之间的生命周期
- STARTED:对应Activity的onStart到onPause之间的生命周期
- RESUMED:对应Activity的onResume
- Event:事件,当State发生变化时,Lifecycle会向已注册的LifecycleObserver发送事件,例如:当State从INITIALIZED变化到CREATED时,就会发出ON\_CREATE事件。
因此,弄懂Lifecycle,其实也就是需要弄懂两件事:
- State是如何与Activity/Fragment的生命周期绑定的?
- Event事件是如何分发到LifecycleObserver的?
ok,带着这两个问题,我们开始看源码:
1.从AppCompatActivity的getLifecycle()开始
直接ctrl+左键跟进源码,由于AppCompatActivity继承自SupportActivity,我们发现,AppCompatActivity.getLifecycle(),最终定位在了SupportActivity.getLifecycle()方法中
public class SupportActivity extends Activity implements LifecycleOwner {
......
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
......
}
不难看到:
- 最终getLifecycle()返回的是一个LifecycleRegistry 对象,所以所有对LifecycleObserver的操作都是由LifecycleRegistry 完成的
- 在onCreate()方法中,我们还看到了一个ReportFragment.injectIfNeededIn(this),先做个标记,后面再说
2.LifecycleRegistry
字面意思:生命周期登记处
这个类是Lifecycle中最重要的一个类,它是Lifecycle的子类,起着添加观察者,响应生命周期事件,分发生命周期事件的作用
public class LifecycleRegistry extends Lifecycle {
// LifecycleObserver Map,每一个Observer都有一个State
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
// 当前的状态
private State mState;
// 生命周期拥有者,上述的SupportActivity继承了LifecycleOwner
private final WeakReference<LifecycleOwner> mLifecycleOwner;
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
/**
* 添加LifecycleObserver观察者,并将之前的状态分发给这个Observer,例如我们在onResume之后注册这个Observer,
* 该Observer依然能收到ON_CREATE事件
*/
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
......
// 例如:Observer初始状态是INITIALIZED,当前状态是RESUMED,需要将INITIALIZED到RESUMED之间的
// 所有事件分发给Observer
//
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
targetState = calculateTargetState(observer);
}
......
}
/**
* 处理生命周期事件
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
/**
* 改变状态
*/
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
......
sync();
......
}
/**
* 同步Observer状态,并分发事件
*/
private void sync() {
LifecycleOwner lfecycleOwner = 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;
// State中,状态值是从DESTROYED-INITIALIZED-CREATED-STARTED-RESUMED增大
// 如果当前状态值 < Observer状态值,需要通知Observer减小状态值,直到等于当前状态值
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
// 如果当前状态值 > Observer状态值,需要通知Observer增大状态值,直到等于当前状态值
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
/**
* 向前传递事件,对应图中的INITIALIZED -> RESUMED
* 增加Observer的状态值,直到状态值等于当前状态值
*/
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
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()))) {
pushParentState(observer.mState);
// 分发状态改变事件
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
/**
* 向后传递事件,对应图中的RESUMED -> DESTROYED
* 减小Observer的状态值,直到状态值等于当前状态值
*/
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();
}
}
}
}
我们再看看新版AppCompatActivity是如何将事件分发给LifecycleRegistry的,还记得SupportActivity中有这么一段逻辑吗:
public class SupportActivity extends Activity implements LifecycleOwner {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
}
我们看看ReportFragment是什么
3.ReportFragment
public class ReportFragment extends Fragment {
public static void injectIfNeededIn(Activity activity) {
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
// ...... 其他生命周期也是同样调用了dispatch(Lifecycle.Event.xxx)分发事件
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
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);
}
}
}
}
可以看到,SupportActivity添加了一个没有页面的ReportFragment,在ReportFragment的生命周期函数中,调用了LifecycleRegistry.handleLifecycleEvent()方法来分发生命周期事件。用一张图总结一下就是:
AppCompatActivity中添加了一个ReportFragment,其生命周期变化时,调用LifecycleRegistry.handleLifecycleEvent()方法通知LifecycleRegistry改变状态,LifecycleRegistry内部调用moveToState()改变状态,并调用每个LifecycleObserver.onStateChange()方法通知生命周期变化。
为什么不直接在SupportActivity的生命周期函数中给Lifecycle分发生命周期事件,而是要加一个Fragment呢?
因为不是所有的页面都继承AppCompatActivity,为了兼容非AppCompatActivity,所以封装一个同样具有生命周期的Fragment来给Lifecycle分发生命周期事件。
- 那我们不继承新版本AppCompatActivity时,Lifecycle是如何通过ReportFragment来分发生命周期事件的呢?
这里我们直接使用AndroidStudio强大的搜索功能,alt+F7搜索ReportFragment的调用者,我们发现:除了SupportActivity以外,还有两个地方使用到了ReportFragment:LifecycleDispatcher和ProcessLifecycleOwner
4.LifecycleDispatcher
字面意思:生命周期分发者
class LifecycleDispatcher {
static void init(Context context) {
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
/**
* 给所有子Fragment设置State
*/
private static void markState(FragmentManager manager, State state) {
Collection<Fragment> fragments = manager.getFragments();
if (fragments == null) {
return;
}
for (Fragment fragment : fragments) {
if (fragment == null) {
continue;
}
markStateIn(fragment, state);
if (fragment.isAdded()) {
markState(fragment.getChildFragmentManager(), state);
}
}
}
private static void markStateIn(Object object, State state) {
if (object instanceof LifecycleRegistryOwner) {
LifecycleRegistry registry = ((LifecycleRegistryOwner) object).getLifecycle();
registry.markState(state);
}
}
// 通过注册Application.registerActivityLifecycleCallbacks来获取Activity的生命周期回调
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(mFragmentCallback, true);
}
// 给每个Activity添加ReportFragment
ReportFragment.injectIfNeededIn(activity);
}
@Override
public void onActivityStopped(Activity activity) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
}
}
可以看到LifecycleDispatcher是通过注册Application.registerActivityLifecycleCallbacks来监听Activity的生命周期回调的。
- 在onActivityCreated()中添加ReportFragment,将Activity的生命周期交给ReportFragment去分发给LifecycleRegistry
- 在onActivityStopped()以及onActivitySaveInstanceState()中,将Activity及其所有子Fragment的State置为CREATED
5.ProcessLifecycleOwner
字面意思:线程生命周期拥有者
public class ProcessLifecycleOwner implements LifecycleOwner {
public static LifecycleOwner get() { return sInstance; }
static void init(Context context) {
sInstance.attach(context);
}
void activityResumed() {
mResumedCounter++;
if (mResumedCounter == 1) {
if (mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mPauseSent = false;
} else {
mHandler.removeCallbacks(mDelayedPauseRunnable);
}
}
}
void activityPaused() {
mResumedCounter--;
if (mResumedCounter == 0) {
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}
private ActivityInitializationListener mInitializationListener = new ActivityInitializationListener() {
@Override
public void onCreate() {}
@Override
public void onStart() {
activityStarted();
}
@Override
public void onResume() {
activityResumed();
}
};
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
}
根据官方注释,我们可以了解到:
- ProcessLifecycleOwner是用来监听Application生命周期的,因此它只会分发一次ON\_CREATE事件,并且不会分发ON\_DESTROY事件。
- ProcessLifecycleOwner在Activity的onResume和onStop方法中都采用了Handle.postDelayed()方法,是为了处理Activity重建时比如横竖屏幕切换时,不会发送事件。
- ProcessLifecycleOwner一般用来判断应用是在前台还是后台。但由于使用了Handle.postDelayed(),因此这个判断不是即时的,有默认700ms的延迟。
- ProcessLifecycleOwner与LifecycleDispatcher一样,都是通过注册Application.registerActivityLifecycleCallbacks来监听Activity的生命周期回调,来给每个Activity添加ReportFragment的。
那么问题又来了,ProcessLifecycleOwner和LifecycleDispatcher两个类是在哪里初始化呢?
从源码中我们看到,他们的入口都是init(Context),继续搜索源码,我们发现:
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
// ......
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
......
<provider
android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
android:authorities="me.baron.achitecturelearning.lifecycle-trojan"
android:exported="false"
android:multiprocess="true" />
</manifest>
了然,Lifecycle自动在我们的AndroidManifest.xml中添加了一个ContentProvider,用于初始化ProcessLifecycleOwner和LifecycleDispatcher,这么做的好处是,不需要我们在Application中显示调用,不需要我们写一行代码。
总结
回到我们最初的两个问题:
- State是如何与Activity/Fragment的生命周期绑定的?
在Activity中添加一个ReportFragment(如果你的Activity继承AppCompatActivity,会在父类的onCreate()中添加ReportFragment,否则由LifecycleDispatcher添加),在ReportFragment生命周期函数中调用LifecycleRegistry.handleLifecycleEvent()方法改变State。
- Event事件是如何分发到LifecycleObserver的?
LifecycleRegistry在收到handleLifecycleEvent()后,内部调用moveToState()方法,改变State值,每一次State值改变,都会调用LifecycleObserver.onStateChanged()方法将Event分发到LifecycleObserver
涨知识?学技能?关注微信公众号:Android必修课
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。