远古监听生命周期方式
// 接口定义
public interface LifeListener {
void onCreate();
void onDestroy();
void onResume();
}
// 实现类
public class Book implements LifeListener{
private final String TAG = Book.class.getSimpleName();
@Override
public void onCreate() {
Log.e(TAG, " --- onCreate: --- ");
}
@Override
public void onDestroy() {
Log.e(TAG, " --- onDestroy: --- ");
}
@Override
public void onResume() {
Log.e(TAG, " --- onResume: --- ");
}
}
// 在 Activity 的生命周期中调用监听方法
public class MainActivity extends AppCompatActivity {
private Book book = new Book();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
book.onCreate();
}
@Override
protected void onResume() {
super.onResume();
book.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
book.onDestroy();
}
}
这种方式耦合度太高,不符合我们的开发规范,需要解耦合,Lifecycle应运而生
Lifecycle 监听生命周期方式
Lifecycle的使用
观察者实现 LifecycleObserver 接口,被观察者实现 LifecycleOwner 接口
// 观察者
public class Student implements LifecycleObserver {
}
// 被观察者 AppCompatActivity-FragmentActivity-ComponentActivity
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
}
具体实现代码如下
// 观察者
public class Student implements LifecycleObserver {
private final String TAG = Student.class.getSimpleName();
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreateX(){
Log.e(TAG, " --- onCreateX --- " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResumeX(){
Log.e(TAG, " --- onResumeX --- " );
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroyX(){
Log.e(TAG, " --- onDestroyX --- " );
}
}
// 被观察者
public class MainActivity extends AppCompatActivity {
private Student student = new Student();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 添加本 activity 的观察者
getLifecycle().addObserver(student);
}
}
如此一来 student 即可实现对 activity 的生命周期监听
Lifecycle 实现原理
分两步走:
- 观察者的注册
- 被观察通知观察者
观察者的注册
从这里开始
// 此处当做起点
getLifecycle().addObserver(student);
// --------- addObserver(student) ---------
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 包装为observer,从这进去。 observer 就是 student
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
....
}
// --------- ObserverWithState(observer, initialState) ---------
ObserverWithState(LifecycleObserver observer, State initialState) {
// 继续包装,从这深入
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
// --------- lifecycleEventObserver(observer) ---------
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);
}
// 上面那段代码没啥用,继续从这深入,此处的 object 依旧是 student
return new ReflectiveGenericLifecycleObserver(object);
}
// --------- ReflectiveGenericLifecycleObserver(object) ---------
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
// 此处把 student 的类信息给过去了,这玩意一般是反射用的,继续深入
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
// --------- getInfo(mWrapped.getClass()) ---------
CallbackInfo getInfo(Class klass) {
// 第一次过来肯定是不存在的
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
// 继续深入
existing = createInfo(klass, null);
return existing;
}
// --------- createInfo(klass, null) ---------
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
// 拿到类中所有方法的反射对象
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
for (Method method : methods) {
// 找到有注解标记的方法
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
// 没有注解标记的方法放过
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
// 拿到方法的参数
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(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
// 获取我们填入的 Lifecycle.Event.ON_CREATE 等等
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(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"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);
// 把 methodReference 存入,即把 methodReference 放入 handlerToEvent 中
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
// 再做一层包装 handlerToEvent,把所有有注解的方法都存起来了,用的时候从这取就行
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
// --------- verifyAndPutHandler(handlerToEvent, methodReference, event, klass) ---------
private void verifyAndPutHandler(Map<MethodReference, Lifecycle.Event> handlers,
MethodReference newHandler, Lifecycle.Event newEvent, Class klass) {
Lifecycle.Event event = handlers.get(newHandler);
// 把方法的反射与参数放入 handlers 中
if (event != null && newEvent != event) {
Method method = newHandler.mMethod;
throw new IllegalArgumentException(
"Method " + method.getName() + " in " + klass.getName()
+ " already declared with different @OnLifecycleEvent value: previous"
+ " value " + event + ", new value " + newEvent);
}
if (event == null) {
handlers.put(newHandler, newEvent);
}
}
总结:getLifecycle().addObserver(student)
的作用是把有注解的方法的发射对象存起来,当Activity生命周期变化时调用对应的方法即可。
被观察者通知观察者
从ComponentActivity看起
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
// 这是起点 -- 如果需要,在这里注入
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
// --------- ReportFragment.injectIfNeededIn(this); ---------
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
// 这部分代码就跟 glide 很像了,覆盖一个空白的fragment(不带UI)得到感知生命周期的能力,static方法,
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.
// 发送一个消息,尽快生成fragment
manager.executePendingTransactions();
}
}
观察 ReportFragment.java 的各个生命周期函数,会发现很多相似的代码,比如 onStart() 方法
@Override
public void onStart() {
super.onStart();
// 基本都有下面两个方法
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
// 先说 dispatchStart(mProcessListener) 此方法只有onCreate、onStart、onResume三个方法有,都是没有UI之前的,使用此方法分发
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) ---------
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
// 此处会用到枚举
State next = getStateAfter(event);
moveToState(next);
}
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);
}
根据这张图能拿到状态
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;
// 在这深入
sync();
mHandlingEvent = false;
}
// --------- 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;
}
// --------- forwardPass(lifecycleOwner) ---------
private void forwardPass(LifecycleOwner lifecycleOwner) {
// ObserverWithState 这个东西记录了反射对象以及状态
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);
// 进行事件分发,upEvent(observer.mState)得到事件
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
// --------- observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState)) ---------
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
// 事件分发,找实现类
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
// --------- forwardPass(lifecycleOwner) ---------
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
// 之前在此获得反射信息的,可以看上面笔记
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
// 反射调用
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
总结:Lifecycle监听生命周期的方式不算新鲜,跟glide的实现方式差不多,都是在当前Activity上覆盖一个fragment监听生命周期变化。使用注解获取标记生命周期的方法及其各自状态,当生命周期变动时使用反射对象,达到一个生命周期监听的效果。