role
What does the LifecycleObserver do?
- Lifecycle is used to store information about the Lifecycle state of a component, such as an Activity or Fragment, and allow other objects to observe this state. Data will not be refreshed repeatedly for operations such as mobile phone status switching.
use
- LifeCycle can be used in a relatively simple way, such as defining an object and implementing the LifecycleObserver method, as shown in the following example:
1. Create the MyChronometer class
class MyChronometer @JvmOverloads constructor(
context: Context.attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : Chronometer(context, attrs, defStyleAttr), LifecycleObserver {
var l: Long = 0
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun startMeter(a): Unit {
setBase(SystemClock.elapsedRealtime() - l)
start()
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun stopMeter(a): Unit {
l = SystemClock.elapsedRealtime() - base
stop(a)}}Copy the code
2.MainActivity
class MainActivity : AppCompatActivity(a){
lateinit var mChonometer: MyChronometer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mChonometer=findViewById(R.id.chronometer)
lifecycle.addObserver(mChonometer)
}
}
Copy the code
On the Activity page, it’s as simple as adding mChonometer lifecycle. AddObServer to the method to complete the lifecycle listening.
The basic principle of
- The AppComponentActivity and FragmentActivity pages both inherit the ComponentActivity method
And ComponentActivity implements LifecycleOwner, SavedStateRegistryOwner interface, so we can directly lifecycle method in the Activity page