目录:
1. Lifecycle是如何诞生的? 用来解决什么问题的
Lifecycle的使用
Lifecycle源码分析
Lifecycle重要的几个类梳理
1. Lifecycle是如何诞生的? 用来解决什么问题的
作用:这样 Lifecycle 库能有效的避免内存泄漏和解决常见的 Android 生命周期难题
问题: Lifecycle之前是如何管理生命周期
通过Activity的onstop, onstart()方法
组件留存的时间比所需的时间要长,从而导致内次泄漏
- 无法保证组件会在 Activity/Fragment停止后不执行启动
2. Lifecycle的使用
2.1. Lifecycle的使用很简单:
- 1、生命周期拥有者 使用getLifecycle()获取Lifecycle实例,然后代用addObserve()添加观察者;
- 2、观察者实现LifecycleObserver,方法上使用OnLifecycleEvent注解关注对应生命周期,生命周期触发时就会执行对应方法;
public class LifecycleTestActivity extends AppCompatActivity {
private String TAG = "Lifecycle_Test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifecycle_test);
//Lifecycle 生命周期
getLifecycle().addObserver(new MyObserver());
Log.i(TAG, "onCreate: ");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause: ");
}
}
public class LifecycleTestActivity extends AppCompatActivity {
private String TAG = "Lifecycle_Test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifecycle_test);
//Lifecycle 生命周期
getLifecycle().addObserver(new MyObserver());
Log.i(TAG, "onCreate: ");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause: ");
}
}
2.2. 自定义LifecycleOwner
如果有一个自定义类并希望使其成为LifecycleOwner,可以使用LifecycleRegistry类,它是Lifecycle的实现类,但需要将事件转发到该类
也即MyActivity变成了LifecycleOwner,然后就可以和 实现了LifecycleObserver的组件配合使用了
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);
}
@Override
public void onStart() {
super.onStart();
lifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
}
2.3. Lifecycle判断应用在前台还是后台
之前对App进入前后台的判断是通过registerActivityLifecycleCallbacks(callback)方法,然后在callback中利用一个全局变量做计数,在onActivityStarted()中计数加1,在onActivityStopped方法中计数减1,从而判断前后台切换。
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//注册App生命周期观察者
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicationLifecycleObserver());
}
/**
* Application生命周期观察,提供整个应用进程的生命周期
*
* Lifecycle.Event.ON_CREATE只会分发一次,Lifecycle.Event.ON_DESTROY不会被分发。
*
* 第一个Activity进入时,ProcessLifecycleOwner将分派Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME。
* 而Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP,将在最后一个Activit退出后后延迟分发。如果由于配置更改而销毁并重新创建活动,则此延迟足以保证ProcessLifecycleOwner不会发送任何事件。
*
* 作用:监听应用程序进入前台或后台
*/
private static class ApplicationLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onAppForeground() {
Log.w(TAG, "ApplicationObserver: app moved to foreground");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onAppBackground() {
Log.w(TAG, "ApplicationObserver: app moved to background");
}
}
}
2.4 实际应用,就是后台播放声音和视频
2.5 LifecycleHandler 的封装
我们平时在使用 handler 的时候,在 activity onDestroy 的时候,需要手动取 removeMessage 或者 removeCallBack,不然的话,很容易发生内存泄漏。
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
public class LifecycleHandler extends Handler implements FullLifecycleObserver {
private LifecycleOwner mLifecycleOwner;
public LifecycleHandler(LifecycleOwner lifecycleOwner) {
mLifecycleOwner = lifecycleOwner;
addObserver();
}
public LifecycleHandler(LifecycleOwner lifecycleOwner, Callback callback) {
super(callback);
mLifecycleOwner = lifecycleOwner;
addObserver();
}
public LifecycleHandler(LifecycleOwner lifecycleOwner, Looper looper) {
super(looper);
mLifecycleOwner = lifecycleOwner;
addObserver();
}
public LifecycleHandler(LifecycleOwner lifecycleOwner, Looper looper, Callback callback) {
super(looper, callback);
mLifecycleOwner = lifecycleOwner;
addObserver();
}
private void addObserver() {
if (mLifecycleOwner != null) {
mLifecycleOwner.getLifecycle().addObserver(new FullLifecycleObserverAstrong textdapter(mLifecycleOwner, this));
}
}
@Override
public void onCreate(LifecycleOwner owner) {
}
@Override
public void onStart(LifecycleOwner owner) {
}
@Override
public void onResume(LifecycleOwner owner) {
}
@Override
public void onPause(LifecycleOwner owner) {
}
@Override
public void onStop(LifecycleOwner owner) {
}
@Override
public void onDestroy(LifecycleOwner owner) {
removeCallbacksAndMessages(null);
}
}
2.6 MVP 中引入 lifecycle,可以自行监听 activity 生命周期变化
MVP用Lifecycle是为了解耦
Lifecycle框架,希望借Lifecycle将activity的生命周期事件传递给Presenter,让Presenter承担部分业务,从而降低了Activity的复杂度
public class LifecycleTestActivity extends AppCompatActivity implements IView {
private String TAG = "Lifecycle_Test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lifecycle_test);
//Lifecycle 生命周期
// getLifecycle().addObserver(new MyObserver());
//MVP中使用Lifecycle
getLifecycle().addObserver(new MyPresenter(this));
Log.i(TAG, "onCreate: ");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause: ");
}
@Override
public void showView() {}
@Override
public void hideView() {}
}
//Presenter
class MyPresenter implements LifecycleObserver {
private static final String TAG = "Lifecycle_Test";
private final IView mView;
public MyPresenter(IView view) {mView = view;}
@OnLifecycleEvent(value = Lifecycle.Event.ON_START)
private void getDataOnStart(LifecycleOwner owner){
Log.i(TAG, "getDataOnStart: ");
Util.checkUserStatus(result -> {
//checkUserStatus是耗时操作,回调后检查当前生命周期状态
if (owner.getLifecycle().getCurrentState().isAtLeast(STARTED)) {
start();
mView.showView();
}
});
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_STOP)
private void hideDataOnStop(){
Log.i(TAG, "hideDataOnStop: ");
stop();
mView.hideView();
}
}
//IView
interface IView {
void showView();
void hideView();
}
3. Lifecycle源码分析
Lifecycle类:
添加和移除,用户管理的,获取状态
里面的自旋锁:
public abstract class Lifecycle {
//添加观察者
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
//移除观察者
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
//获取当前状态
public abstract State getCurrentState();
//生命周期事件,对应Activity生命周期方法
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY //可以响应任意一个事件
}
//生命周期状态. (Event是进入这种状态的事件)
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
//判断至少是某一状态
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
3.1.1 Lifecycle 是怎么分发生命周期的?-----生命周期事件分发
给当前activity添加了ReportFragment,注意这个fragment是没有布局的!
问题: 为什么使用一个没有布局的fragment?
逻辑抽离出来,实现activity的无侵入。如果你对图片加载库Glide比较熟,就会知道它也是使用透明Fragment获取生命周期的。
ReportFragment
ReportFragment.injectIfNeededIn(this)
//专门用于分发生命周期事件的Fragment
public class ReportFragment extends Fragment {
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
//在API 29及以上,可以直接注册回调 获取生命周期
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
//API29以前,使用fragment 获取生命周期
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@SuppressWarnings("deprecation")
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
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);//使用LifecycleRegistry的handleLifecycleEvent方法处理事件
}
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
...省略onStop、onDestroy
private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
dispatch(getActivity(), event);
}
}
//在API 29及以上,使用的生命周期回调
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
...
@Override
public void onActivityPostCreated(@NonNull Activity activity,@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
@Override
public void onActivityPostStarted(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_START);
}
@Override
public void onActivityPostResumed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_RESUME);
}
@Override
public void onActivityPrePaused(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_PAUSE);
}
...省略onStop、onDestroy
}
}
生命周期事件处理——LifecycleRegistryLifecycleRegistry类:
LifecycleRegistry是Lifecycle具体实现
到这里,生命中周期事件的处理有转移到了 LifecycleRegistry 中:
//LifecycleRegistry.java
//系统自定义的保存Observer的map,可在遍历中增删
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);//获取event发生之后的将要处于的状态
moveToState(next);//移动到这个状态
}
private void moveToState(State next) {
if (mState == next) {
return;//如果和当前状态一致,不处理
}
mState = next; //赋值新状态
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
return;
}
mHandlingEvent = true;
sync(); //把生命周期状态同步给所有观察者
mHandlingEvent = false;
}
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()) { //isSynced()意思是 所有观察者都同步完了
mNewEventOccurred = false;
//mObserverMap就是 在activity中添加observer后 用于存放observer的map
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;
}
...
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);
}
用observer创建带状态的观察者ObserverWithState,observer作为key、ObserverWithState作为value,存到mObserverMap。 接着做了安全判断,最后把新的观察者的状态 连续地 同步到最新状态mState,意思就是:虽然可能添加的晚,但会把之前的事件一个个分发给你,即粘性。
原理总结:
原理比较清晰:Activity/Fragment实现LifecycleOwner接口,通过LifecycleRegistry在对应生命周期分发事件Lifecycle.Event,回调到生命周期观察者LifecycleObserver对应订阅方法。
Activity(LifeCycleOwner)----------Lifecycle-------LifecycleReigtry-----ReportFragment----addObserver-----LifecycleObserver
简单的叙述源码实现的总体流程,按照使用的步骤顺序叙述:
1). 创建一个观察者实现LifecycleObserver接口,用于监听响应被观察者生命周期的变化
观察者通过注解的方式监听组件某个生命状态的改变。
2). LifecycleRegistry继承了Lifecycle,管理着观察者
通过LifecycleRegistry添加观察者,利用反射原理获取到观察者中的方法与注解信息
被观察者(组件)通过实现LifecycleOwner 接口拿到LifecycleRegistry
3). 在组件生命周期中调用LifecycleRegistry提供的方法来监听生命周期状态
当生命周期发生变化时,LifecycleRegistry就会执行通过反射获取到的方法。实现监听的目的
3.1 问题: Lifecycle是怎样感知生命周期的?
就是在ReportFragment中的各个生命周期都调用了dispatch(Lifecycle.Event event)
方法,传递了不同的Event的值
3.2 问题: Lifecycle是如何处理生命周期的?
通过调用了((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
方法,也就是LifecycleRegistry 类来处理这些生命周期。
3.3 问题: LifecycleObserver的方法是怎么回调的呢?
LifecycleRegistry 的 handleLifecycleEvent方法,然后会通过层层调用最后通过反射到LifecycleObserver方法上的@OnLifecycleEvent(Lifecycle.Event.XXX)注解值,来调用对应的方法
3.4 问题: 为什么LifecycleObserver可以感知到Activity的生命周期
LifecycleRegistry调用handleLifecycleEvent方法时会传递Event类型,然后会通过层层调用,最后是通过反射获取注解的值,到LifecycleObserver方法上的@OnLifecycleEvent(Lifecycle.Event.XXX)注解上对应的Event的值,注意这个值是和Activity/Fragment的生命周期的一一对应的,所以就可以感知Activity、Fragment的生命周期了。
4. Lifecycle重要的几个类梳理
-
Lifecycle
Lifecycle是一个持有组件生命周期状态(如Activity或Fragment)的信息的类,并允许其他对象观察此状态。 - Event :从框架和Lifecycle类派发的生命周期事件。这些事件映射到活动和片段中的回调事件。
- State :由Lifecycle对象跟踪的组件的当前状态。
- LifecycleOwner (重要,)一个接口,Lifecycle持有者
- 实现该接口的类持有生命周期(Lifecycle对象),该接口的生命周期(Lifecycle对象)的改变会被其注册的观察者LifecycleObserver观察到并触发其对应的事件。
- LifecycleObserver(重要)Lifecycle观察者
- 实现该接口的类,通过注解的方式,可以通过被LifecycleOwner类的addObserver(LifecycleObserver o)方法注册,被注册后,LifecycleObserver便可以观察到LifecycleOwner的生命周期事件。 ** ReportFragmen**t: ------ ---生命周期事件分发
LifecycleRegistry-------生命周期事件处理
4.2 问题: Lifecycle和LifecycleObserver的关系:
Lifecycle添加观察者LifecycleObserver
mainActivity.getLifecycle().addObserver(mVideoView);
public Lifecycle getLifecycle()
通过将 Lifecycle 对象的 addObserver() 方法,将 Lifecycle 对象和 LifecycleObserver 对象进行绑定。LifecycleObserver便可以观察到LifecycleOwner的生命周期事件。
Lifecycle是怎么来的。在Activity或者Fragment里面: mainActivity.getLifecycle()= LifecycleRegistry
Lifecycle是被观察者,通过Add的方式把LifecycleObserver这个观察者添加进来