美文网首页
Android Jetpack 之 Lifecycle

Android Jetpack 之 Lifecycle

作者: xulj100 | 来源:发表于2022-03-24 00:48 被阅读0次

1、Lifecycle 介绍

Lifecycle 是android.arch.lifecycle 包下各种类和相关接口,通过该Lifecycle 组件可以让开发者构建能够感知其他组件(主要是Activity,Fragment)的生命周期的变化。也就是说通过注册Lifecycle的类,可以监听Activity或者Fragment的生命周期的变化。

2、使用 Lifecycle 解耦页面与组件

自定义一个定时器,与Activity解耦,看代码

class MyChronometer(context: Context?, attrs: AttributeSet) : Chronometer(context, attrs),
    LifecycleObserver {

    private var exitTime: Long = 0

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private fun startTime() {
        base = SystemClock.elapsedRealtime() - exitTime
        start()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private fun pauseTime() {
        exitTime = SystemClock.elapsedRealtime() - base
        stop()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun onRelease() {
        onRelease()
    }

}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <cn.kt.app.jetpack.MyChronometer
        android:id="@+id/chronometer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp" />
    <Button
        android:id="@+id/startGPS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="开始定位" />
    <Button
        android:id="@+id/stopGPS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止定位" />
</LinearLayout>
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.page_main)
        lifecycle.addObserver(chronometer)
    }
}

实现效果如下:

SVID_20220323_220028_1.gif

3、使用 LifecycleService 解耦 Service 与组件

定义一个MyLocationObserver service解耦,获取用户经纬度,看代码

class MyLocationObserver(private val mContext: Context) : LifecycleObserver {
    private lateinit var locationManager: LocationManager
    private lateinit var locationListener: MyLocationListener

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private fun startLocation() {
        Log.d(TAG, "-- startLocation")
        locationListener = MyLocationListener()
        locationManager = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (ActivityCompat.checkSelfPermission(
                mContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(
                mContext,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            3000,
            1f,
            locationListener
        )
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun stopLocation() {
        Log.d(TAG, "-- stopLocation")
        locationManager.removeUpdates(locationListener)
    }

    internal class MyLocationListener : LocationListener {
        override fun onLocationChanged(location: Location) {
            Log.d(TAG, location.toString())
        }
        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
        override fun onProviderEnabled(provider: String) {}
        override fun onProviderDisabled(provider: String) {}
    }

    companion object {
        private const val TAG = "MyLocationObserver"
    }
}
class MyLocationService : LifecycleService() {
    init {
        val observer = MyLocationObserver(this)
        lifecycle.addObserver(observer)
    }
}
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.page_main)
        lifecycle.addObserver(chronometer)
        initView();
    }

    private fun initView() {
        startGPS.setOnClickListener {
            startService(Intent(this, MyLocationService::class.java))
        }
        stopGPS.setOnClickListener {
            stopService(Intent(this, MyLocationService::class.java))
        }
    }
}
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />" />

使用命令修改经纬度位置

./adb -s emulator-5554 emu geo fix 128.22 80.11

监听到位置的变化

2022-03-24 08:37:44.836 18168-18168/cn.kt.app D/MyLocationObserver: -- startLocation
2022-03-24 08:37:48.786 18168-18168/cn.kt.app D/MyLocationObserver: Location[gps 36.880000,128.219998 hAcc=5 et=+19075d0h37m48s773ms etAcc=+1ms alt=0.0 vel=0.0 bear=0.0 vAcc=1 sAcc=1 bAcc=30 {Bundle[mParcelledData.dataSize=96]}]
2022-03-24 08:37:58.640 18168-18168/cn.kt.app D/MyLocationObserver: Location[gps 50.219998,128.219998 hAcc=5 et=+19075d0h37m58s639ms etAcc=+1ms alt=0.0 vel=0.0 bear=0.0 vAcc=1 sAcc=1 bAcc=30 {Bundle[mParcelledData.dataSize=96]}]
2022-03-24 08:38:09.564 18168-18168/cn.kt.app D/MyLocationObserver: Location[gps 80.109998,128.219998 hAcc=5 et=+19075d0h38m9s562ms etAcc=+1ms alt=0.0 vel=0.0 bear=0.0 vAcc=1 sAcc=1 bAcc=30 {Bundle[mParcelledData.dataSize=96]}]

4、使用 ProcessLifecycleOwner 监听应用程序生命周期

class ApplicationObserver : LifecycleObserver {
    /**
     * onCreate 只会调用一次
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() {
    }

    /**
     * onDestroy 不会调用
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
    }
}
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationObserver())
    }
}

相关文章

网友评论

      本文标题:Android Jetpack 之 Lifecycle

      本文链接:https://www.haomeiwen.com/subject/jxjhjrtx.html