俗话说工欲善其事必先利其器,研究源码前首先得熟悉这个架构组件怎么用,还好官方文档介绍详细官网介绍,官方项目例子官方例子
看截图,浅蓝色字体部分就是今天文章要讲的内容LiveData、ViewModel、LifecycleObserver、LifecycleOwner这四个类的使用以及源码分析,利用好这几个类可以实现ui和data的分离,data层的数据共享,数据刷新与生命周期绑定避免因生命周期引起的闪退。今天讲的重点是LifecycleObserver、LifecycleOwner
进入LifecycleOwner,发现它只是一个接口,里面只有一个getLifecycle方法需要实现
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
@NonNull
Lifecycle getLifecycle();
}
而 LifecycleObserver只是一个接口连要实现的方法都没有,这里可以看出这个接口只是用来声明这个对象属于一种类型,这属于多态性的一种应用。
public interface LifecycleObserver {
}
根据官方文档提供的解释,这里写一个小例子测试一下
public class ActivityDaiLi implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void start(LifecycleOwner activity) {
// connect
Log.i("huoying","ON_START");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume(LifecycleOwner activity)
{
Log.i("huoying","onResume");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy(){
Log.i("huoying","onDestroy");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void stop(LifecycleOwner activity) {
// disconnect if connected
Log.i("huoying","ON_STOP");
}
可以看出这里随便建了一个类实现
LifecycleObserver ,然后采用了注解方式表明这个方法是在那个生命周期里回调,最后在需要监听它生命周期的activity中加入getLifecycle().addObserver(new ActivityDaiLi())。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
getLifecycle().addObserver(new ActivityDaiLi());
}
这里注意了只有高版本的兼容包才有
getLifecycle()方法,这里采用的环境如下 环境:android studio2.3.3
com.android.tools.build:gradle:2.3.3
配置:
compile 'com.android.support:appcompat-v7:26.+'
也就是说在高版本兼容库中,我们可以直接采用以上方法将生命周期给代理出来,还记得没有这些类之前,比如用第三方的库,有时一些功能需要和activity的生命周期绑定,以前的做法是写一个基类,在基类方法中处理,更好一点是在此基础上加上生命周期的代理类,来处理生命周期相关的内容。这里采用 LifecycleObserver 用法的意义就是将客户端要在生命周期处理的内容给扩展出去了,比如这里用百度地图
MainActivity m=(MainActivity) activity;
m.mapView.onResume();
控制mapView的生命周期,做一些事情。这里有个问题假如用的是低版本兼容库呢,很遗憾,LifeCycle库和这个库不兼容,当然还是可以实现此效果,不过得写额外的代码。
这种情况官方文档也有介绍,ok看看官方给我提供的例子代码
ublic class MyActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
}
@Override
public void onStart() {
super.onStart();
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
可以看出只要在我们的基类实现implements LifecycleOwner接口,然后实现getLifecycle,当然LifecycleRegistry这个类是官方提供的默认事件注册类,没有必要自己再写一个,最后在你想要监听的生命周期中通知mLifecycleRegistry.markState,生命周期改变。
看LifecycleObserver这个接口的英文右半部分,是不是标记它为观察者,也就是常用的模式之一:观察者模式。ok,那么可以理解为,我们写的ActivityDaiLi 为观察者,而activity为被观察者,只不过它的被观察者的实现放在了LifecycleRegistry处理。好用法已经介绍完了,接下来介绍这几个相关类的源码是怎么实现的。
public class SupportActivity extends Activity implements LifecycleOwner {
高版本的兼容库最终是在上面这个类中实现了LifecycleOwner 接口,这就和官方文档介绍的吻合了
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
实现方法最终返回的是 LifecycleRegistry (被观察者真正实现类),但是这个基类没有没有实现所有生命周期方法的通知,只在onCreate方法中实现了这个小东西
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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
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();
}
}
可以看到这里加入了一个没有视图的Frament,是不是有点眼熟,Glide图片框架就是采用了默认加一个frament来生命周期的控制图片的下载。
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;
}
默认加的 ReportFragment 得生命周期里面充斥着对观察者的通知,最后的通知是下面这个方法
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);
}
}
}
还记得上面的activity实现的是 LifecycleOwner 接口吗,最后通过获得 handleLifecycleEvent方法将事件发回去。继续跟进handleLifecycleEvent方法
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;
}
这个方法首先判断了下一个状态是否和当前状态一样,一样的话,那么不做处理,然后 mHandlingEvent 判断事件是否在分发,在分发不处理, mAddingObserverCounter 参数默认为0,这个参数没有特殊处理,可能谷歌留有备用,那么,接下来最后调用 sync方法进行处理。
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;
}
这里的
mLifecycleOwner就是activity实现的接口,这里用弱引用保存,首先判断activity是否被回收,也就是防止手贱突然退出容易造成activity不能及时回收,然后开始遍历我们上面注册的观察者对象,判断要执行的生命周期状态和保存的观者者对应的状态是否一样,假如要执行的状态小于第一个状态,那么从数组后面开始遍历观察者,反之从数组前面开始遍历观察者对象。这里只看一从数组前面开始遍历
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);
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
这句话的意思就是遍历客户端注册的观察者,进行状态合理化判断,最后通过 observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));进行分发消息。这个observe并不是上面我们声明的那个类,而是 ObserverWithState故名思议起这个名字就是即包括观察者对象又持有状态类对象,如下所示
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
而持有的观察者对象也不是上面声明的的ActivityDaiLi,而是它的包装类GenericLifecycleObserver ,那么 ObserverWithState 肯定是在 addObserver方法中添加的
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
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 对象,那么接着跟进看看修饰 LifecycleObserver对象到底是何许人也,
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);
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);
}
首先判断LifecycleObserver是否是
FullLifecycleObserver、GenericLifecycleObserver,此处当然不是,那么接着调用getObserverConstructorType方法获取class的类型参数
private static int resolveObserverCallbackType(Class<?> klass) {
// anonymous class bug:35073837
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
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;
}
首先获得class文件的名字,然后通过
generatedConstructor获得反射中的构造者对象,如果不为null,那么返回主方法执行,进入这个获得构造器的方法
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);
}
}
看个方法,有没有发现最后的class是通过 Class.forName获得,而参数居然是全拼的,包名和我们项目的包名保持一致,项目中,我们果断没有声明这个类,接触过注解框架的此时应该疑问是否是apt帮我们生成的这个类,好找一下
看截图,build项目以后果然自动生成了一个类,同时看一下app/build.gradle
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0'
也难怪官方文档会让我们加这个配置,这个配置就是告诉编译器在编译阶段调用 lifecycle:compiler库的逻辑生成我们想要的文件,这个原理和ButterNnife框架、Dragger2框架等(编译期注解框架)功能一样,这里不做过多解释,也就是说lifecycle框架最终会为我们的ActivityDaiLi产生一个对象适配器类 ActivityDaiLi_LifecycleAdapter,再将适配器对象用 SingleGeneratedAdapterObserver包装起来,最后通知观察者对象先通过SingleGeneratedAdapterObserver一步一步的转发。
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
也就是通过onStateChanged方法告诉SingleGeneratedAdapterObserver被观察者状态改变,
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
mGeneratedAdapter.callMethods(source, event, false, null);
mGeneratedAdapter.callMethods(source, event, true, null);
}
最终直接将方法调用转交给框架产生的 ActivityDaiLi_LifecycleAdapter方法
public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
MethodCallsLogger logger) {
boolean hasLogger = logger != null;
if (onAny) {
return;
}
if (event == Lifecycle.Event.ON_START) {
if (!hasLogger || logger.approveCall("start", 2)) {
mReceiver.start(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", 1)) {
mReceiver.onDestroy();
}
return;
}
if (event == Lifecycle.Event.ON_STOP) {
if (!hasLogger || logger.approveCall("stop", 2)) {
mReceiver.stop(owner);
}
return;
}
}
}
look,这就是最终的调用方法, 而mReceiver就是自己创建的的ActivityDaiLi 对象
ActivityDaiLi_LifecycleAdapter(ActivityDaiLi receiver) {
this.mReceiver = receiver;
}
最后就是判断是声明周期的哪一个方法,然后进行相应的回调了。