为什么需要Lifecycle组件,这些就不具体细讲了。网上很多关于该类文章。参考​​Android 架构组件(一)——Lifecycle​​。下面主要描述无法找到类DefaultLifecycleObserver的情况(SDK29)。

此时我们查看一下Lifecycle包的情况。

Lifecycle_Lifecycle


发现的确没有DefaultLifecycleObserver的class或者interface。那么如果我们想实现DefaultLifecycleObserver的效果该怎么做呢?代码如下。

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
class LifecycleDeno implements LifecycleObserver {
private static final String TAG = "LifecycleDeno";

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate(LifecycleOwner owner) {
Log.d(TAG, "onCreate: ");
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart(LifecycleOwner owner) {
Log.d(TAG, "onStart: ");
}

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume(LifecycleOwner owner) {
Log.d(TAG, "onResume: ");
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(LifecycleOwner owner) {
Log.d(TAG, "onPause: ");
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop(LifecycleOwner owner) {
Log.d(TAG, "onStop: ");
}

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy(LifecycleOwner owner) {
Log.d(TAG, "onDestroy: ");
}

}

Lifecycle_Lifecycle_02

此时用户可能会觉得奇怪​​@OnLifecycleEvent​​是什么东西呢?其实这就是Java注解类​​@interface​​的用法我们将在下一章中讲解。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OnLifecycleEvent {
Lifecycle.Event value();
}

参考文章:https://www.jianshu.com/p/22295c0a48ee