目录
2.创建Service继承自LifecycleService
6.在activity中启动和停止service,查看输出结果
一、LifeCycle作用
让自定义组件能够感受到生命周期的变化,在自定义组件内部就可以管理好其生命周期,避免内存泄漏,降低模块间耦合度。
二、LifeCycle
1.实现LifeCycleObserver接口
使自定义组件实现LifeCycleObserver接口
open class LocationComponent(
var context: Activity,
var onLocationChangedListener: OnLocationChangedListener
) : LifecycleObserver {
val TAG = "LocationComponent"
}
2.注解生命周期相关方法
使用@OnLifecycleEvent注解对自定义组件的方法进行注解,使被注解的方法能感知Activity/Fragment/Service/Application的生命周期。
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun startGetLocation() {
Log.d(TAG, "startGetLocation")
RxLocationTool.registerLocation(
context,
1000,
5,
object : RxLocationTool.OnLocationChangeListener {
override fun getLastKnownLocation(location: Location) {
}
override fun onLocationChanged(location: Location) {
Log.d(
TAG,
"onLocationChanged latitude:${location.latitude} longitude: ${location.longitude}"
)
onLocationChangedListener.onChanged(location)
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
}
})
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stopGetLocation() {
Log.d(TAG, "stopGetLocation")
RxLocationTool.unRegisterLocation()
}
注解参数有以下值,分别对应生命周期的对应阶段
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,