俗话说工欲善其事必先利其器,研究源码前首先得熟悉这个架构组件怎么用,还好官方文档介绍详细官网介绍,官方项目例子官方例子
看截图,浅蓝色字体部分就是今天文章要讲的内容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();
}
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.+'
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 {
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
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();
}
}
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) lifecycle).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;
}
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 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> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry 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();
}
}
}
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
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--;
}
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> 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
.>singletonList(constructor));
return GENERATED_CALLBACK;
}
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
Class> superclass = klass.getSuperclass();
List> 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);
}
}
看截图,build项目以后果然自动生成了一个类,同时看一下app/build.gradle
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0'
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
mGeneratedAdapter.callMethods(source, event, false, null);
mGeneratedAdapter.callMethods(source, event, true, null);
}
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;
}
}
}
ActivityDaiLi_LifecycleAdapter(ActivityDaiLi receiver) {
this.mReceiver = receiver;
}