lifecycle是一个感知生命周期的组件,一般用作响应Activity/Fragment生命周期的变化,并将此变化通知到注册的观擦者,让其代码更符合生命周期的规范,从而减少内存泄漏,增强稳定性。
使用
- 直接实现LifecycleObserver接口,使用@OnLifecycleEvent注解在方法上,注解入参表示需要监听的对应的生命周期
class MyLifecycleObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {}
}
2.实现DefaultLifecycleObserver
class MyLifecycleObserver2:DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
}
}
在API26 时因为AppCompatActivity实现了LifecycleOwner可以直接
lifecycle.addObserver(MyLifecycleObserver())
这样就可以了
低于API26 则需要实现LifecycleOwner接口,在生命周期方法中分发事件
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mLifecycleRegistry.addObserver(MyLifecycleObserver())
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}
private val mLifecycleRegistry by lazy {
LifecycleRegistry(this)
}
override fun getLifecycle() = mLifecycleRegistry
}
源码解析
AppCompatActivity继承自ComponentActivity,在OnCreate中
/**
* {@inheritDoc}
*
* If your ComponentActivity is annotated with {@link ContentView}, this will
* call {@link #setContentView(int)} for you.
*/
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
我们可以看到 ReportFragment.injectIfNeededIn(this);
ReportFragment
类是一个Fragment
,他的作用是分派生命周期,injectIfNeededIn()
就是在当前Activity中添加一个ReportFragment
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
就可以共享到当前绑定的Activity的生命周期,
在ReportFragment
的生命周期内我们可以看到都调用了
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);
}
}
}
我们可以看到,此方法会判断activity 是否实现了LifecycleOwner 如果实现了会获取到LifecycleRegistry
,借由LifecycleRegistry
通知给各个LifecycleObserver
从而调用其对应的方法
LifecycleRegistry
/**
* An implementation of {@link Lifecycle} that can handle multiple observers.
* <p>
* It is used by Fragments and Support Library Activities. You can also directly use it if you have
* a custom LifecycleOwner.
*/
public class LifecycleRegistry extends Lifecycle {
他实现了Lifecycle
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
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;
State targetState = calculateTargetState(observer);
mAddingObserverCounter++;
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.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--;
}
查看他主要的addObserver()
可以看到,使用了ObserverWithState
将监听封装然后放入mObserverMap
,mObserverMap
是一个FastSafeIterableMap
FastSafeIterableMap
是一个自定义列表,用于保存观察者并可在遍历期间处理删除/添加。任何时刻:观察者1和观察者2,如果addition_order(observer1)<addition_order(observer2),那么 state(observer1)> = state(observer2)
@Override
public V putIfAbsent(@NonNull K key, @NonNull V v) {
Entry<K, V> current = get(key);
if (current != null) {
return current.mValue;
}
mHashMap.put(key, put(key, v));
return null;
}
我们可以看到此方法,当此observer已存在的时候会返回存在的ObserverWithState
,否则返回null
所以在addObserver()
方法中判断了返回值不为null
则return,当此LifecycleRegistry
的LifecycleOwner
为null
时表示此表已无意义了也return。
我们可以看一下关键的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;
}
我么你可以看到,判断当前状态小于列表中第一个ObserverWithState
的状态执行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();
}
}
}
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();
}
}
}
总之都会执行ObserverWithState
的dispatchEvent()
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
执行onStateChanged()
通知LifecycleObserver
我们回到ObserverWithState
的构造方法中来
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
其中执行了Lifecycling
的lifecycleEventObserver()
方法
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) 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);
}
该方法返回了3种实现
1.FullLifecycleObserverAdapter
实现DefaultLifecycleObserver
返回
2.CompositeGeneratedAdaptersObserver
使用lifecycle-compiler
返回
3.ReflectiveGenericLifecycleObserver通过反射返回