This is the 16th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

The role of LifeCycle is to be aware of the LifeCycle of the component (Activity/Fragment) and perform the assigned task at the appropriate LifeCycle.

1. Listen to components late in life

Suppose we have a Util class that has two methods that need to be executed on the Activity’s onStart and onDestory, we can start by having it implement LifecycleObserver:

class LifecycleUtil : LifecycleObserver {

    @OnLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_START)
    fun startFun(a){}@OnLifecycleEvent(androidx.lifecycle.Lifecycle.Event.ON_STOP)
    fun stopFun(a){}}Copy the code

Then for any lifecycle component that implements the LifecycleOwner interface, if you need to use this Util, just add the following line of code.

lifecycle.addObserver(LocationUtil( ))

class MyActivity : AppCompatActivity(), LifecycleOwner {

    override fun onCreate(savedInstanceState: Bundle?). {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my)

        lifecycle.addObserver(LifecycleUtil())
    }
}
Copy the code

LifeCycle allows third-party components such as LifecycleUtil to have their lifecycles internally so that logic processing that would otherwise be written inside an Activity/Fragment can be done independently within the component, further decoupling.

If two of the LifecycleUtil methods need to be executed in other lifecycles at this point, just change the annotations. No external changes are required.

2. Monitor the switch between the application front and background

Some apps have a toast that pops up when the application is switched to the background to indicate that you are running in the background. Lifecycle implementation is easy to do and also uses the ON_Start and ON_STOP of Lifecycle.

Then the Application starts, using the following code in a ContentProvider or Application: ProcessLifecycleOwner. The get () lifecycle. AddObserver (LifecycleUtil ())

class MyApplication : Application() {

    override fun onCreate(a) {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(LifecycleUtil())
    }
}
Copy the code

ProcessLifecycleOwner is aware of the entire process life cycle and can easily monitor the application’s front and back switches.

Using ProcessLifecycleOwner may require adding dependencies to build.grade:

Implementation "android. Arch. Lifecycle: extensions: 1.1.1"

Or implementation ‘androidx. Lifecycle: lifecycle – extensions: 2.2.0 – rc03’

3. Manage the Activity globally

We often have this feature, and interviewers ask questions like, what do I do to shut down all the activities?

Using the Application. The ActivityLifecycleCallbacks have a whole new way to implement.

class MyActivityLifeCycleCallBack : Application.ActivityLifecycleCallbacks {

   companion object {
       val instance = MyActivityLifeCycleCallBack()
   }

   private val activityList: ArrayList<Activity> = ArrayList()

   override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?). {
       activityList.add(activity)
       println("onActivityCreated : ${activity.localClassName}")}override fun onActivityStarted(activity: Activity) {
       println("onActivityStarted : ${activity.localClassName}")}override fun onActivityResumed(activity: Activity) {
       println("onActivityResumed : ${activity.localClassName}")}override fun onActivityPaused(activity: Activity) {
       println("onActivityPaused : ${activity.localClassName}")}override fun onActivityDestroyed(activity: Activity) {
       println("onActivityDestroyed : ${activity.localClassName}")
       activityList.remove(activity)
   }

   override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?).{}override fun onActivityStopped(activity: Activity) {
       println("onActivityStopped : ${activity.localClassName}")}fun clearAllActivity(a) {
       for (activity: Activity in activityList) {
           activity.finish()
       }
   }
}
Copy the code

Through the Application. The ActivityLifecycleCallbacks can listen to all the Activity of the life cycle, as long as in the Application to register the Callback.

registerActivityLifecycleCallbacks(MyActivityLifeCycleCallBack.instance)

At this point, the lifecycle of each Activity is monitored. If we want to close all activities, we can do this:

In MyActivityLifecycleCallback we implemented a clearAllActivity method, simple, and will be MyActivityLifecycleCallback used as a singleton.

companion object { 
val instance = MyActivityLifeCycleCallBack() 
} 

 
fun clearAllActivity(a) { 
for (activity: Activity in activityList) { 
activity.finish() 
} 
} 

Copy the code

Instead, call this method directly when it is used:

conclusion

Lifecycle is a great tool that allows us to write more standard and accurate code.

Reference: Hardcore Jetpack for LifeCycle Use