Lifecycle的基本使用方法
//AppCompatActivity继承了ComponentActivity类,实现了LifecycleOwner接口
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 MyObserver implements LifecycleObserver {
private String TAG = "Lifecycle_Test";
//在生命周期进行触发函数执行
@OnLifecycleEvent(value = Lifecycle.Event.ON_RESUME)
public void connect(){
Log.i(TAG, "connect: ");
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_PAUSE)
public void disConnect(){
Log.i(TAG, "disConnect: ");
}
}
自定义LifecycleOwner
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
//直接使用Activity实现Lifecycleowner接口
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);
lifecycleRegistry.addObserver(new TestObserver());
}
@Override
public void onStart() {
super.onStart();
//!!!
lifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
}
class TestObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreated(LifecycleOwner owner) {
// owner.getLifecycle().addObserver(anotherObserver);
// owner.getLifecycle().getCurrentState();
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
void onAny(LifecycleOwner owner, Lifecycle.Event event) {
// event.name()
}
源码分析
ComponentActivity
//androidx.activity.ComponentActivity,,实现LifecycleOwner接口
public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner{
...
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
...
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//使用ReportFragment分发生命周期事件,管理生命周期
ReportFragment.injectIfNeededIn(this);
}
@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
lifecycleRegistry.currentState = Lifecycle.State.CREATED
super.onSaveInstanceState(outState);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
ReportFragment
//用于管理和分发生命周期事件的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 LifecycleOwner) {
//获取Activity的LifecycleRegistry进行回调状态
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
//使用LifecycleRegistry的handleLifecycleEvent方法处理事件
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
@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);
}
...
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);
}
...
}
}
LifecycleRegistry
public actual open class LifecycleRegistry
private constructor(provider: LifecycleOwner, private val enforceMainThread: Boolean) :
Lifecycle()
public actual constructor(provider: LifecycleOwner) : this(provider, true)
init {
lifecycleOwner = WeakReference(provider)
}
//设置状态,并通知观察者
public actual open fun handleLifecycleEvent(event: Event) {
enforceMainThreadIfNeeded("handleLifecycleEvent")
moveToState(event.targetState)
}
private fun moveToState(next: State) {
//和当前状态相同,退出
if (state == next) {
return
}
check(!(state == State.INITIALIZED && next == State.DESTROYED)) {
"State must be at least CREATED to move to $next, but was $state in component " +
"${lifecycleOwner.get()}"
}
state = next
if (handlingEvent || addingObserverCounter != 0) {
newEventOccurred = true
// we will figure out what to do on upper level.
return
}
handlingEvent = true
sync()
handlingEvent = false
if (state == State.DESTROYED) {
observerMap = linkedMapOf()
}
}
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
private fun sync() {
val lifecycleOwner =
lifecycleOwner.get()
?: throw IllegalStateException(
"LifecycleOwner of this LifecycleRegistry is already " +
"garbage collected. It is too late to change lifecycle state."
)
while (!isSynced) {
newEventOccurred = false
//检查当前状态(state)是否小于observerMap中第一个观察者的最小状态
//observerMap是一个存储LifecycleObserver及其对应状态的映射
//做回溯处理,,确保所有观察者都能接收到之前错过的状态变化。
if (state < observerMap.values.first().state) {
backwardPass(lifecycleOwner)
}
val newest = observerMap.values.lastOrNull()
//回溯中未发生变化,且有观察者,当前状态超过最新的状态
if (!newEventOccurred && newest != null && state > newest.state) {
//向前推进
forwardPass(lifecycleOwner)
}
}
newEventOccurred = false
_currentStateFlow.value = currentState
}
private fun backwardPass(lifecycleOwner: LifecycleOwner) {
forEachObserverReversed { key, observer ->
//确保所有观察者状态同步
while (observer.state > state && !newEventOccurred && observerMap.contains(key)) {
//生命周期回退
val event =
Event.downFrom(observer.state)
?: throw IllegalStateException("no event down from ${observer.state}")
pushParentState(event.targetState)
//通知观察者生命周期发生变化
observer.dispatchEvent(lifecycleOwner, event)
popParentState()
}
}
}
//添加观察者
override fun addObserver(observer: LifecycleObserver) {
enforceMainThreadIfNeeded("addObserver")
val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
val statefulObserver = ObserverWithState(observer, initialState)
val previous = observerMap.put(observer, statefulObserver)
if (previous != null) {
return
}
val lifecycleOwner =
lifecycleOwner.get()
?: // it is null we should be destroyed. Fallback quickly
return
val isReentrance = addingObserverCounter != 0 || handlingEvent
var targetState = calculateTargetState(observer)
addingObserverCounter++
//同步新添加的观察者的状态
while (statefulObserver.state < targetState && observerMap.contains(observer)) {
pushParentState(statefulObserver.state)
val event =
Event.upFrom(statefulObserver.state)
?: throw IllegalStateException("no event up from ${statefulObserver.state}")
statefulObserver.dispatchEvent(lifecycleOwner, event)
popParentState()
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer)
}
if (!isReentrance) {
// we do sync only on the top level.
sync()
}
addingObserverCounter--
}
//事件具体分发
internal class ObserverWithState(observer: LifecycleObserver?, initialState: State) {
var state: State
private var lifecycleObserver: LifecycleEventObserver
init {
lifecycleObserver = Lifecycling.lifecycleEventObserver(observer!!)
state = initialState
}
fun dispatchEvent(owner: LifecycleOwner?, event: Event) {
val newState = event.targetState
state = min(state, newState)
lifecycleObserver.onStateChanged(owner!!, event)
state = newState
}
}
public interface LifecycleEventObserver extends LifecycleObserver {
//生命周期状态变化
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
//Lifecycling.getCallback(observer);
static LifecycleEventObserver lifecycleEventObserver(Object object) {
return new ReflectiveGenericLifecycleObserver(object);
}
//具体实现概括为:通过接口进行反射,查找进行注解标识的方法,然后保存,使用反射执行方法,达到通知观察者的目的
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());//存放了event与加了注解方法的信息
}
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);//执行对应event的观察者的方法
}
}
}
//ClassesInfoCache.java
private final Map<Class, CallbackInfo> mCallbackMap = new HashMap<>();//所有观察者的回调信息
private final Map<Class, Boolean> mHasLifecycleMethods = new HashMap<>();//观察者是否有注解了生命周期的方法
CallbackInfo getInfo(Class<?> klass) {
CallbackInfo existing = mCallbackMap.get(klass);//如果已经存在当前观察者回调信息 直接取
if (existing != null) {
return existing;
}
existing = createInfo(klass, null);//没有就去收集信息并创建
return existing;
}
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
Class<?> superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();//生命周期事件到来 对应的方法
...
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);//反射获取观察者的方法
boolean hasLifecycleMethods = false;
for (Method method : methods) {//遍历方法 找到注解OnLifecycleEvent
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue; //没有注解OnLifecycleEvent 就return
}
hasLifecycleMethods = true;//有注解OnLifecycleEvent
Class<?>[] params = method.getParameterTypes(); //获取方法参数
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) { //有参数
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(//第一个参数必须是LifecycleOwner
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(//第二个参数必须是Event
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(//有两个参数 注解值只能是ON_ANY
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 2) { //参数不能超过两个
throw new IllegalArgumentException("cannot have more than 2 params");
}
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);//校验方法并加入到map handlerToEvent 中
}
CallbackInfo info = new CallbackInfo(handlerToEvent);//获取的 所有注解生命周期的方法handlerToEvent,构造回调信息实例
mCallbackMap.put(klass, info);//把当前观察者的回调信息存到ClassesInfoCache中
mHasLifecycleMethods.put(klass, hasLifecycleMethods);//记录 观察者是否有注解了生命周期的方法
return info;
}
static class CallbackInfo {
final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;//Event对应的多个方法
final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;//要回调的方法
CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
mHandlerToEvent = handlerToEvent;
mEventToHandlers = new HashMap<>();
//这里遍历mHandlerToEvent来获取mEventToHandlers
for (Map.Entry<MethodReference, Lifecycle.Event> entry : handlerToEvent.entrySet()) {
Lifecycle.Event event = entry.getValue();
List<MethodReference> methodReferences = mEventToHandlers.get(event);
if (methodReferences == null) {
methodReferences = new ArrayList<>();
mEventToHandlers.put(event, methodReferences);
}
methodReferences.add(entry.getKey());
}
}
@SuppressWarnings("ConstantConditions")
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);//执行对应event的方法
invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,target);//执行注解了ON_ANY的方法
}
private static void invokeMethodsForEvent(List<MethodReference> handlers,
LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {//执行Event对应的多个方法
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
}
static class MethodReference {
...
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
try {
switch (mCallType) {
case CALL_TYPE_NO_ARG:
mMethod.invoke(target);//没有参数的
break;
case CALL_TYPE_PROVIDER:
mMethod.invoke(target, source);//一个参数的:LifecycleOwner
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
mMethod.invoke(target, source, event);//两个参数的:LifecycleOwner,Event
break;
}
}
...
}
...
}
ProcessLifecycleOwner
为整个应用过程提供生命周期监控。
在第一个Activity创建,最后一个Activity停止时,触发回调。可用于监控应用是否进入前后台。
使用方法
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");
}
}
}
源码
@Suppress("DEPRECATION")
internal fun attach(context: Context) {
handler = Handler()
registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
val app = context.applicationContext as Application
//监听Activity
app.registerActivityLifecycleCallbacks(
object : EmptyActivityLifecycleCallbacks() {
@RequiresApi(29)
override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) {
// We need the ProcessLifecycleOwner to get ON_START and ON_RESUME precisely
// before the first activity gets its LifecycleOwner started/resumed.
// The activity's LifecycleOwner gets started/resumed via an activity registered
// callback added in onCreate(). By adding our own activity registered callback
// in
// onActivityPreCreated(), we get our callbacks first while still having the
// right relative order compared to the Activity's onStart()/onResume()
// callbacks.
//给Activity注册监听事件
Api29Impl.registerActivityLifecycleCallbacks(
activity,
object : EmptyActivityLifecycleCallbacks() {
override fun onActivityPostStarted(activity: Activity) {
activityStarted()
}
override fun onActivityPostResumed(activity: Activity) {
activityResumed()
}
}
)
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
// Only use ReportFragment pre API 29 - after that, we can use the
// onActivityPostStarted and onActivityPostResumed callbacks registered in
// onActivityPreCreated()
if (Build.VERSION.SDK_INT < 29) {
activity.reportFragment.setProcessListener(initializationListener)
}
}
override fun onActivityPaused(activity: Activity) {
activityPaused()
}
override fun onActivityStopped(activity: Activity) {
activityStopped()
}
}
)
}
//activity计数,和状态
internal fun activityStarted() {
startedCounter++
if (startedCounter == 1 && stopSent) {
registry.handleLifecycleEvent(Lifecycle.Event.ON_START)
stopSent = false
}
}
internal fun activityResumed() {
resumedCounter++
if (resumedCounter == 1) {
if (pauseSent) {
registry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
pauseSent = false
} else {
handler!!.removeCallbacks(delayedPauseRunnable)
}
}
}
internal fun activityPaused() {
resumedCounter--
if (resumedCounter == 0) {
handler!!.postDelayed(delayedPauseRunnable, TIMEOUT_MS)
}
}
internal fun activityStopped() {
startedCounter--
dispatchStopIfNeeded()
}
internal fun dispatchPauseIfNeeded() {
if (resumedCounter == 0) {
pauseSent = true
registry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
}
}
internal fun dispatchStopIfNeeded() {
if (startedCounter == 0 && pauseSent) {
registry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
stopSent = true
}
}