google文档: https://developer.android.google.cn/topic/libraries/architecture/li
Lifecycle, 用于存储有关组件(Activity, Fragment)的生命周期状态信息,并允许其他对象观察此状态。
不用在Activity,Fragment的生命周期方法里写业务逻辑, 可以写在单独的业务类。干净!
基本使用:
public class MyObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void connectListener() {
...
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void disconnectListener() {
...
}
}
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLifecycle().addObserver(new MyObserver());
}
}
源码解析:
讲解一下几个核心类。先看看它们之间的关系。
Lifecycle
这个抽象类定义了lifecycle的几个基本接口和状态值。详细看一下我添加的注释。这里再提一嘴:状态最后面的是RESUMED,而不是DESTROYED。所以isAtLeast(STARTED),就是要求必须是STARTED和RESUMED这两个活的状态。
DESTROYED是在最开始的。
public abstract class Lifecycle {
@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 {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY
}
/**
* Lifecycle 状态. 它们是处在上面各个Event之间。
*/
@SuppressWarnings("WeakerAccess")
public enum State {
/**
* * 相对于activity是调用了onDestory(),从此就不再分发lifecycle的状态了。
*/
DESTROYED,
/**
* 相对于activity是调用了activity构造方法,但是onCreate还没有调用。
*/
INITIALIZED,
/**
* 相对于activity是onCreate()完 和 onStop()还没开始 之间.
*
*/
CREATED,
/**
* 相对于activity是onStart()完 和 onPause()还没开始 之间.
*/
STARTED,
/**
* 相对于activity是onResume()完.
*/
RESUMED;
/**比较状态
*这里必须要注意一下,状态最后面的是RESUMED,而不是DESTROYED。所以isAtLeast
* (STARTED),就是要求必须是STARTED和RESUMED这两个活的状态。
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
LifecycleRegistry
- LifecycleRegistry继承实现了Lifecycle.
- 它是Lifecycle的唯一实现类,是针对Activity和Fragment的Lifecycle管理类。
- 从Activity或Fragment接收各种事件,通过LifecycleRegistry,转发给所有的观察者,再有观察者们完成它们自己的工作。
下图是事件和状态的关系。
LifecycleOwner
是Activity和Fragment实现LifecycleOwner ,把内部LifecycleRegistry类对象给观察者们来注册观察。
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
LifecycleObserver
这是一个空接口,用于标记这是一个lifecycle的观察者类。结合注解@OnLifecycleEvent(),观察者可以只监听特定的事件。
/**
* 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 {
}
LifecycleEventObserver
也好FullLifecycleObserver,LifecycleObserver也好, 最后都会被封装成LifecycleEventObserver的实现类。而LifecycleRegistry也只知道LifecycleEventObserver。具体详见Lifecycling类的lifecycleEventObserver方法。
public interface LifecycleEventObserver extends LifecycleObserver {
/**
* Called when a state transition event happens.
*
* @param source The source of the event
* @param event The event
*/
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
LifecycleRegistry中LifecycleEventObserver和State被封装进了ObserverWithState 。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
Activity中的Lifecycle
这是Activity之间的继承关系。
MainActivity->AppCompatActivity->FragmentActivity->ComponentActivity
在ComponentActivity类中实现了Lifecycleowner, 并且初始化了LifecycleRegistry。再看看ComponentActivity构造方法,Activity自己也是自己的观察者,用于实现ViewModel的功能。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
HasDefaultViewModelProviderFactory,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
static final class NonConfigurationInstances {
Object custom;
ViewModelStore viewModelStore;
}
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public ComponentActivity() {
Lifecycle lifecycle = getLifecycle();
//noinspection ConstantConditions
if (lifecycle == null) {
throw new IllegalStateException("getLifecycle() returned null in ComponentActivity's "
+ "constructor. Please make sure you are lazily constructing your Lifecycle "
+ "in the first call to getLifecycle() rather than relying on field "
+ "initialization.");
}
if (Build.VERSION.SDK_INT >= 19) {
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_STOP) {
Window window = getWindow();
final View decor = window != null ? window.peekDecorView() : null;
if (decor != null) {
decor.cancelPendingInputEvents();
}
}
}
});
}
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
if (19 <= SDK_INT && SDK_INT <= 23) {
getLifecycle().addObserver(new ImmLeaksCleaner(this));
}
}
那么Event事件是怎么产生的呢?请看handleLifecycleEvent的调用情况。
用户自己也可以写自带lifecycle的业务类。像Activity 或者Fragment一样。
参考了:https://blog.csdn.net/huweijian5/article/details/103309727