Android Jetpack架构组件

As a matter of fact, Android Jetpack was inspired by the Support Library, which is a set of components to take advantage of advanced Android features; whereas, it maintains backwards compatibility. Google mentioned that it is currently used by 99% of every app in the Play Store. Furthermore, Google introduced the Architecture Components for dealing with data changes and app lifecycle. This essay aims to introduce main concepts and features that are used in Android Jetpack Architecture Components.

实际上,Android Jetpack的灵感来自于支持库,该库是利用高级Android功能的一组组件。 相反,它保持了向后兼容性。 Google提到,目前Play商店中每个应用程序中有99%使用它。 此外,Google引入了用于处理数据更改和应用程序生命周期的体系结构组件。 本文旨在介绍Android Jetpack体系结构组件中使用的主要概念和功能。

简介与概述 (Introduction and Overview)

Basically, Android Jetpack is set of libraries, tools, and guidance for modern Android development. Currently, there are four categories for using Jetpack, which includes: Architecture, UI, Behavior, and Foundation. In addition, Architecture Components could be classified as follows: Room, WorkManager, Lifecycle, Navigation, Paging, Data Binding, ViewModel, and LiveData.

基本上,Android Jetpack是一套用于现代Android开发的库,工具和指南。 当前,有四种使用Jetpack的类别,包括:体系结构,UI,行为和基础。 此外, 体系结构组件可以分类如下:Room,WorkManager,生命周期,导航,分页,数据绑定,ViewModel和LiveData。

Image for post
Google Documents Google Documents提供

As a matter of fact, your Android app can run on different versions of the platform because Android Jetpack components are built to support backwards compatibility. Besides, Android Jetpack is built for modern design practices such as separation of concerns, test-ability, loose coupling, Observer Pattern, Inversion of Control as well as productivity features like Kotlin integration. This would be helpful for building robust, high quality apps with less code much more easily. While the components of Android Jetpack are built to work together like lifecycle awareness and LiveData, there is no need to use all of them. This means you can integrate the parts of Android Jetpack that solve your problems; whereas, you can be able to keep the parts of your app that are already working appropriately.

实际上,您的Android应用可以在平台的不同版本上运行,因为Android Jetpack组件旨在支持向后兼容性。 此外,Android Jetpack专为现代设计实践而构建,例如关注点分离,可测试性,松散耦合,观察者模式,控制反转以及Kotlin集成等生产力功能。 这对于以更少的代码轻松构建健壮,高质量的应用程序将很有帮助。 尽管Android Jetpack的各个组件可以像生命周期感知和LiveData这样协同工作,但并不需要全部使用它们。 这意味着您可以集成解决问题的Android Jetpack部分; 相反,您可以保留应用程序中已经正常运行的部分。

Jetpack encompasses a collection of Android libraries that incorporate best practices and provide backwards compatibility in your Android apps.

Jetpack包含一系列Android库,这些库结合了最佳实践并在您的Android应用程序中提供向后兼容性。

在您的应用程序中使用Jetpack库 (Using a Jetpack library in your app)

Initially, all Jetpack components are available on the Google Maven repository. You should open the build.gradle file for your project and add the google() repository as follows:

最初,所有Jetpack组件都可在Google Maven存储库中使用 。 您应该打开项目的build.gradle文件,并添加google()存储库,如下所示:

allprojects {
repositories {
google()
jcenter()
}
}

So, you can add architecture components such as LiveData and ViewModel as shown below:

因此,您可以添加架构组件,例如LiveData和ViewModel,如下所示:

dependencies {
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
...
}

In fact, Kotlin-based and Java-based API reference pages are available for all Jetpack libraries.

实际上,所有Jetpack库都可以使用基于 Kotlin和基于 Java的 API参考页。

房间 (Room)

At Google I/O 2017, Room as an persistence library that supports an abstraction layer over SQLite to allow fluent database access while controlling the full power of SQLite was introduced. In short, Room is a robust SQL object mapping library. Because Room takes can address some previous problems effectively, Google highly recommends using Room instead of SQLite. Main components in Room can be classified into three categories:

在Google I / O 2017中,引入了Room作为持久性库,它支持SQLite上的抽象层,以允许流畅的数据库访问,同时控制SQLite的全部功能。 简而言之, Room是一个强大SQL对象映射库。 由于Room Take可以有效解决以前的一些问题,因此Google强烈建议您使用Room而不是SQLite。 会议室中的主要组件可以分为三类:

Entity: Annotated class that represents a database table when working with Room.

实体 :带注释的类,表示使用Room时的数据库表。

DAO (Data Access Object): A mapping of SQL queries to functions. It contains the methods used for accessing the database.

DAO(数据访问对象) :SQL查询到函数的映射。 它包含用于访问数据库的方法。

Room database: Simplifies database work and serves as an access point to the underlying SQLite database.

Room数据库 :简化数据库工作,并充当基础SQLite数据库的访问点。

Image for post
Google document Google文档提供

For example, after adding some Room dependencies, if you want to have a table of users, and you want every row of that table to be an instance of the user class. First of all, you must annotate your class with that Entity. Secondly, you should set the mandatory primary key. After this main step, we need a way to access the data in the database. We can be able to perform that with Data Access Object (DAO). More precisely, you must create an interface, and annotate it with Dao. Finally, the class that puts together the entities and the DAOs is the Room database. Thus, you have to create an extra class that extends the Room database, and annotate it with Database.

例如,在添加一些Room依赖项之后 ,如果您要拥有一个用户表,并且希望该表的每一行都是用户类的实例。 首先,您必须使用Entity注释您的类。 其次,您应该设置强制性主键。 完成这一主要步骤之后,我们需要一种访问数据库中数据的方法。 我们可以使用数据访问对象(DAO)来执行该操作。 更准确地说,您必须创建一个接口,并使用Dao对其进行注释 最后,将实体和DAO放在一起的类是Room数据库 。 因此,您必须创建一个额外的类来扩展Room数据库,并使用Database对其进行注释。

Some benefits cane be mentioned in using Room in your Android projects as follows briefly:

简要介绍在Android项目中使用Room的一些好处,如下所述:

  • It performs SQL query validation at compile time.

    它在编译时执行SQL查询验证。
  • Simplification of access to database.

    简化对数据库的访问。
  • It reduces boilerplate codes within the application.

    它减少了应用程序中的样板代码。
  • It takes care of schema generation and data manipulation in the code.

    它负责代码中的模式生成和数据操作。
  • It integrates well with other android architecture components such as LiveData and ViewModel.

    它与其他Android体系结构组件(如LiveData和ViewModel)很好地集成在一起。
  • Ease of implementing migrations

    易于实施迁移
  • High degree of test-ability.

    高度的测试能力。

工作经理 (WorkManager)

Basically, WorkManager provides a unified solution for background works, and also covers Android’s power-saving features as well as the user’s API levels. It is backwards compatible to API level 14. Furthermore, it can be run with or without Google Play services. These unique features make it the recommended solution for most background work on Android. For instance, you might point your app to download new resources from the network occasionally. Therefore, the downloading is a task and you can set up this task to run at an appropriate time based on the availability of the WiFi network or when the device is charging. Now, you can be able to schedule a task by using WorkManager. There are two key attributes that make a task suitable for WorkManager. First, that the task is deferrable, and second, that the task requires to be guaranteed to run.

基本上,WorkManager为后台工作提供了统一的解决方案,还涵盖了Android的节能功能以及用户的API级别。 它向后兼容API级别14。此外,它可以在有或没有Google Play服务的情况下运行。 这些独特的功能使其成为Android上大多数后台工作的推荐解决方案。 例如,您可能会指向您的应用,偶尔从网络下载新资源。 因此,下载是一项任务,您可以将该任务设置为根据WiFi网络的可用性或在设备充电时在适当的时间运行。 现在,您可以使用WorkManager安排任务。 有两个关键属性使任务适合WorkManager。 首先,任务是可延迟的 ,其次,需要保证任务能够运行。

  1. Deferrable: The task can run later and is still useful.

    可延缓该任务可以稍后运行,仍然有用。

2. Guaranteed: The task runs even if the device restarts.

2. 保证即使设备重新启动,任务也会运行。

WorkManager is an API that makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or the device restarts.

WorkManager是一个API,即使应用程序退出或设备重新启动,也可以轻松地计划可运行的异步任务。

WorkManager performs the work requests in the order that you specified while it supports compatibility issues and best practices for battery and system health. Also, WorkManager can return the state of the work request. So, that you can represent this state in your UI.

WorkManager在支持兼容性问题以及电池和系统运行状况的最佳做法时,将按照您指定的顺序执行工作请求。 另外,WorkManager可以返回工作请求的状态。 因此,您可以在用户界面中表示此状态。

Image for post
Google Documents Google Documents提供

Some other advantages could be indicated in using WorkManager in your Android projects as follows:

在Android项目中使用WorkManager可能会显示出一些其他优点,如下所示:

  1. You can schedule a task depending on the condition when they should run. So WorkManager give the guarantee that the task will be executed even when the device is rebooted.

    您可以根据任务的运行时间安排任务。 因此,WorkManager保证即使重新启动设备也会执行任务。

2. It provides backward compatibility, which means you do not have to specify the device capabilities or choose an appropriate API.

2.它提供了向后兼容性,这意味着您不必指定设备功能或选择适当的API。

3. You can detect and track the status of your tasks.

3.您可以检测并跟踪任务的状态。

4. It provides task chaining. It means you can create a draft of your work, and enqueue one after the other using the WorkManager.

4.它提供任务链。 这意味着您可以创建工作草稿,然后使用WorkManager依次入队。

生命周期感知组件 (Lifecycle-Aware Components)

Fundamentally, 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. In fact, one of the major 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. Also, one of the main classes in this component is Lifecycle. In short, Lifecycle is an abstract class that has an Android Lifecycle attached to it. Objects can observe this state and act appropriately. To keep a track of this state, there are two main concepts that are represented as Enums: Events and State.

从根本上说,如果一个对象能够检测并响应应用程序中其他对象的生命周期状态变化,则该对象是生命周期感知的。 一些Android组件(例如LiveData)已经具有生命周期意识。 另外,可以通过在类中实现LifecycleObserver接口,将任何类配置为可感知生命周期 。 实际上,Android开发中的主要问题之一就是生命周期管理问题。 换句话说,无法正确处理应用程序生命周期会导致一些问题,例如内存泄漏和崩溃。 作为Android体系结构组件的一部分的具有生命周期意识的组件可以完成任务,以响应另一个组件(例如活动和片段)的生命周期状态变化。 因此,这些组件可帮助您创建组织更好,更轻量的代码,从而更易于维护和测试。 同样,此组件中的主要类之一是Lifecycle。 简而言之,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.

生命周期是一个类,其中包含有关组件生命周期状态(如活动或片段)的信息,并允许其他对象观察此状态。

Image for post
Google Document Google Document提供

视图模型 (ViewModel)

Basically, ViewModels are objects that support data for UI components, and survive configuration changes. In fact, rotating your mobile phone is considered a configuration change. Configuration changes cause your whole activity to get recreated. If you do not properly save and restore data from the destroyed activity, you will lose that data. In addition, you will face some UI bugs or crashes. Thus, instead of storing all of your UI data in your activity, you should put it in the ViewModel. In this case, this helps with configuration changes; however, it is also a best practice for software design.

基本上,ViewModels是支持UI组件数据并可以保留配置更改的对象。 实际上,旋转手机被视为配置更改。 配置更改会导致重新创建整个活动。 如果您没有正确地保存和恢复销毁活动中的数据,则将丢失该数据。 此外,您还会遇到一些UI错误或崩溃。 因此,您应该将其放在ViewModel中,而不是将所有UI数据存储在活动中。 在这种情况下,这有助于更改配置。 但是,这也是软件设计的最佳实践。

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

ViewModel类旨在以生命周期感知的方式存储和管理与UI相关的数据。 ViewModel类允许数据幸免于配置更改(例如屏幕旋转)。

Another important issue is that UI controllers (activities and fragments) frequently need to make asynchronous calls that may take some time to return the result. So, the UI controller needs to manage these calls, and make sure the system cleans them up after destroying to avoid some potential memory leaks. It is clear that this issue needs a lot of maintenance because an object is re-created for a configuration change, and this leads to waste of resources due to this repeated processes

另一个重要的问题是UI控制器(活动和片段)经常需要进行异步调用,这可能需要一些时间才能返回结果。 因此,UI控制器需要管理这些调用,并确保系统销毁后将其清除,以避免潜在的内存泄漏。 显然,此问题需要大量维护,因为重新创建对象以进行配置更改,并且由于此重复过程而导致资源浪费

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

ViewModel是一个类,负责为Activity或Fragment准备和管理数据。 它还处理活动/片段与应用程序其余部分的通信(例如,调用业务逻辑类)。

Image for post
Google documents Google文档提供

实时数据 (LiveData)

LiveData is an observable data holder class, which is also lifecycle aware. For instance, if you have your UI as well as LiveData object that holds some data, which you want to show on screen. In this case, the UI observes the LiveData object. This means the UI wants to be notified for new updates. As a result, when the LiveData changes, the UI will get notified, and then the UI can be able to redraw itself with the new data. In other words, LiveData makes it easy to keep what is going on screen in sync with the data. However, LiveData checks the state of the observer for the first step before any updates. What makes LiveData different from other observable approaches is that it is also lifecycle aware. This means that it understands whether your UI is on screen, off-screen or destroyed. LiveData knows about your UI state because you passed it when you call Observe.

LiveData是可观察的数据持有者类,它也是生命周期感知的。 例如,如果您有UI以及包含要在屏幕上显示的某些数据的LiveData对象。 在这种情况下,UI会观察LiveData对象。 这意味着UI希望收到有关新更新的通知。 结果,当LiveData更改时,UI将得到通知,然后UI可以使用新数据重绘自身。 换句话说,LiveData可以轻松地使正在显示的内容与数据保持同步。 但是,LiveData在进行任何更新之前会先检查观察者的状态。 LiveData与其他可观察方法的不同之处在于,它还具有生命周期感知能力。 这意味着它可以了解您的UI是在屏幕上,屏幕外还是已损坏。 LiveData知道您的UI状态,因为您在调用Observe时传递了它。

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仅更新处于活动生命周期状态的应用程序组件观察者。

Some benefits of LiveData:

LiveData的一些优点:

  1. An appropriate update in UI: With the help of LiveData, your application’s UI will only be changed if there is a change in the data.

    UI中的适当更新:在LiveData的帮助下,仅当数据发生更改时,才会更改应用程序的UI。
  2. No crash because of stopped activities: Only that observer will be notified that is in a live state. Thus, an app crash will not be occurred because of stopped or paused activities.

    由于停止的活动而不会崩溃:仅通知该观察者处于活动状态。 因此,不会因活动停止或暂停而导致应用程序崩溃。
  3. Proper configuration changes: If an activity or fragment is recreated because of a configuration change like device rotation, it immediately receives the latest state.

    正确的配置更改: 如果由于配置更改(例如设备旋转)而重新创建活动或片段,则该活动或片段会立即收到最新状态。

  4. Up-to-date data: The observer will have the latest data even if the observer is in background or pause state. Whenever the observer is resumed then the latest updated data will be provided to the observer.

    最新数据:即使观察者处于后台或暂停状态,其也将拥有最新数据。 每当观察者恢复时,最新的更新数据将被提供给观察者。
  5. No memory leaks: Because all the observers are bound to Lifecycle objects and are cleaned up when their associated lifecycle is destroyed, there are no memory leaks.

    没有内存泄漏:因为所有观察者都绑定到Lifecycle对象,并且在销毁其相关联的生命周期时被清除,所以没有内存泄漏。

导航 (Navigation)

While activities are entry points into your Android app’s UI, their inflexibility when it comes to sharing data between each other and transitions has made them a less than ideal architecture for building your in-app navigation. The Navigation component is a framework for structuring your in-app UI by focusing on making a single-Activity app architecture. It supports Fragments wholly, and you can obtain all of the Architecture Components benefits such as Lifecycle and ViewModel; whereas, Navigation can manage the complexity of Fragment Transactions for you. Additionally, the Navigation component allows you to show transitions and Back behavior. It also provides full support for deep links and helpers for connecting Navigation into the appropriate UI widgets such as the navigation drawer and bottom navigation.

虽然活动是Android应用程序UI的切入点,但它们之间彼此共享数据和进行过渡时缺乏灵活性,这使它们成为构建应用程序内导航的理想架构。 导航组件是一个框架,可通过着重于构建单一活动应用架构来构建应用内UI。 它完全支持Fragments,并且您可以获得诸如生命周期和ViewModel之类的所有Architecture Components好处; 而Navigation可以为您管理Fragment Transactions的复杂性。 此外,导航组件使您可以显示过渡和后退行为。 它还为深层链接和帮助程序提供了全面支持,用于将导航连接到适当的UI小部件,如导航抽屉和底部导航。

Navigation refers to the interactions that allow users to navigate across, into, and back out from the different pieces of content within your app. Android Jetpack’s Navigation component helps you implement navigation, from simple button clicks to more complex patterns, such as app bars and the navigation drawer.

导航是指允许用户在应用程序中的不同内容之间进行浏览,浏览和退出的交互。 Android Jetpack的导航组件可帮助您实现导航,从简单的按钮单击到更复杂的模式,例如应用程序栏和导航抽屉。

Image for post
Google Documents Google Documents提供

Therefore, some benefits for using Navigation in your Android app can be indicated as follow:

因此,在Android应用中使用导航的一些好处可以表示如下:

  1. Handling Fragment Transactions

    处理片段交易

2. Implementing proper Back

2.实施适当的退货

3. Supporting Deep Linking

3.支持深度链接

4. Providing easy animated transitions

4.提供简单的动画过渡

5. Supporting common navigation pattern

5.支持通用导航模式

分页 (Paging)

Initially, most Android apps work with large sets of data; however, they just only require to load and display a small amounts of data at any given time. If you do not handle the process of loading data, you might request data that you do not actually need. This leads to waste your user’s battery and bandwidth. If the data you are displaying is constantly updating, it would be a difficult task to maintain your UI in sync and still send only a small amount of information over the network. The Paging Library as a part of Jetpack, addresses these issues appropriately. It enables you to load data gradually and gracefully. This library provides both large but bounded lists, as well as lists of unbounded sites like continuously-updating feeds. It offers integration with RecyclerView, which is typically used to display large data sets, and plays properly with either LiveData or RxJava for observing new data in your UI.

最初,大多数Android应用程序都可以处理大量数据。 但是,它们仅需要在任何给定时间加载并显示少量数据。 如果您不处理加载数据的过程,则可能会请求实际上不需要的数据。 这会浪费用户的电池和带宽。 如果要显示的数据不断更新,则要保持UI同步并通过网络仅发送少量信息将是一项艰巨的任务。 作为Jetpack一部分的分页库可以适当地解决这些问题。 它使您能够逐步且优雅地加载数据。 该库既提供大型但有边界的列表,也提供无边界站点的列表,例如不断更新的提要。 它提供了与RecyclerView的集成,后者通常用于显示大数据集,并且可以与LiveData或RxJava正常播放,以在UI中观察新数据。

The Paging Library helps you load and display small chunks of data at a time. Loading partial data on demand reduces usage of network bandwidth and system resources.gradually.

分页库可帮助您一次加载和显示小块数据。 按需加载部分数据会逐渐减少网络带宽和系统资源的使用。

Furthermore, the Paging Library Provides the following three common scenarios for loading data:

此外,分页库提供以下三种常见的数据加载方案:

  1. Stored only in an on-device database.

    仅存储在设备上的数据库中。

2. Served the database as a cache for data loaded from network

2.将数据库用作从网络加载的数据的缓存

3. Served only from a back-end server.

3.仅从后端服务器提供服务。

数据绑定 (Data Binding)

Initially, the Data Binding Library allows you to bind UI components in your layouts to data sources in your Android app by using a declarative format rather than programmatically. As you know, layouts are often defined in activities with code that calls UI framework methods. For instance, the code below calls findViewById() to find a TextView widget and bind it to the userName property of the viewModel variable:

最初, 数据绑定库允许您使用声明性格式而非编程方式将布局中的UI组件绑定到Android应用中的数据源。 如您所知,布局通常是在活动中使用调用UI框架方法的代码定义的。 例如,下面的代码调用findViewById()来查找TextView小部件并将其绑定到viewModel变量的userName属性:

findViewById<TextView>(R.id.sample_text).apply {
text = viewModel.userName
}

So, after using Data Binding library, you can change the code by using the assignment expression as follows:

因此,在使用数据绑定库之后,您可以使用赋值表达式来更改代码,如下所示:

<TextView
android:text="@{viewmodel.userName}" />

Binding components in the layout file allows you remove a number of UI framework calls in your activities, and make them simpler and easier to maintain. Besides, this can enhance your app’s performance, and help prevent memory leaks and null pointer exceptions. Another important point is that the Data Binding Library supports classes and methods to observe data for changes. So, you can be able to create your variables or their properties observable. In other words, the library allows you to make objects, fields, or collections observable.

通过在布局文件中绑定组件,您可以删除活动中的许多UI框架调用,并使它们更易于维护。 此外,这可以提高应用程序的性能,并有助于防止内存泄漏和空指针异常。 另一个重要的一点是,数据绑定库支持类和方法来观察数据的变化。 因此,您可以创建变量或其可观察的属性。 换句话说,该库使您可以观察对象,字段或集合。

结论 (In conclusion)

This article introduced main concepts and features that are used in Android Jetpack Architecture Components. Android Jetpack is set of libraries, tools, and guidance for modern Android development. In fact, Android Jetpack is built for modern design practices such as separation of concerns, test-ability, loose coupling, Observer Pattern, Inversion of Control as well as productivity features like Kotlin integration.

本文介绍了Android Jetpack体系结构组件中使用的主要概念和功能。 Android Jetpack是一套用于现代Android开发的库,工具和指南。 实际上,Android Jetpack是为现代设计实践而构建的,例如关注点分离,可测试性,松散耦合,观察者模式,控制反转以及Kotlin集成等生产率功能。

翻译自: https://medium.com/kayvan-kaseb/android-jetpack-architecture-components-119c9c973d7e

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值