没有铺垫,直接开始。
简单介绍一下 lifecycle 生命周期感知组件执行操作以响应另一个组件(例如活动和片段)的生命周期状态的更改。这样就可以简化 onCreate() 和 onDestory() 中的逻辑(PVP中Presenter)。
简单使用
class MainActivity : AppCompatActivity() {
private var lifeListenter:LifeListenter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifeListenter= LifeListenter()
//因AppCompatActivity中已经实现了LifecycleOwner接口,所以可以直接获得lifecycle
lifecycle.addObserver(lifeListenter!!)
}
}
class LifeListenter : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(owner: LifecycleOwner) {
Log.e("TAG-----CREATE", "CREATE")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume(owner: LifecycleOwner) {
Log.e("TAG-----RESUME", "RESUME")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy(owner: LifecycleOwner) {
Log.e("TAG-----DESTROY", "DESTROY")
}
// ON_ANY 注解能观察到其它所有的生命周期方法
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onLifecycleChanged(owner: LifecycleOwner){
Log.e(TAG-----CHANGED, "CHANGED")
}
}
介绍里面的关键类
Lifecycle
先看谷歌简介
`Lifecycle` is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.
Lifecycle 是一个类,它包含有关组件生命状态的信息(如Activity、Fragment),并允许其他对象观察此状态。
`Lifecycle`uses two main enumerations to track the lifecycle status for its associated component:
Lifecycle使用两个主要枚举来跟踪其关联组件的生命周期状态(Event 与 State),下面看一下这两个类。
Event
The lifecycle events that are dispatched from the framework and the `Lifecycle` class. These events map to the callback events in activities and fragments.
从框架和lifecycle类调度的生命周期事件。这些事件映射到Activity和Fragment的回调事件。
State
The current state of the component tracked by the `Lifecycle` object.
Lifecycle对象跟踪的组件的当前状态
其实Lifecycle这个类很简单,Lifecycle是个抽象类:
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 {
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;
}
}
}
LifecycleOwner
先看一下此接口,只有一个方法,这个接口的返回值为Lifecycle。(SupportActivity 和 Fragment 都实现了此接口),有没有什么想法.......LifecycleOwner生命周期的时间分发者,在Activity或Fragment的生命周期发生变化的时候发出相应的Event
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
我们看看在Activity和Fragment中此方法的返回值
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
返回的是LifecycleRegistry, LifecycleRegistry 继承了 Lifecycle
public class LifecycleRegistry extends Lifecycle {...}
LifecycleRegistry(自定义LifecycleOwner)
在api 26.1.0及更高版本中Activity和Fragment已实现该[LifecycleOwner
]接口。
如果您要创建自定义类,则 [LifecycleOwner
]可以使用 [LifecycleRegistry]类,但需要将事件转发到该类。
class MyActivity : Activity(), LifecycleOwner {
private lateinit var mLifecycleRegistry: LifecycleRegistry
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mLifecycleRegistry = LifecycleRegistry(this)
mLifecycleRegistry.markState(Lifecycle.State.CREATED)
}
public override fun onStart() {
super.onStart()
mLifecycleRegistry.markState(Lifecycle.State.STARTED)
}
override fun getLifecycle(): Lifecycle {
return mLifecycleRegistry
}
}
LifecycleRegistry是个特别重要的类,控制state转换接受以及分发event事件。看一下LifecycleRegistry添加观察者的方法 addObserver,下面的解析是整个lifecycle的重点,生命周期转换以及分发的过程。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 将initialState 和 observer包装成了ObserverWithState对象
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//mObserverMap 缓存了所有的生命周期观察者
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--;
}
ObserverWithState
ObserverWithState 是 LifecycleRegistry 的静态内部类
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//此方法将 LifecycleObserver 转成了 GenericLifecycleObserver
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
//分发Event事件
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
//mLifecycleObserver 是下文中的 SingleGeneratedAdapterObserver
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
Lifecycling
//利用适配器Adapter 把 LifeObserver 转化成 GenericLifecycleObserver,ReflectiveGenericLifecycleObserver 实现了GenericLifecycleObserver 接口
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) 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);
//将MyLifecycleActivity_LifeListenter_LifecycleAdapter 转成了SingleGeneratedAdapterObserver,而GenericLifecycleObserver实现了 SingleGeneratedAdapterObserver
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);
}
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
private static int getObserverConstructorType(Class<?> klass) {
//缓存有直接返回
if (sCallbackCache.containsKey(klass)) {
return sCallbackCache.get(klass);
}
// resolveObserverCallbackType 进行解析类型
int type = resolveObserverCallbackType(klass);
sCallbackCache.put(klass, type);
return type;
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
private static int resolveObserverCallbackType(Class<?> klass) {
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
// 通过调用 generatedConstructor 来生成了 GeneratedAdapter 的构造器,GeneratedAdapter 是LifecycleObserver的适配器,并且这里的GeneratedAdapter 的实现类通过kapt帮我们完成。在app/build/generated/source/kapt/debug目录下。此方法生成的类就是下面的类MyLifecycleActivity_LifeListenter_LifecycleAdapter
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
//直接返回
return GENERATED_CALLBACK;
}
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
Class<?> superclass = klass.getSuperclass();
List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
if (isLifecycleParent(superclass)) {
if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
}
for (Class<?> intrface : klass.getInterfaces()) {
if (!isLifecycleParent(intrface)) {
continue;
}
if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
if (adapterConstructors == null) {
adapterConstructors = new ArrayList<>();
}
adapterConstructors.addAll(sClassToAdapters.get(intrface));
}
if (adapterConstructors != null) {
sClassToAdapters.put(klass, adapterConstructors);
return GENERATED_CALLBACK;
}
return REFLECTIVE_CALLBACK;
}
下面看下kapt为我们生成的GeneratedAdapter 的实现类
public class MyLifecycleActivity_LifeListenter_LifecycleAdapter implements GeneratedAdapter {
final MyLifecycleActivity.LifeListenter mReceiver;
MyLifecycleActivity_LifeListenter_LifecycleAdapter(MyLifecycleActivity.LifeListenter receiver) {
this.mReceiver = receiver;
}
@Override
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (onAny) {
if (!hasLogger || logger.approveCall("onLifecycleChanged", 2)) {
mReceiver.onLifecycleChanged(owner);
}
return;
}
if (event == Lifecycle.Event.ON_CREATE) {
if (!hasLogger || logger.approveCall("onCreate", 2)) {
mReceiver.onCreate(owner);
}
return;
}
if (event == Lifecycle.Event.ON_RESUME) {
if (!hasLogger || logger.approveCall("onResume", 2)) {
mReceiver.onResume(owner);
}
return;
}
if (event == Lifecycle.Event.ON_DESTROY) {
if (!hasLogger || logger.approveCall("onDestroy", 2)) {
mReceiver.onDestroy(owner);
}
return;
}
}
}
细想一下大体逻辑调用顺序是这样的
Acitivty --> lifecycle.addObserver(LifecycleObserver ) --> LifecycleObserver 被封装成了 ObserverWithState 存入集合 -->Lifecycling.getCallback(observer) -->createGeneratedAdapter() --> createGeneratedAdapter生成 GenericLifecycleObserver(MyLifecycleActivity_LifeListenter_LifecycleAdapter) -->ObserverWithState .dispatchEvent() --> GenericLifecycleObserver.onStateChanged()-->Activity
也可以返过来
Activity生命周期改变 --> ObserverWithState.dispatchEvent --> SingleGeneratedAdapterObserver.onStateChanged -> MyLifecycleActivity_LifeListenter_LifecycleAdapter.callMethods -> LifeListenter.onCreate/onAny/onDestroy
还没有完,还有生命周期事件是怎么驱动的,状态值是怎么改变的。
处理生命周期的方法
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
//改变State
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;
}
}
//同步生命周期
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
+ "new events from it.");
return;
}
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;
}
下面还有几个比较重要的类
//ReportFragment 加入到了 Activity,跟随Activity的生命周期变化,执行相应的dispatch方法
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
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();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
private ActivityInitializationListener mProcessListener;
private void dispatchCreate(ActivityInitializationListener listener) {
if (listener != null) {
listener.onCreate();
}
}
private void dispatchStart(ActivityInitializationListener listener) {
if (listener != null) {
listener.onStart();
}
}
private void dispatchResume(ActivityInitializationListener listener) {
if (listener != null) {
listener.onResume();
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatchStart(mProcessListener);
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
@Override
public void onPause() {
super.onPause();
dispatch(Lifecycle.Event.ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(Lifecycle.Event.ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(Lifecycle.Event.ON_DESTROY);
// just want to be sure that we won't leak reference to an activity
mProcessListener = null;
}
//分发生命周期方法
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中的方法,至此形成一个闭环。
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
//用于分发生命周期的类
class LifecycleDispatcher {
private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}
@SuppressWarnings("WeakerAccess")
@VisibleForTesting
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
private final FragmentCallback mFragmentCallback;
DispatcherActivityCallback() {
mFragmentCallback = new FragmentCallback();
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(mFragmentCallback, true);
}
ReportFragment.injectIfNeededIn(activity);
}
@Override
public void onActivityStopped(Activity activity) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
}
@SuppressWarnings("WeakerAccess")
public static class DestructionReportFragment extends Fragment {
@Override
public void onPause() {
super.onPause();
dispatch(ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(ON_DESTROY);
}
protected void dispatch(Lifecycle.Event event) {
dispatchIfLifecycleOwner(getParentFragment(), event);
}
}
private static void markState(FragmentManager manager, State state) {
Collection<Fragment> fragments = manager.getFragments();
if (fragments == null) {
return;
}
for (Fragment fragment : fragments) {
if (fragment == null) {
continue;
}
markStateIn(fragment, state);
if (fragment.isAdded()) {
markState(fragment.getChildFragmentManager(), state);
}
}
}
private static void markStateIn(Object object, State state) {
if (object instanceof LifecycleRegistryOwner) {
LifecycleRegistry registry = ((LifecycleRegistryOwner) object).getLifecycle();
registry.markState(state);
}
}
private static void markState(FragmentActivity activity, State state) {
markStateIn(activity, state);
markState(activity.getSupportFragmentManager(), state);
}
private static void dispatchIfLifecycleOwner(Fragment fragment, Lifecycle.Event event) {
if (fragment instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) fragment).getLifecycle().handleLifecycleEvent(event);
}
}
@SuppressWarnings("WeakerAccess")
@VisibleForTesting
static class FragmentCallback extends FragmentManager.FragmentLifecycleCallbacks {
@Override
public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
dispatchIfLifecycleOwner(f, ON_CREATE);
if (!(f instanceof LifecycleRegistryOwner)) {
return;
}
if (f.getChildFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
f.getChildFragmentManager().beginTransaction().add(new DestructionReportFragment(),
REPORT_FRAGMENT_TAG).commit();
}
}
@Override
public void onFragmentStarted(FragmentManager fm, Fragment f) {
dispatchIfLifecycleOwner(f, ON_START);
}
@Override
public void onFragmentResumed(FragmentManager fm, Fragment f) {
dispatchIfLifecycleOwner(f, ON_RESUME);
}
}
}
LifecycleObserver
一个空接口,生命周期的观察者,通过注解的方式监听Event绑定。
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {}
至此,整个Lifecycle的大致流程就完结了,静下来看完源码还是有收获的,但是Lifecycle是有弊端的,以后再说吧。。。