jetpack 组件
As a matter of fact, one of the main problems in Android development is facing with lifecycle management issues. In other words, failing to handle application lifecycles appropriately can cause some problematic issues such as memory leaks and some crashes. Lifecycle-aware components as a part of Android Architecture Components accomplish tasks in response to a change in the lifecycle status of another component, such as activities and fragments. As a result, these components help you create better-organized, and often lighter-weight code, that is easier to maintain and test. This essay aims to consider Android Jetpack Lifecycle-aware components as an advanced approach for managing lifecycles in Android development.
实际上,Android开发中的主要问题之一就是生命周期管理问题。 换句话说,无法正确处理应用程序生命周期会导致一些问题,例如内存泄漏和崩溃。 作为Android体系结构组件的一部分的具有生命周期意识的组件可以完成任务,以响应另一个组件(例如活动和片段)的生命周期状态变化。 因此,这些组件可帮助您创建组织更好,更轻量的代码,从而更易于维护和测试。 本文旨在将Android Jetpack生命周期感知组件视为一种管理Android开发中生命周期的高级方法。
概述与介绍 (Overview and Introduction)
Android Architecture Components is a new collection of libraries by Google, which aims to help us design Android applications that are robust, testable, and maintainable. In other words, this component helps us handle data across lifecycle events and configuration changes, and also create a proper architecture for our classes for maintenance and test.
Android Architecture Components是Google的新库集合,旨在帮助我们设计健壮,可测试和可维护的Android应用程序。 换句话说,该组件可以帮助我们处理生命周期事件和配置更改中的数据,还可以为我们的类创建适当的体系结构以进行维护和测试。
Fundamentally, most Android components have a lifecycle that are associated with them. You used to be responsible for handling your app’s lifecycle, which was not always easy task particularly for multiple asynchronous calls in a simultaneous way. Failing to handle application lifecycles appropriately can cause some problematic issues such as memory leaks and some crashes. Although you managed the lifecycle correctly, implementing all of that lifecycle-dependent code in your lifecycle methods such as onStart() and onStop() methods was complicated. In short, this approach makes methods difficult to read, maintain, and test.
从根本上讲,大多数Android组件都有与其相关联的生命周期。 您曾经负责处理应用程序的生命周期,这并非总是一件容易的事,尤其是对于同时进行多个异步调用而言。 无法正确处理应用程序生命周期会导致一些问题,例如内存泄漏和崩溃。 尽管您正确地管理了生命周期,但是在生命周期方法(例如onStart()和onStop()方法)中实现所有与生命周期相关的代码都是很复杂的。 简而言之,这种方法使方法难以阅读,维护和测试。

So, the Lifecycle library provides an advanced approach to lifecycle management by supporting all the classes and interfaces needed to implement lifecycle-aware components, which adjust their behavior automatically, and even accomplish various actions in response to lifecycle events. In addition, there is no guarantee that the component starts before the activity or fragment is stopped. For instance, if we have to perform a long-running task like some configuration check in onStart(). This can lead to a race condition where the onStop() method finishes before the onStart(). This means keeping the component alive longer than it is needed. For example, assume we have an activity that represents the device location on the screen as follow:
因此,生命周期库通过支持实现生命周期感知组件所需的所有类和接口来提供生命周期管理的高级方法,这些类和接口可自动调整其行为,甚至响应生命周期事件而执行各种操作。 此外,不能保证组件在活动或片段停止之前就已启动。 例如,如果我们必须执行长时间运行的任务,例如在onStart()中进行一些配置检查。 这可能导致竞态条件,其中onStop()方法在onStart()之前完成。 这意味着使组件的使用寿命比需要的更长。 例如,假设我们有一个代表屏幕上设备位置的活动,如下所示:
class MyActivity : AppCompatActivity() { private lateinit var myLocationListener: MyLocationListener override fun onCreate(...) { myLocationListener = MyLocationListener(this) { location -> // update UI } } public override fun onStart() { super.onStart() Util.checkUserStatus { result ->//If this callback is invoked after activity is stopped, what should we do? if (result) { myLocationListener.start() } } } public override fun onStop() { super.onStop() myLocationListener.stop() }}
Lifecycle-aware components help you manage your activity and fragment lifecycles. Survive configuration changes, avoid memory leaks and easily load data into your UI.
In fact, since this process is automated, Lifecycle helps you avoid some problems caused by lifecycle mismanagement. As a result, your code would be be much more organized. and it would be easier to read, maintain, and test.
实际上,由于此过程是自动化的,因此Lifecycle可帮助您避免因生命周期管理不当而引起的某些问题。 结果,您的代码将更有条理。 并且更易于阅读,维护和测试。
生命周期意识的定义是什么? (What is the definition of lifecycle awareness?)
An object is mentioned to be lifecycle-aware if it is able to detect and respond to changes in the lifecycle state of other objects within an app. Some Android components like LiveData are already lifecycle-aware. In addition, it is possible to configure any class to be lifecycle-aware by implementing the LifecycleObserver interface within the class.
如果对象能够检测并响应应用程序中其他对象的生命周期状态变化,则该对象被称为生命周期感知。 一些Android组件(例如LiveData)已经具有生命周期意识。 另外,可以通过在类中实现LifecycleObserver接口,将任何类配置为可感知生命周期 。
生命周期 (Lifecycle)
Initially, Lifecycle is an abstract class that has an Android Lifecycle attached to it. Objects can observe this state and act appropriately.
最初,Lifecycle是一个抽象类,其中附加了Android Lifecycle。 对象可以观察到这种状态并采取适当的措施。
Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.
生命周期是一个类,其中包含有关组件生命周期状态(如活动或片段)的信息,并允许其他对象观察此状态。
To keep a track of this state, there are two main concepts that are represented as Enums: Events and State.
为了跟踪此状态,有两个主要概念表示为枚举:事件和状态。

As a matter of fact, in above diagram, states are nodes of a graph, and events are the edges between these nodes. Basically, a class can monitor the component’s lifecycle status by using annotations in its methods. For instance:
实际上,在上图中,状态是图形的节点,事件是这些节点之间的边缘。 基本上,一个类可以通过在其方法中使用注释来监视组件的生命周期状态。 例如:
class MyObserver : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun connectListener() { //... } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun disconnectListener() { //... }}
In fact, the @OnLifecycleEvent annotation can react to the following lifecycle events:
实际上, @ OnLifecycleEvent批注可以对以下生命周期事件作出React:
- ON_CREATE ON_CREATE
- ON_DESTROY ON_DESTROY
- ON_PAUSE ON_PAUSE
- ON_RESUME ON_RESUME
- ON_START ON_START
- ON_STOP ON_STOP
- ON_ANY 任何
Note: The method assigned to the ON_ANY event will be called for all lifecycle events.
注意:将为所有生命周期事件调用分配给ON_ANY事件的方法。
After that, you can be able to add an observer by calling the addObserver() method of the Lifecycle class and passing an instance of your observer as follow:
之后,您可以通过调用Lifecycle类的addObserver()方法并按如下方式传递观察者的实例来添加观察者:
myLifecycleOwner.getLifecycle().addObserver(MyObserver())
You should add this line of code in your onCreate() method of your activity in order to associate the LifecycleOwner with the LifecycleObserver by using getLifecycle().addObserver().
您应该在活动的onCreate()方法中添加以下代码行,以便通过使用getLifecycle()。addObserver()将LifecycleOwner与LifecycleObserver关联。
生命周期所有者 (LifecycleOwner)
An interface that is implemented by objects with a Lifecycle. Fragments and Activities already implement the LifecycleOwner interface in Support Library 26.1.0+, and are LifecycleOwners by default. Custom classes may also be configured as lifecycle owners by using the LifecycleRegistry class and implementing the LifecycleObserver interface.
由具有生命周期的对象实现的接口。 片段和活动已经在支持库26.1.0+中实现了LifecycleOwner接口,并且默认情况下是LifecycleOwners。 通过使用LifecycleRegistry类并实现LifecycleObserver接口,还可以将自定义类配置为生命周期所有者。
Besides, when the status of a lifecycle owner changes, the assigned Lifecycle object will be updated with the new state. At any time, a lifecycle owner will be in one of the following five states:
此外,当生命周期所有者的状态更改时,将使用新状态更新分配的Lifecycle对象。 在任何时候,生命周期所有者将处于以下五个状态之一:
- Lifecycle.State.INITIALIZED 生命周期状态初始化
- Lifecycle.State.CREATED 生命周期状态创建
- Lifecycle.State.STARTED 生命周期状态
- Lifecycle.State.RESUMED 生命周期状态恢复
- Lifecycle.State.DESTROYED 生命周期状态被破坏
Thus, the isAtLeast() method of the current state object may also be used when the owner state needs to be at a certain lifecycle stage:
因此,当所有者状态需要处于某个生命周期阶段时,也可以使用当前状态对象的isAtLeast()方法:
if(getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) { //...}
Eventually, if you are trying to handle the lifecycle of a whole application process, you should use ProcessLifcyceOwner.
最终,如果您尝试处理整个应用程序流程的生命周期,则应使用ProcessLifcyceOwner 。
生命周期感知组件的一些用例 (Some use cases for lifecycle-aware components)
As a matter of fact, Lifecycle-aware components can make it much easier for you to manage lifecycles in a variety of cases. For instance:
实际上,具有生命周期意识的组件可以使您在各种情况下更轻松地管理生命周期。 例如:
- Stopping and starting video buffering 停止和开始视频缓冲
- Starting and stopping network connectivity. 启动和停止网络连接。
- Pausing and resuming animated drawables. 暂停和恢复动画可绘制对象。
实时数据 (LiveData)
Additionally, the Lifecycle library supports the foundation for additional Android Architecture Components, including LiveData. LiveData is an observable wrapper that can hold any data, including Lists. Once a LiveData has a value, it will notify its assigned Observers whenever that value changes.
此外,生命周期库为其他Android体系结构组件(包括LiveData)提供了基础。 LiveData是一个可观察的包装器,可以保存任何数据,包括列表。 LiveData具有值后,只要该值发生更改,它将通知其分配的观察者。
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
LiveData是可观察的数据持有者类。 与常规的可观察数据不同,LiveData具有生命周期感知功能,这意味着它尊重其他应用程序组件(例如活动,片段或服务)的生命周期。 这种意识确保LiveData仅更新处于活动生命周期状态的应用程序组件观察者。
However, in contrast to a regular Observable, LiveData is lifecycle-aware. Therefore, it only updates Observers that are in an “active” state such as STARTED or RESUMED. If the LifecycleOwner reaches a Lifecycle.State.DESTROYED state, then the LiveData will eliminate the Observer automatically. This lifecycle-awareness helps you avoid the crashes that can occur if you try to update a stopped Activity or Fragment. Whenever a component enters the STARTED state, it automatically receives the most recent value from the LiveData object it is observing. If an Activity or Fragment is resumed, or recreated as part of a configuration change process, it will receive the latest data.
但是,与常规的Observable相比,LiveData具有生命周期意识。 因此,它仅更新处于“活动”状态(例如STARTED或RESUMED)的观察者。 如果LifecycleOwner达到Lifecycle.State.DESTROYED状态,则LiveData将自动消除Observer。 这种生命周期意识可帮助您避免在尝试更新已停止的“活动”或“片段”时可能发生的崩溃。 每当一个组件进入启动状态时,它自动接收从LiveData对象被观察的最新值。 如果恢复活动或片段,或者在配置更改过程中重新创建了活动或片段,它将接收最新数据。
Google的生命周期感知组件的一些最佳做法 (Some best practices for lifecycle-aware components by Google)
- Keep your UI controllers (activities and fragments) as lean as possible by using LiveData and ViewModel 通过使用LiveData和ViewModel使UI控制器(活动和片段)保持精简
2. Put your data logic in your ViewModel class. In fact, ViewModel should use as a connector between your UI controller and the rest of your app.
2.将数据逻辑放入ViewModel类。 实际上,ViewModel应该用作UI控制器与应用程序其余部分之间的连接器。
3. Use Data Binding to maintain a clean connection between your views and the UI controller.
3.使用数据绑定来保持视图与UI控制器之间的干净连接。
4. Avoid referencing a View or Activity context in your ViewModel.
4.避免在ViewModel中引用View或Activity上下文。
结论 (In conclusion)
This essay considered Android Jetpack Lifecycle-aware components as some advanced classes for handling lifecycles in Android apps. In fact, these libraries could be helpful in some cases such as stopping and starting video buffering, starting and stopping network connectivity, and pausing and resuming animated drawables. In addition, you can be able to use LiveData as an lifecycle-aware approach in your Android apps.
本文将Android Jetpack生命周期感知组件视为处理Android应用程序中生命周期的一些高级类。 实际上,这些库在某些情况下可能很有用,例如停止和启动视频缓冲,启动和停止网络连接以及暂停和恢复动画可绘制对象。 此外,您可以将LiveData用作可感知生命周期的Android应用程序。
翻译自: https://medium.com/kayvan-kaseb/using-android-jetpack-lifecycle-aware-components-8fe79481e441
jetpack 组件