Android Jetpack framework -Lifecycles

1 Introduction

Lifecycles one Jetpack frame assembly, using the observer pattern or Fragment Activity Tracking life cycle, in order to avoid adding or Fragment Activity lifecycle process much logic coupling for reducing code, and the code is repeated removal of memory leaks.

The official description:

Lifecycle aware component may perform the operation in response to a change in the lifecycle state of another component (e.g., Activity and Fragment) a. These components help you write better organized and often more streamlined code, so the code easier to maintain. A common mode of operation is implemented in the dependent components and Fragment Activity lifecycle process. However, this model can lead to code bars rational and poor will spread error. By using a life-cycle-aware components, you can rely on the code component into the component itself from a life-cycle approach.

androidx.lifecycle package provides classes and interfaces can be used to build lifecycle aware components - these components can automatically adjust its behavior based on the current status of the life cycle of Activity or Fragment.

2. Why use Lifecycles

In the usual Android development, we need to register the various components or use a variety Manager. In traditional MVC framework, all the logic in the Activity or Fragment, register () in OnCreate, in OnDestory () or OnStop () go unregistered. And some components need to survive outside the Activity life cycle, this time they hold a reference to Context, which will lead to a memory leak. Activity or more are required to register some components, resulting in a large number of template code. Of course, these problems can be optimized code, on the Application, or define a BaseActivity resolved, but there is no way to solve the Activity / Fragment overweight problem. In the MVC or MVVM architecture, write code that is clear coupling more serious. And sometimes we encounter some timing issues, such as the registration process is relatively time-consuming, but this time Activity life cycle have gone OnStop (), it will cause the component to perform cancel the registration when registration has not been completed. This time we need to use this lifecycle Lifecycle of the observer.

3. How to use

3.1 Importing project

Add the app in the build.gradle

    implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"

3.2 does not use LifeCycle

As used herein, the official Demo code and does not use the traditional way of LifeCycle make a comparison. The following code all use Kotlin, behind not remind

Suppose we have a Activity device location is displayed on the screen. Common implementation might look like this:

 internal class MyLocationListener(
            private val context: Context,
            private val callback: (Location) -> Unit
    ) {

        fun start() {
            // connect to system location service
        }

        fun stop() {
            // disconnect from system location service
        }
    }

    class MyActivity : AppCompatActivity() {
        private lateinit var myLocationListener: MyLocationListener

        override fun onCreate(...) {
            myLocationListener = MyLocationListener(this) { location ->
                // update UI
            }
        }

        public override fun onStart() {
            super.onStart()
            myLocationListener.start()
            // manage other components that need to respond
            // to the activity lifecycle
        }

        public override fun onStop() {
            super.onStop()
            myLocationListener.stop()
            // manage other components that need to respond
            // to the activity lifecycle
        }
    }
    

3.3 LifeCycle

Create a lifecycle observer

 class MyObserver : LifecycleObserver {
		//LifecycleObserver 是一个空的接口,需要用注解来具体控制
		//表示当被观察的对象生命周期到达OnResume()的时候
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun connectListener() {
            ...
        }
		//表示当被观察的对象生命周期到达OnPause()的时候
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun disconnectListener() {
            ...
        }
    }

In the above code we create the life cycle of an observer, which is the most simple wording, usually we need to use the viewer Context and LifecycleOwner members of the observer. The method can be configured in these two objects in MyObserver

internal class MyObserver constructor(context:Context,lifeOwner:LifeOwner) :LifecycleObserver {
    private var mContext:Context = context
	private var mLifeOwner = lifeOwner
	...
}

Why LifecycleOwner objects?
Official documentation for the introduction LifecycleOwner as follows:

LifecycleOwner single method interfaces, classes that have Lifecycle. It has a method (i.e. getLifecycle ()), which must be implemented by classes. If you try to manage the entire life cycle of the application process, please refer to ProcessLifecycleOwner.

This interface from various classes (e.g. Fragment and AppCompatActivity) abstraction Lifecycle ownership, and allow the preparation of these classes with the use of the assembly. Any class can implement custom applications LifecycleOwner interface.

Component implementation LifecycleObserver can work together seamlessly and implementation LifecycleOwner components, because the owner can provide life-cycle, and the viewer can register to observe the life cycle.

For location tracking example, we can make MyLocationListener class implements LifecycleObserver, and then use the Lifecycle Activity in the onCreate () method to initialize it. In this way, MyLocationListener class will be "self-sufficient", which means that changes in the life cycle states would make a logical response in MyLocationListener (not in Activity) in declared. Let each component stores its own logic, enables Activity and Fragment logic easier to manage.

A common use case is, if Lifecycle now is not in good condition, you should avoid calling some callback. For example, if the callback to run after the transaction is stored in Fragment Activity state, it will lead to collapse, so we must not invoke the callback.

To simplify this use case, Lifecycle classes allow other objects to query the current state.

 internal class MyLocationListener(
            private val context: Context,
            private val lifecycle: Lifecycle,
            private val callback: (Location) -> Unit
    ) {

        private var enabled = false

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun start() {
            if (enabled) {
                // connect
            }
        }

        fun enable() {
            enabled = true
            if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
                // connect if not connected
            }
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun stop() {
            // disconnect if connected
        }
    }
    

For this implementation, LocationListener class can fully perceive life cycle. If we need to use LocationListener from another Activity or Fragment, just to be initialized. All settings and dismantling operations managed by the class itself.

If you need to use the Android library provides life-cycle class, we recommend that you use life-cycle-aware components. Library clients can easily integrate these components without the need to manually manage the life cycle of the client.

Support Library 26.1.0 and later versions Fragment and Activity realized LifecycleOwner interface.

Therefore lifecycle may be acquired in the code as follows

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityMainBinding = DataBindingUtil.setContentView(
            this, R.layout.activity_main
        )
        mContext = this
        myObserver = MyObserver(this)

        mViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
        binding.lifecycleOwner = this
        binding.viewModel = mViewModel
        //给lifecycle对象添加之前创建的观察者
        lifecycle.addObserver(myObserver)
        //也可以这么写
        //binding.lifecycleOwner.getLifecycle().addObserver(MyObserver())

    }

4. Custom LifecycleOwner

As mentioned above Support Library 26.1.0 and later versions Fragment and Activity have been achieved. So low version of how to use? Or say you want to use LifecycleOwner in components that are outside of Activity and Fragment in how to do? This time you need to customize LifecycleOwner.

If you have a custom class and want to make it LifecycleOwner, you can use LifecycleRegistry class, but it needs to forward events to the class, as shown in the following code sample:

    class MyActivity : Activity(), LifecycleOwner {

        private lateinit var lifecycleRegistry: LifecycleRegistry

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

            lifecycleRegistry = LifecycleRegistry(this)
            lifecycleRegistry.markState(Lifecycle.State.CREATED)
        }

        public override fun onStart() {
            super.onStart()
            lifecycleRegistry.markState(Lifecycle.State.STARTED)
        }

        override fun getLifecycle(): Lifecycle {
            return lifecycleRegistry
        }
    }
    

5. Examples

Lifecycle-aware components make it easier for you to manage the life cycle in a variety of situations. Here are a few examples:

  1. Switching between coarse and fine-grained location update. Life cycle aware enable fine-grained components may be visible when the location update in a location application, and switch to update the coarse-grained in the application in the background. With life-cycle-aware components LiveData, the application automatically updates the interface can be used to change the position of the user.
  2. Stop and start the video buffer. Life cycle-aware component video buffer may begin as soon as possible, but will be delayed play until the application is fully started. In addition, after the destruction of the application, you can also use life-cycle-aware components stop buffer.
  3. Start and stop network connections. With life-cycle-aware components to enable real-time updates of the data network (streaming) at the time of application is in the foreground and automatically pause when the application goes into the background.
  4. Pause and resume animations can draw resources. With life-cycle-aware components may pause when the application is in the background animations can draw resources and resource recovery can draw upon the application in the foreground.

6.OnStop () in some pit

Official documents mentioned onStop () in some of the pits, the main talking onSaveInstanceState () and onStop timing issues between the (). In performing onSaveInstanceState (), in which case onStop () may not have to perform at this time would think that view has not changed, this time to change the view would lead to an inconsistent state when reconstruction of view.
Here Insert Picture Description

Published 21 original articles · won praise 16 · views 3565

Guess you like

Origin blog.csdn.net/weixin_44666188/article/details/104031067