Android新组件架构——Lifecylce
本篇文章已授权微信公众号guolin_blog(郭霖)独家发布
在过去和今年的谷歌IO大会上,Google推出了许多新的组件架构,个人也在慢慢接触学习这些新的组件架构。今天给大家介绍的一个能处理 Activity 和 Fragment 生命周期的组件 —— Lifecycle.
官网(科学上网):https://developer.android.com/topic/libraries/architecture/lifecycle
简单案例
class MainActivity : AppCompatActivity() {
private var lifeListenter:LifeListenter?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifeListenter= LifeListenter()
lifecycle.addObserver(lifeListenter!!)
}
}
open class LifeListenter : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(owner: LifecycleOwner) {
Log.e("TAG-----CREATE", "CREATE")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart(owner: LifecycleOwner) {
Log.e("TAG-----START", "START")
}
@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")
}
}
打印的Log:
06-03 22:20:00.242 20096-20096/com.lifecycle.lifecycle E/TAG-----CREATE: CREATE
06-03 22:20:00.242 20096-20096/com.lifecycle.lifecycle E/TAG-----START: START
06-03 22:20:00.252 20096-20096/com.lifecycle.lifecycle E/TAG-----RESUME: RESUME
//关掉APP
06-03 22:21:29.822 20723-20723/com.lifecycle.lifecycle E/TAG-----DESTROY: DESTROY
可以看出来,我们可以清楚的知道 actvity 的生命周期,并且只写了 一行代码 lifecycle.addObserver(lifeListenter!!)。
那么有人要就会问,这个组件能干嘛?
学会了这个之后,就不需要再去写那些类似调用并且会导致 onCreate() 和 onDestroy() 臃肿的方法。
例如:那些需要在 onCreate 方法中初始化,在 onStop 进行一些处理,onDestoty 进行释放的操作。(MVP 中的 Presenter,MediaPlayerd等)。
使用:
首先需要知道三个关键的东西:
1.LifecycleOwner
生命周期的事件分发者,在 Activity/Fragment 他们的生命周期发生变化的时候 发出相应的 Event 给LifecycleRegistry。
2.LifecycleObserver
生命周期的观察者,通过注解将处理函数与希望监听的Event绑定,当相应的Event发生时,LifecycleRegistry会通知相应的函数进行处理。
3.LifecycleRegistry
控制中心。它负责控制state的转换、接受分发event事件
通过上面的案例就可以知道,在我们需要对 生命周期进行监听的类中
1.继承自 LifecycleObserver
2.在类的方法上 加上注解 @OnLifecycleEvent(Lifecycle.Event.XXXX)
3.在类的方法加上 LifecycleOwner 作为参数
4.在 Activity/Fragment 中 实例化类后 加上 getLifecycle().addObserver(xxx)/Kotlin是( lifecycle.addObserver(xxxx));
其中类的注解方法有如下:
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
}
原理分析:
既然他这么方便就能处理 Activity/Fragment 的生命周期,我们肯定要去知道为什么他可以这样的。
//入口:
lifecycle.addObserver(lifeListenter!!)
点击 addObserver 发现他是 Lifecycle 一个抽象方法。
点击 lifecycle 。
//跟进
@Override
public Lifecycle getLifecycle() {
return super.getLifecycle();
}
//继续跟进....
在 SupportActivity 中
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
由: LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
可以知道 mLifecycleRegistry 是 LifecycleRegistry 的对象
跟进 LifecycleRegistry :
//在这个类中他继承自 Lifecycle ,所以 Activirty 的addObserver 实际是 LifecycleRegistry 的
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//把带着状态的 observer 封装成 ObserverWithState
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
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
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//getCallback() 通过不同的 observer 放回不同的 mLifecycleObserver
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
跟进 getCallbak()
@NonNull
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();
//跟进(1)这个方法,看下面的跟进
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> constructors =
sClassToAdapters.get(klass);
//这里是在获取到构造方法后,根据数量创建不同的 GeneratedAdapteObserver
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);
}
return new ReflectiveGenericLifecycleObserver(object);
}
(1).一直跟进到这里,可以发现上面我们跟进的方法就是通过反射,获取构造方法
@Nullable
private static Constructor<? extends GeneratedAdapter> generatedConstructor(Class<?> klass) {
try {
Package aPackage = klass.getPackage();
String name = klass.getCanonicalName();
final String fullPackage = aPackage != null ? aPackage.getName() : "";
final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
name.substring(fullPackage.length() + 1));
@SuppressWarnings("unchecked") final Class<? extends GeneratedAdapter> aClass =
(Class<? extends GeneratedAdapter>) Class.forName(
fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
Constructor<? extends GeneratedAdapter> constructor =
aClass.getDeclaredConstructor(klass);
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return constructor;
} catch (ClassNotFoundException e) {
return null;
} catch (NoSuchMethodException e) {
// this should not happen
throw new RuntimeException(e);
}
}
------------------------------------------------------
我们继续跟进其中一个 GeneratedAdapte 以:SingleGeneratedAdapterObserver 为例
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver {
private final GeneratedAdapter mGeneratedAdapter;
SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
mGeneratedAdapter = generatedAdapter;
}
//这里有个 onStateChanged 方法,用于状态改变
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
mGeneratedAdapter.callMethods(source, event, false, null);
mGeneratedAdapter.callMethods(source, event, true, null);
}
}
//让我们回到 ObserverWithState 中,可以知道 这里的 onStateChanged 就是我们上面生成的 SingleGeneratedAdapterObserver 里面的方法。
void dispatchEvent(LifecycleOwner owner, Event event) {
//得到 State
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
总结一下:
acitivty 中调用 LifecycleRegistry 的 ddObserver (实际是 LifecycleRegistry 的)
LifecycleObserver 被封装成了 ObserverWithState 并存入我们集合中,
在 ObserverWithState 中,调用了 Lifecycling.getCallback(observer)
getCallback(observer) 调用了createGeneratedAdapter()
createGeneratedAdapter通过构造方法的数量,反射生成了不同的 GenericLifecycleObserver 对象
在ObserverWithState的dispatchEvent()方法调用了GenericLifecycleObserver 对象的onStateChanged方法,
回到 SuppertActivity 中
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
//可以知道这里创建了 ReportFragment
//在 ReportFragment 中 可以发现他和我们的 Activity 关联,并且在生命周期方法中都掉去分发一个 event,跟进一下
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) lifecycle).handleLifecycleEvent(event);
}
}
}
//而 handleLifecycleEvent 方法是在 LifecycleRegistry 去调用并且会去执行
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);//获取下一个state
moveToState(next);
}
分析之前 看一下官网的图:
lifecycle-states.png
什么意思呢 大概意思就是可以通过不同的 events 知道不同的 States 。例如:当你的 events 是
ON_RESUME 的时候就代表他当前的 State 是 STARTE 所以 next State 就是 RESUMED,
分析 getStateAfter:
//对照着表其实很简单, events 是 ON_CREATE 和 ON_STOP 的下一个状态指向都是 CREATED,所以返回 CREATED,其他的类似。
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;
}
所以 getStateAfter 获取的是下一个 State 也就是下一个生命周期。
那么 moveToState(next); 呢?
rivate void moveToState(State next) {
//判断 当前 state 是不是 等于我们上面获取的
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;
}
// 当前的 State 和最早的 State 或最新的 State 进行比较。
// mObserverMap 这个集合存放的是 ObserverWithState ,而 ObserverWithState 有我们的状态
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;
}
//第一个while循坏遍历我们存储观察者的集合,
//第二个是要处理各个状态经过的event
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);
//upEvent 返回所要经历的event
//例如:当前是 STARTED , 那么他的经过的 events 就是 ON_RESUME
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
private void backwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
// downEvent 返回下一个 events
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
这两个都会执行 observer.dispatchEvent (),而这个方法就会去改变 State ,从而我们就知道了生命周期的变化。附上一个简单的流程图:
LifecycleRegistry.png