简介
Android框架中定义的大多数应用程序组件都具有生命周期。生命周期由进程中运行的操作系统或框架代码管理。它们是Android工作方式的核心,您的应用程序必须尊重它们。否则可能会导致内存泄漏甚至应用程序崩溃。
androidx.lifecycle 软件包提供了一些类和接口,使您可以构建生命周期感知的组件,这些组件可以根据活动或片段的当前生命周期状态自动调整其行为。
基于AppCompatActivity的简单使用
1、需要引包,这里以Androidx的包为例
implementation androidx.appcompat:appcompat:1.1.0
2、实现LifecycleObserver接口,同时使用@OnLifecycleEvent监听状态变更
public class DemoLifecycle implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
}
}
3、与Activity的lifecycle同步生命周期
public class DemoViewModelActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_binding_activity);
getLifecycle().addObserver(new DemoLifecycle());
}
}
很简答,执行会发现DemoLifecycle跟随Activity生命周期同步进行。
自定义生命周期发布者
有些时候我们可以不能使用AppCompatActivity,比如项目早期有自定义的BaseActivity,并且BaseActivity没实现lifecycle功能。
1、Activity实现LifecycleOwner接口
2、new LifecycleRegistry()作为成员变量,用于发布状态
3、Activity生命周期中发布状态
public class DemoViewModelActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry lifecycleRegistry;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_binding_activity);
lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
}
@Override
protected void onStart() {
super.onStart();
lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
}
源码分析
这里我们从自定义的LifecycleOwner分析吧
1、首先看下LifecycleOwner接口
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
只有一个getLifecycle接口,返回Lifecycle
2、看下Lifecycle
public abstract class Lifecycle {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@NonNull
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
定义了Event和State,主要还是通过Lifecycle添加和去除observer观察者
3、所以一切的重点都在LifecycleRegistry,这里精简下必要代码
public class LifecycleRegistry extends Lifecycle {
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
private final WeakReference<LifecycleOwner> mLifecycleOwner;
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
// 1、addObserver添加需要监听的LifecycleObserver
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
}
// 2、Activity等通过此接口分发生命周期
@MainThread
public void setCurrentState(@NonNull State state) {
moveToState(state);
}
private void moveToState(State next) {
......
sync();
}
// 3、调用forwardPass同时传入lifecycleOwner
private void sync() {
......
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
forwardPass(lifecycleOwner);
}
// 4、通过mObserverMap取出LifecycleObserver集合,循环执行dispatchEvent
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();
}
}
}
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
// 5、执行mLifecycleObserver.onStateChange同步状态
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
}
4、最终回调到了LifecycleObserver.onStateChange()方法
/**
* Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
* {@link OnLifecycleEvent} annotated methods.
* <p>
* @see Lifecycle Lifecycle - for samples and usage patterns.
*/
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {
}
最终通过注解回调到了LifecycleObserver的实现类。这里就不详细介绍注解怎么起作用的了。有兴趣的可以自行研究。
附录一个不错的注解讲解:
秒懂,Java 注解 (Annotation)你可以这样学