在Application初始化Lifecycle监听:
/*
*Author:XingHai.Zhao
*Purpose: Application
*/
class App : Application() {
override fun onCreate() {
super.onCreate()
//初始化Lifecycle监听
ProcessLifecycleOwner.get().lifecycle.addObserver(LifecycleChecker())
}
}
LifecycleChecker实体类:
/*
*Author:XingHai.Zhao
*Purpose:Lifecycle实体类
*/
public class LifecycleChecker implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onAppForeground() {
// 应用进入前台
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onAppBackground() {
// 应用进入后台
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private void onAppDESTROY() {
// 应用销毁
}
}
更多的生命周期只需要新创建任意名称的方法,加上该注解:@OnLifecycleEvent()
对应如下类型:
@SuppressWarnings("WeakerAccess")
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
}