LifeCycle的诞生:
为了解决代码解耦的问题,将系统组件和普通组件尽可能的解耦
LifeCycle应用:
- 使用Lifecycle解耦页面与组件
- 使用LifecycleService解耦Service与组件
- 使用ProcessLifecycleOwner监听应用程序生命周期
使用Lifecycle解耦页面与组件
案例:统计页面停留时间
基础逻辑实现思路:
/**
* 计时器,只显示页面停留时间,在页面进入后台,时间不再计算
* 业务的实现依赖于系统组件Activity
*/
class TestActivity : AppCompatActivity() {
private lateinit var chronometer:Chronometer
var elapsedTime:Long= 0L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test)
chronometer = findViewById<Chronometer>(R.id.chronometer)
}
override fun onResume() {
super.onResume()
chronometer.base = SystemClock.elapsedRealtime()-elapsedTime
chronometer.start()
}
override fun onPause() {
super.onPause()
elapsedTime = SystemClock.elapsedRealtime()-chronometer.base
chronometer.stop()
}
}
封装自定义组件MyChronometer,使用Lifecycle进行解耦:
class MyChronometer : Chronometer, LifecycleObserver {
var elapsedTime: Long = 0L
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
private fun startMeter() {
base = SystemClock.elapsedRealtime() - elapsedTime
start()
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
private fun stopMeter() {
elapsedTime = SystemClock.elapsedRealtime()-base
stop()
}
}
//控件使用
/**
* 计时器,只显示页面停留时间,在页面进入后台,时间不再计算
* 业务的实现依赖于系统组件Activity
*/
class TestActivity : AppCompatActivity() {
private lateinit var chronometer:MyChronometer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test)
chronometer = findViewById<MyChronometer>(R.id.chronometer)
lifecycle.addObserver(chronometer)
}
}
使用LifecycleService解耦Service与组件
案例:使用Service后台监听GPS改变
class LocationObserver(var context: Context) : LifecycleObserver {
private lateinit var locationManager: LocationManager
private lateinit var myLocationListener: MyLocationListener
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun startLocation() {
Log.d("Location", "startLocation")
locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
return
}
myLocationListener = MyLocationListener()
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
300,
10F,
myLocationListener
)
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun stopLocation() {
Log.d("Location", "stopLocation")
locationManager.removeUpdates(myLocationListener)
}
open class MyLocationListener : LocationListener {
override fun onLocationChanged(location: Location) {
Log.d("Location", "${location.latitude} --- ${location.longitude}")
}
override fun onLocationChanged(locations: MutableList<Location>) {
super.onLocationChanged(locations)
}
override fun onFlushComplete(requestCode: Int) {
super.onFlushComplete(requestCode)
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
super.onStatusChanged(provider, status, extras)
}
override fun onProviderEnabled(provider: String) {
super.onProviderEnabled(provider)
}
override fun onProviderDisabled(provider: String) {
super.onProviderDisabled(provider)
}
}
}
LocationService继承LifecycleService:
class LocationService: LifecycleService() {
init {
lifecycle.addObserver(LocationObserver(this))
}
}
启动服务:
class Test2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test2)
startService(Intent(this,LocationService::class.java))
}
}
使用ProcessLifecycleOwner监听应用程序生命周期
- 针对整个应用程序的监听,与Activity数量无关
- Lifecycle.Event.ON_CREATE只会被调用一次,Lifecycle.Event.ON_DESTROY永远不会被调用
class App: Application() {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver())
}
}
class AppLifecycleObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
Log.d("AppLifecycleObserver", "Lifecycle.Event.ON_CREATE")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
Log.d("AppLifecycleObserver", "Lifecycle.Event.ON_START")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun onResume() {
Log.d("AppLifecycleObserver", "Lifecycle.Event.ON_RESUME")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
Log.d("AppLifecycleObserver", "Lifecycle.Event.ON_PAUSE")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
Log.d("AppLifecycleObserver", "Lifecycle.Event.ON_STOP")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
Log.d("AppLifecycleObserver", "Lifecycle.Event.ON_DESTROY")
}
}
前后台切换App输出:
27761-27761 D/AppLifecycleObserver: Lifecycle.Event.ON_STOP
27994-27994 D/AppLifecycleObserver: Lifecycle.Event.ON_CREATE
27994-27994 D/AppLifecycleObserver: Lifecycle.Event.ON_START
27994-27994 D/AppLifecycleObserver: Lifecycle.Event.ON_RESUME
27994-27994 D/AppLifecycleObserver: Lifecycle.Event.ON_PAUSE
27994-27994 D/AppLifecycleObserver: Lifecycle.Event.ON_STOP