一、定义以及作用
1.1、定义
Lifecycle是用来感知Activity或者Fragment生命周期的组件,是一个表示android生命周期及状态的对象
1.2、作用
Lifecycle可以有效的避免内存泄漏和解决android生命周期的常见难题 LivecycleOwner 用于连接有生命周期的对象,如activity,fragment LivecycleObserver 用于观察查LifecycleOwner
1.3、用法
在没有Lifecycle时,我们是如何处理在不同的生命周期时做不同的代码操作的?
案例1:在使用百度地图SDK时,我们需要让地图控件的生命周期和Activity或者Fragment的生命周期绑定一致
class MapActivity : AppCompatActivity {
private lateinit var mMapView:MapView
override fun onCreate(savedInstanceState:Bundle){
// 此处省略其他代码
mMapView = findViewById(R.id.bmapView)
}
override fun onResume() {
super.onResume()
mMapView.onResume()
}
override fun onPause() {
super.onPause()
mMapView.onPause()
}
override fun onDestroy() {
super.onDestroy()
mMapView.onDestroy()
}
}
案例2:在使用友盟统计时,需要在Activity或者Fragment的各个生命周期添加统计的代码
class BaseActivity : AppCompatActivity {
override fun onResume() {
super.onResume()
MobclickAgent.onPageStart(javaClass.simpleName)
MobclickAgent.onResume(this)
}
override fun onPause() {
super.onPause()
MobclickAgent.onPageEnd(javaClass.simpleName)
MobclickAgent.onPause(this)
}
}
class BaseFragment : Fragment {
override fun onResume() {
super.onResume()
MobclickAgent.onPageStart(javaClass.simpleName)
}
override fun onPause() {
super.onPause()
MobclickAgent.onPageEnd(javaClass.simpleName)
}
}
要说上面这些案例有什么问题,其实这么写并没有什么问题,功能都能实现,但是一旦需要在生命周期里绑定的操作变多了就会容易乱,而且不符合单一职责原则,如果能把不同的功能放到不同的类中封装起来会更简洁更优雅。
下面就拿案例2
结合Lifecycle
来做个封装试试:
class UMengLifecycle private constructor(private val context: Context,private val className:String):LifecycleEventObserver {
private val isFragment: Boolean
companion object {
@JvmStatic
fun with(fragment: Fragment) {
LifecycleUtil(fragment.requireContext(),fragment.javaClass.simpleName)
}
@JvmStatic
fun with(activity: Activity) {
LifecycleUtil(activity,activity.javaClass.simpleName)
}
@JvmStatic
fun with(activity: FragmentActivity) {
LifecycleUtil(activity,activity.javaClass.simpleName)
}
}
init {
when(context){
is FragmentActivity->{
isFragment = false
context.lifecycle.addObserver(this)
}
is Fragment->{
isFragment = true
context.lifecycle.addObserver(this)
}
else -> throw Throwable("not support this context type")
}
}
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
when (event) {
Lifecycle.Event.ON_RESUME -> {
MobclickAgent.onPageStart(className)
if (!isFragment) {
MobclickAgent.onResume(context)
}
}
Lifecycle.Event.ON_PAUSE -> {
MobclickAgent.onPageEnd(className)
if (!isFragment) {
MobclickAgent.onPause(context)
}
}
}
}
}
在Activity
中如何使用?
class BaseActivity: AppCompatActivity {
public BaseActivity(){
LifecycleUtil.with(this);
}
}
在Fragment
中如何使用?
class BaseFragment: Fragment {
override fun onAttach(context:Context){
LifecycleUtil.with(context);
}
}
为什么Fragment
不能在构造函数中使用呢?
下面我们来看看Activity和Fragment中Lifecycle的LifecycleRegistry是在什么时候初始化的
// 路径:androidx/activity/ComponentActivity.java
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
}
// 路径:androidx/fragment/app/Fragment.java
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner, SavedStateRegistryOwner {
LifecycleRegistry mLifecycleRegistry;
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
// 。。。
}
}
在Activity中的LifecycleRegistry
是成员变量在构造函数中就能调用,而Fragment中的LifecycleRegistry
会在构造函数执行完才会初始化完LifecycleRegistry,所以如果在Fragment的构造函数中使用的话会导致crash,这里在onAttach里调用。
最佳做法:
- 使界面控制器(Activity 和 Fragment)尽可能保持精简。它们不应试图获取自己的数据,而应使用
ViewModel
执行此操作,并观察LiveData
对象以将更改体现到视图中。 - 设法编写数据驱动型界面,对于此类界面,界面控制器的责任是随着数据更改而更新视图,或者将用户操作通知给
ViewModel
。 - 将数据逻辑放在
ViewModel
类中。ViewModel
应充当界面控制器与应用其余部分之间的连接器。不过要注意,ViewModel
不负责获取数据(例如,从网络获取)。但是,ViewModel
应调用相应的组件来获取数据,然后将结果提供给界面控制器。 - 使用数据绑定在视图与界面控制器之间维持干净的接口。这样一来,您可以使视图更具声明性,并尽量减少需要在 Activity 和 Fragment 中编写的更新代码。如果您更愿意使用 Java 编程语言执行此操作,请使用诸如 Butter Knife 之类的库,以避免样板代码并实现更好的抽象化。
- 如果界面很复杂,不妨考虑创建 presenter 类来处理界面的修改。这可能是一项艰巨的任务,但这样做可使界面组件更易于测试。
- 避免在
ViewModel
中引用View
或Activity
上下文。如果ViewModel
存在的时间比 Activity 更长(在配置更改的情况下),Activity 将泄漏并且不会获得垃圾回收器的妥善处置。 - 使用 Kotlin 协程管理长时间运行的任务和其他可以异步运行的操作。
用例:
- 在粗粒度和细粒度位置更新之间切换。使用生命周期感知型组件可在位置应用可见时启用细粒度位置更新,并在应用位于后台时切换到粗粒度更新。借助生命周期感知型组件
LiveData
,应用可以在用户使用位置发生变化时自动更新界面。 - 停止和开始视频缓冲。使用生命周期感知型组件可尽快开始视频缓冲,但会推迟播放,直到应用完全启动。此外,应用销毁后,您还可以使用生命周期感知型组件终止缓冲。
- 开始和停止网络连接。借助生命周期感知型组件,可在应用位于前台时启用网络数据的实时更新(流式传输),并在应用进入后台时自动暂停。
- 暂停和恢复动画可绘制资源。借助生命周期感知型组件,可在应用位于后台时暂停动画可绘制资源,并在应用位于前台后恢复可绘制资源。
二、被观察者、观察者
Lifecycle是通过观察者模式实现观察者监听被观察者(Activity/Fragment)的生命周期的。
2.1、被观察者
在Activity
中,在ComponentActivity类中实现了LifecycleOwner接口,实现了getLifecycle
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
在Fragment
中,实现了LifecycleOwner接口,也实现了getLifecycle
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner,
ViewModelStoreOwner, SavedStateRegistryOwner {
@NonNull
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
在Activity和Fragment中使用时都不需要自己实现接口了
2.2、观察者
通过实现LifecycleObserver接口来实现观察,但是LifecycleObserver接口又是一个空接口
public interface LifecycleObserver {
// 没有任何实现接口
}
可以使用注解的方式接收被观察者的事件发送
public class BasePresenter<T extends IBaseView> implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onStart(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
void onPause(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy(LifecycleOwner owner) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onAny(LifecycleOwner owner) {
}
}
在LifecycleObserver的基础上定义了几个常用的接口:
-
LifecycleEventObserver
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
-
FullLifecycleObserver
void onCreate(LifecycleOwner owner); void onStart(LifecycleOwner owner); void onResume(LifecycleOwner owner); void onPause(LifecycleOwner owner); void onStop(LifecycleOwner owner); void onDestroy(LifecycleOwner owner);
2.3、订阅
在Activity或者Fragment中直接使用getLifecycle().addObserver(xxx)
被观察者.addObserver(观察者)
三、核心原理
我们从getLifecycle().addObserver(xxx)
作为入口来一步步的查看源码:
getLifecycle()返回了一个LifecycleRegistry类:
public class LifecycleRegistry extends Lifecycle {
// 用来存储观察者和当前的状态
// 实现了一个HashMap单链表,但是value是一个双链表的封装
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
// 弱引用的LifecycleOwner,方便Activity或者Fragment释放时标记回收
// 会在构造函数中初始化
private final WeakReference<LifecycleOwner> mLifecycleOwner;
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 封装LifecycleObserver对象,会将LifecycleObserver转换成一个LifecycleEventObserver对象
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 存到mObserverMap对象中
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
if (previous != null) {
return;
}
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
// it is null we should be destroyed. Fallback quickly
return;
}
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
// 获取当前addObserver时的页面状态,因为addObserver并不一定是在onCreate方法中执行的
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
// statefulObserver.mState小于targetState时
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
// 触发Event事件分发,更新mState状态
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
mAddingObserverCounter--;
}
}
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.");
}
// 待ReportFragment开始分发时mState会变化,isSynced()=false
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;
}
forwardPass:向前传递,遍历mObserverMap
中的mStart
到mCurrent
,即从第一个加入mObserverMap
时的状态到当前Activity或者Fragment的状态
backwardPass:向后传递,遍历mObserverMap
中mEnd
到mStart
,即从最后一个加入mObserverMap
时的状态到最后一个LifecycleObserver的状态
// 向前传递
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
// 会把State枚举按顺序走一遍,直到两个state相同
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();
}
}
}
// 向后传递
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
// 会把State枚举按顺序走一遍,直到两个state相同
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();
}
}
}
看了上面观察者的注册过程,那么被观察者是如何通知观察者生命周期变化的呢?
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
// 注册了一个ReportFragment观察生命周期
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
}
ReportFragment作为一个空的Fragment,观察Activity和Fragment的生命周期并分发通知Activity和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);
}
@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;
}
都有dispatch(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);
}
}
}
会调用handleLifecycleEvent(Event)
方法,Activity中实现了LifecycleOwner
所以会调用LifecycleRegistry
的handleLifecycleEvent
下面看下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(event)
移动到下一个状态:
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;
// 通过这个方法去同步状态,又回到了backwardPass或者forwardPass
sync();
mHandlingEvent = false;
}
sync()
中的forwardPass
和backwardPass
都会调用observer.dispatchEvent
方法分发状态
dispatchEvent方法在class ObserverWithState
类中
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
通过mLifecycleObserver.onStateChanged(owner, event);
会回调分发给实现了onStateChanged事件的接口实现类,如LifecycleEventObserver
,如果没有实现继承LifecycleEventObserver
的类,那么Lifecycling会构建一个ReflectiveGenericLifecycleObserver类,通过反射得到OnLifecycleEvent
注解注册的方法,然后通过对应的方法invoke调用方法实现生命周期的回调。