Jetpack 是一套库、工具和指南,可帮助开发者更轻松地编写优质应用。这些组件可帮助您遵循最佳做法、让您摆脱编写样板代码的工作并简化复杂任务,以便您将精力集中放在所需的代码上。
Jetpack 包含与平台 API 解除捆绑的 androidx.* (android.*)软件包库。这意味着,它可以提供向后兼容性,且比 Android 平台的更新频率更高,以此确保您始终可以获取最新且最好的 Jetpack 组件版本。
官方网址介绍:Android jetpack介绍
Android Jetpack组件的优势:
1.管理应用程序(Activity、Fragment)的生命周期(如后台任务、导航和生命周期管理)
2.构建可观察的数据对象,以便在基础数据库更改时通知视图(View)
3.存储在应用程序轮换中未销毁的UI相关数据,在界面重建后恢复数据
4.轻松的实现SQLite数据库
5.系统自动调度后台任务的执行,优化使用性能
Lifecycles是一个持有组件生命周期状态(Activity、Fragment)信息的类,用来解决生命周期管理问题的组件。通过监听生命周期的方式(Handling Lifecycles with Lifecycle-Aware Components),并允许其他对象观察此状态。生命周期使用两个主要枚举来跟踪其关联组件的生命周期状态:
1.Event:从框架和Lifecycle类派发的生命周期事件。 这些事件映射到活动和片段中的回调事件。
2.State:由Lifecycle对象跟踪的组件的当前状态。
Event和State的对应关系如下图:Android Developer官网关于State 的转化图
def lifecycle_version = "2.0.0"
// alternatively - Lifecycles only (no ViewModel or LiveData). Some UI
// AndroidX libraries use this lightweight import for Lifecycle
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
// For Kotlin use kapt instead of annotationProcessor
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
1.创建MyCustomLifecycles 继承 LifecycleObserver
2.使用注解在每个方法上标记相应的生命周期
注意定义的方法里面的参数,Lifecycles对于参数是有要求的。具体原因分析源码的时候会具体分析(参考3.2.2)
1.如果参数个数大于0。第一个参数必须是LifecycleOwner或者是LifecycleOwner的超类
2.参数个数不大于1时,第一个参数同1第,二个参数必须是Lifecycle.Event或者是Lifecycle.Event的超类,而且注解的Event必须是Lifecycle.Event.ON_ANY
3.参数个数最大是2。否则会出现非法状态异常
class MyCustomLifecycles() : LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
fun onCreate(lifecycleOwner: LifecycleOwner,event :Lifecycle.Event = Lifecycle.Event.ON_ANY ){
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume(){
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy(){
}
}
interface MyCallback{
fun test()
}
如果是支持Java8的话,并且gradle引用了** implementation “androidx.lifecycle:lifecycle-common-java8:$lifecycle_version”` **也可以这么声明
class MyCustomj8Lifecycles : DefaultLifecycleObserver{
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
}
}
/**
**已经弃用了
**/
public class MyGenericLifecycles : GenericLifeCycleObserver {
}
class DataBindingActivity : AppCompatActivity(),LifecycleOwner{
}
在v4包中SupportActivity已经实现了LifecycleOwner。注意是v4包下,不是androidX下面的。代码如下
public class SupportActivity extends Activity implements LifecycleOwner, Component {
private SimpleArrayMap, SupportActivity.ExtraData> mExtraDataMap = new SimpleArrayMap();
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public SupportActivity() {
}
}
所以如果你的Activity已经继承SupportActivity,因为在v4包中SupportActivity已经实现了LifecycleOwner。可以省略如下代码
private lateinit var lifeCycleRegistry: LifecycleRegistry
private lateinit var myCustomLifecycles: MyCustomLifecycles
override fun getLifecycle(): Lifecycle {
return lifeCycleRegistry
}
在addObserver方法中会涉及到自定义Observer的解析。
myCustomLifecycles = MyCustomLifecycles()
lifecycle.addObserver(myCustomLifecycles)
注意点:如果你的Activity继承的是v4包下的AppCompatActivity可以忽略该步骤,observer依旧可以相应Observer的Event注解的方法。但是如果是androidx.appcompat.app.AppCompatActivity,必须在Activity的生命周期中使用markState方法,否则注解的方法无法得到执行。不可以忽略该步骤,具体原因后面会分析。
lifeCycleRegistry.markState(Lifecycle.State.CREATED)
lifeCycleRegistry.markState(Lifecycle.State.RESUMED)
完整类代码如下:
class DataBindingActivity : AppCompatActivity(),LifecycleOwner{
private lateinit var lifeCycleRegistry: LifecycleRegistry
private lateinit var myCustomLifecycles: MyCustomLifecycles
override fun getLifecycle(): Lifecycle {
return lifeCycleRegistry
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifeCycleRegistry = LifecycleRegistry(this)
myCustomLifecycles = MyCustomLifecycles()
lifecycle.addObserver(myCustomLifecycles)
lifeCycleRegistry.markState(Lifecycle.State.CREATED)
}
override fun onResume() {
lifeCycleRegistry.markState(Lifecycle.State.RESUMED)
super.onResume()
}
}
我们都知道Lifecycles是感应Activity的生命周期的,那么在使用Lifecycles时主要有一下几个疑问:
1.在Activity的生命周期发生变化的时候,LifecycleObserver声明的注解方法是怎么被触发的。
2.触发注解方法以后,注解的方法怎么被执行的。
下面就带着这几个疑问分析一下源码
在分析源代码之前,先了解一下SafeIterableMap类(非线程安全),因为在类LifecycleRegistry中会用到FastSafeIterableMapinterface SupportRemove
)。适用于数据量存储不大的场景。
具有如下优点:
1.SafeIterableMap 的插入操作是时间复杂度O(1)直接通过指针的移动插入数据,而且不需要执行hash算法,效率高。
2.遍历的过程中删除元素而不触发ConcurrentModifiedException。
3.使用双向链表来存储会比 HashMap (java 8 红黑树)节省内存空间。
介绍SafeIterableMap中get、put、remove、putIfAbsent方法
protected Entry get(K k) {
Entry currentNode = mStart;
while (currentNode != null) {
if (currentNode.mKey.equals(k)) {
break;
}
currentNode = currentNode.mNext;
}
return currentNode;
}
protected Entry put(@NonNull K key, @NonNull V v) {
Entry newEntry = new Entry<>(key, v);
mSize++;
if (mEnd == null) {
mStart = newEntry;
mEnd = mStart;
return newEntry;
}
mEnd.mNext = newEntry;
newEntry.mPrevious = mEnd;
mEnd = newEntry;
return newEntry;
}
public V putIfAbsent(@NonNull K key, @NonNull V v) {
Entry entry = get(key);
if (entry != null) {
return entry.mValue;
}
put(key, v);
return null;
}
public V remove(@NonNull K key) {
Entry toRemove = get(key);
if (toRemove == null) {
return null;
}
mSize--;
if (!mIterators.isEmpty()) {
for (SupportRemove iter : mIterators.keySet()) {
iter.supportRemove(toRemove);
}
}
if (toRemove.mPrevious != null) {
toRemove.mPrevious.mNext = toRemove.mNext;
} else {
mStart = toRemove.mNext;
}
if (toRemove.mNext != null) {
toRemove.mNext.mPrevious = toRemove.mPrevious;
} else {
mEnd = toRemove.mPrevious;
}
toRemove.mNext = null;
toRemove.mPrevious = null;
return toRemove.mValue;
}
private WeakHashMap, Boolean> mIterators = new WeakHashMap<>();
public Iterator> iterator() {
ListIterator iterator = new AscendingIterator<>(mStart, mEnd);
mIterators.put(iterator, false);
return iterator;
}
public Iterator> descendingIterator() {
DescendingIterator iterator = new DescendingIterator<>(mEnd, mStart);
mIterators.put(iterator, false);
return iterator;
}
public IteratorWithAdditions iteratorWithAdditions() {
IteratorWithAdditions iterator = new IteratorWithAdditions();
mIterators.put(iterator, false);
return iterator;
}
SupportRemove接口有两个实现类,每当删除元素,而且mIterators不是空时,会调用这个方法对entry进行删除。SupportRemove通过调整尾指针和下一个元素的指针,达到安全遍历的效果。
IteratorWithAdditions
private class IteratorWithAdditions implements Iterator>, SupportRemove {
@Override
public void supportRemove(@NonNull Entry entry) {
}
}
ListIterator有两个子类
private abstract static class ListIterator implements Iterator>,
SupportRemove {
@Override
public void supportRemove(@NonNull Entry entry) {
}
}
private static class AscendingIterator extends ListIterator {
}
private static class DescendingIterator extends ListIterator {
}
以网上比较全的一张图来说明,其中设计到的主要类的类关系图。
Lifecycle组件成员Lifecycle被定义成了抽象类,LifecycleOwner、LifecycleObserver被定义成了接口。
组件(Activity、Fragment)实现了LifecycleOwner接口,该只有一个返回Lifecycle对象的方法getLifecyle(): LifecycleRegistry。
Lifecycle的内部类State标明状态、Event表示事件
ObserverWithState的成员变量GenericLifecycleObserver继承自LifecycleObserver
Fragment中getLifecycle()方法返回的是继承了抽象类Lifecycle的LifecycleRegistry。
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
...........
}
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
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;
}
}
@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();
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);
}
在getCallback根据我们在传入类不同构建不同的GenericLifecycleObserver子类,通过上下文知道,我们传入的是LifecycleObserver的子类,所以下面两个条件都不成立。
if (object instanceof FullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
}
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
s在getObserverConstructorType方法中会继续调用resolveObserverCallbackType方法,下面我们来分析该方法。
(1)代码块1:主要是看有没有生成XXX_LifecycleAdapter的类,XXX表示自定义的Observer类。在2.0.0的版本是没有的。可能是为了兼容老代码
(2)代码块2:是否有OnLifecycleEvent注解的方法。显然我们是通过注解的方式实现的。
private static int resolveObserverCallbackType(Class> klass) {
// anonymous class bug:35073837
//肯定不为null
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
//代码块1
Constructor extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
sClassToAdapters.put(klass, Collections
.>singletonList(constructor));
return GENERATED_CALLBACK;
}
//代码块2
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 ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
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);
}
}
MethodReference(int callType, Method method) {
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}
CallbackInfo里面主要是两个HashMap。
mEventToHandlers以Event作为KeyList作为value。这样存储的好处是,根据Event事件,可以快速的找到对应的所有注解方法。
mHandlerToEvent以MethodReference,Event键值对的形式存储,意识是某个注解方法对应的Event事件。
final Map> mEventToHandlers;
final Map mHandlerToEvent;
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
Class superclass = klass.getSuperclass();
Map 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 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;
//1.如果参数个数大于0。第一个参数必须是LifecycleOwner或者是LifecycleOwner的超类
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
Lifecycle.Event event = annotation.value();
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
// 2.参数个数不大于1时,第一个参数同1第,二个参数必须是Lifecycle.Event或者是Lifecycle.Event的超类,而且注解
//Event必须是Lifecycle.Event.ON_ANY
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");
}
}
//3.参数个数最大是2。否则会出现非法状态异常
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
MethodReference methodReference = new MethodReference(callType, method);
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
CallbackInfo info = new CallbackInfo(handlerToEvent);
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
在上面我们分析了自定义的Observer是如何被解析的,那么解析出来的方法method是在哪里触发执行的呢。下面我们开始分析。首先说明,如果你继承的类要是v4包中AppCompatActivity,因为在androidx中的继承关系和v4包是有区别的。在androidx下AppCompatActivity超类没有SupportActivity。 注意是v4包下,不是androidX下面的。
@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
}
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) { //初始化Fragment
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
@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);
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;
//代码1
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
对于代码1处的解释: 当正在sync中处理改变状态时 mHandlingEvent = true;当我们调用addObserver时 mAddingObserverCounter != 0以上这两种状态都是正在执行任务的状态,所以此时直接return
在getStateAfter中首先根据执行的Lifecycle.Event,判断执行事件后下一个到达的状态,然后使用moveToState()中的sync()修改活动的生命周期:
4. sync()
顾名思义是用来同步事件的。
(1)判断是否有LifecycleOwner对象,LifecycleOwner是在构造方法通过若引用初始化的。判断当前时候有其他的sync操作
2 )我们知道Lifecycle.Event和Lifecycle.State的声明顺序是和活动 的声明周期执行顺序一致的,所以对Lifecycle.State的前后顺序的比较也就反应了声明周期状态的变换,比较下一个状态和之前状态集合里面的状态大小,mObserverMap.eldest()获取的是双向链表里面的第一个数据,mObserverMap.newest()获取的是尾部数据,这样的数据结构好处就凸显出来了,可以直接获取头部和尾部指针。比如活动此时的生命周期为CREATED(此时mObserverMap中保存的状态为CREATED),而下一个变换的状态为Started(此时的mState为Started),从声明周期中可以知道此时执行的时onStart(),对应的LIfecycle.Event为onStart。
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;
}
while循环是因为有多个Observer的存在。在forwardPass()方法中会将ObserverWithState中保存的状态与mState比较,如果小于目标State。然后调用upEvent()根据保存的状态找出要执行的Event,并调用Observer的dispatEvent()方法发送事件。
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();
}
}
}
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
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;
}
}
void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
target);
}
private static void invokeMethodsForEvent(List handlers,
LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {
handlers.get(i).invokeCallback(source, event, mWrapped);
}
void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
try {
switch (mCallType) {
case CALL_TYPE_NO_ARG:
mMethod.invoke(target);
break;
case CALL_TYPE_PROVIDER:
mMethod.invoke(target, source);
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
mMethod.invoke(target, source, event);
break;
}
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to call observer method", e.getCause());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
// we consciously decided not to send destruction events here in opposition to addObserver.
// Our reasons for that:
// 1. These events haven't yet happened at all. In contrast to events in addObservers, that
// actually occurred but earlier.
// 2. There are cases when removeObserver happens as a consequence of some kind of fatal
// event. If removeObserver method sends destruction events, then a clean up routine becomes
// more cumbersome. More specific example of that is: your LifecycleObserver listens for
// a web connection, in the usual routine in OnStop method you report to a server that a
// session has just ended and you close the connection. Now let's assume now that you
// lost an internet and as a result you removed this observer. If you get destruction
// events in removeObserver, you should have a special case in your onStop method that
// checks if your web connection died and you shouldn't try to report anything to a server.
mObserverMap.remove(observer);
}