Android Jetpack(二) 基础

基础组件可提供横向功能,例如向后兼容性、测试和 Kotlin 语言支持。

1、Android KTX - 编写更简洁、惯用的 Kotlin 代码

KTX 拥有的一些 扩展程序列表


dependencies 
{
//androidx.activity
implementation "androidx.activity:activity-ktx:1.1.0"
//androidx.benchmark
implementation "androidx.benchmark:benchmark-junit4:1.0.0"
//androidx.collection
implementation "androidx.collection:collection-ktx:1.1.0"
//androidx.core
implementation "androidx.core:core-ktx:1.2.0"
//androidx.dynamicanimation
implementation "androidx.dynamicanimation:dynamicanimation-ktx:1.0.0-alpha03"
//androidx.fragment
implementation "androidx.fragment:fragment-ktx:1.2.4"
//androidx.fragment.app.testing
implementation "androidx.fragment:fragment-testing:1.2.4"


//androidx.lifecycle
implementation "androidx.lifecycle:lifecycle-livedata-core-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"

//androidx.navigation
implementation "androidx.navigation:navigation-runtime-ktx:2.3.0-alpha04"
implementation "androidx.navigation:navigation-fragment-ktx:2.3.0-alpha04"
implementation "androidx.navigation:navigation-ui-ktx:2.3.0-alpha04"

//androidx.paging
implementation "androidx.paging:paging-common-ktx:2.1.2"
implementation "androidx.paging:paging-runtime-ktx:2.1.2"
implementation "androidx.paging:paging-rxjava2-ktx:2.1.2"

//androidx.palette
implementation "androidx.palette:palette-ktx:1.0.0"
//androidx.preference
implementation "androidx.preference:preference-ktx:1.1.0"
//androidx.room
implementation "androidx.room:room-ktx:2.2.5"
//androidx.slice.builders
implementation "androidx.slice:slice-builders-ktx:1.0.0-alpha07"
//androidx.sqlite
implementation "androidx.sqlite:sqlite-ktx:2.1.0"
//androidx.work.testing
implementation "androidx.work:work-testing:2.3.4"
//com.google.android.play.core.ktx
implementation "com.google.android.play:core-ktx:1.7.1"

}

2、AppCompat

appcompat 库已经迁移到 AndroidX 库,此库增加了对操作栏界面设计模式的支持。此库包含对 Material Design 界面实现的支持。

最近更新时间:2019 年 9 月 5 日 发布稳定版1.1.0

implementation "androidx.appcompat:appcompat:1.1.0"

3、Auto - 有助于开发 Android Auto 应用的组件(车载系统)

搭载苹果 CarPlay 系统的新车在国内越来越多了,iOS 党的驾车体验变得比原来更好了,有鉴于此,我准备来关爱一下安卓用户。

提到安卓系统的车机手机互联方案,可能你首先想到的就是谷歌的 Android Auto,当然,还有百度家的 CarLife、乐视的 ecolink 以及 MirrorLink 等,但是在全球范围内能和 CarPlay 一战的,恐怕只有 Android Auto 了,基于谷歌强大的生态系统,Android Auto 在使用体验和功能上并不比 CarPlay 差,而且,苹果和谷歌在车载领域的竞争,也能从这两个系统里面直接看出。
但是,在我朝,Android Auto 几乎销声匿迹,CarPlay 呈现碾压的态势。原因大家都懂的,很多人的理解都是:因为谷歌退出中国,所以在国内销售的汽车,都会「阉割」掉谷歌的 Android Auto。

https://developer.android.google.cn/training/cars

Android Automotive OS

是一款 Android 信息娱乐系统,专门内置到了车辆中。车载系统是专为车辆优化的独立 Android 设备。
用户不用使用您的手机应用,而是直接在音响主机上安装驾驶员优化的应用版本。您可以将针对 Android Automotive OS 创建的服务重复用于 Android Auto,但您必须要为一些 Activity(如“登录”和“设置”)设计和实现车载界面。

Android Auto

提供了针对驾驶员优化的应用体验,适用于使用 Android 手机和 Android Auto 应用但没有 Android Automotive OS 车辆的用户。如果用户的汽车或售后市场立体音响系统支持 Android Auto,则可以通过连接手机直接在汽车显示屏上使用您的应用
您可以通过添加 Android Auto 使用的服务使 Android Auto 能够连接您的手机应用,以向驾驶员显示驾驶员优化界面。您可以重复使用这些 Android Automotive OS 应用服务,但用户不用将您的手机应用安装到他们的汽车上。
Android Auto 已拥有数百万用户和数百款兼容的汽车以及售后市场立体音响系统

Android Auto 让您在编写应用时无需担心特定于车辆的硬件差异(如屏幕分辨率、软件界面、旋钮和触摸式控件)。用户可以通过手机上的 Android Auto 应用访问您的应用。或者,当连接到兼容车辆时,运行 Android 5.0(或更高版本)的手持设备上的应用可以与通过 Android Auto 投射到车辆的应用进行通信。

4、检测 - 从 Android Studio 中快速检测基于 Kotlin 或 Java 的代码

使用 Jetpack 基准库,您可以在 Android Studio 中快速对 Kotlin 或 Java 代码进行基准化分析。该库会处理预热,衡量代码性能,并将基准化分析结果输出到 Android Studio 控制台。

如果您使用的是 Android Studio 3.5,则必须手动设置 Android Studio 属性才能启用基准模块向导支持。Android Studio 3.6 或更高版本不需要手动设置。

要启用 Android Studio 基准化分析模板,请执行以下操作:
1.在 Android Studio 3.5 中,依次点击 Help > Edit Custom Properties。
2.将以下行添加到随即打开的文件中:npw.benchmark.template.module=true
3.保存并关闭该文件。
4.重启 Android Studio。
https://developer.android.google.cn/studio/profile/benchmark

5、多dex处理 - 为具有多个 DEX 文件的应用提供支持

为方法数超过 64K 的应用启用多 dex 文件
当您的应用及其引用的库包含的方法数量超过 65536 时,您会遇到一个构建错误,指明您的应用已达到 Android 构建架构规定的引用限制:

    trouble writing output:
    Too many field references: 131000; max is 65536.
    You may try using --multi-dex option.

较低版本的构建系统会报告一个不同的错误,但指示的是同一问题:

    Conversion to Dalvik format failed:
    Unable to execute dex: method ID not in [0, 0xffff]: 65536

这两种错误情况都会显示一个共同的数字:65536。此数字是单个 Dalvik Executable (DEX) 字节码文件内的代码可调用的引用总数。本页介绍如何通过启用称为“多 dex 文件”的应用配置(该配置使您的应用能够构建和读取多个 DEX 文件)来越过这一限制。

Android 5.0 之前版本的多 dex 文件支持

Android 5.0(API 级别 21)之前的平台版本使用 Dalvik 运行时来执行应用代码。默认情况下,Dalvik 将应用限制为每个 APK 只能使用一个 classes.dex 字节码文件。要绕过这一限制,您可以在您的项目中添加多 dex 文件支持库:

 dependencies {
        def multidex_version = "2.0.1"
        implementation 'androidx.multidex:multidex:$multidex_version'
    }

如果您不使用 AndroidX,请改为添加以下支持库依赖项:

 dependencies {
      implementation 'com.android.support:multidex:1.0.3'
    }

此库会成为应用的主要 DEX 文件的一部分,然后管理对其他 DEX 文件及其所包含代码的访问

Android 5.0 及更高版本的多 dex 文件支持

Android 5.0(API 级别 21)及更高版本使用名为 ART 的运行时,它本身支持从 APK 文件加载多个 DEX 文件。ART 在应用安装时执行预编译,扫描 classesN.dex 文件,并将它们编译成单个 .oat 文件,以供 Android 设备执行。因此,如果您的 minSdkVersion 为 21 或更高的值,则默认情况下启用多 dex 文件,并且您不需要多 dex 文件支持库。

针对多 dex 文件配置您的应用

如果您的 minSdkVersion 设为 21 或更高的值,则默认情况下启用多 dex 文件,并且您不需要多 dex 文件支持库。
不过,如果您的 minSdkVersion 设为 20 或更低的值,则必须使用多 dex 文件支持库并对应用项目进行以下修改:

  1. 修改模块级 build.gradle 文件以启用多 dex 文件,并将多 dex 文件库添加为依赖项,如下所示:
 android {
        defaultConfig {
            ...
            minSdkVersion 15
            targetSdkVersion 28
            multiDexEnabled true
        }
        ...
    }

    dependencies {
      implementation 'com.android.support:multidex:1.0.3'
    }

2.对Application的配置
方法一:不替换Application

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.myapp">
        <application
                android:name="android.support.multidex.MultiDexApplication" >
            ...
        </application>
    </manifest>

方法二:替换Application

public class MyApplication extends MultiDexApplication { ... }

方法三(推荐):替换 Application类,不改基类
则可以改为替换 attachBaseContext()方法并调用 MultiDex.install(this)来启用多 dex 文件:

 class MyApplication : SomeOtherApplication() {

        override fun attachBaseContext(base: Context) {
            super.attachBaseContext(base)
            MultiDex.install(this)
        }
    }

6、安全 - 按照安全最佳做法读写加密文件和共享偏好设置

作为 Android Jetpack的一部分,Security 库提供了与读取和写入静态数据以及密钥创建和验证相关的安全最佳做法实现方法。

该库使用构建器模式为以下安全等级提供安全的默认设置:

  • **在可靠加密和良好性能之间取得平衡的强安全性。**这种安全等级适用于银行和聊天应用等消费者应用,以及执行证书吊销检查的企业应用。
  • **最高安全性。**这种安全等级适用于需要由硬件支持的密钥库和用户上线以提供密钥访问权限的应用。

介绍了如何使用 Security 库的建议安全配置,以及如何轻松且安全地读取和写入存储在文件和共享偏好设置中的加密数据。

密钥管理

Security 库使用一个由两部分组成的密钥管理系统:

  • 包含一个或多个密钥的密钥集,用于加密文件或共享偏好设置数据。密钥集本身存储在 SharedPreferences 中。
  • 用于加密所有密钥集的主密钥。此密钥使用 Android 密钥库系统进行存储。

库中包含的类

Security 库包含以下类,以提供更安全的静态数据:

EncryptedFile

提供 FileInputStream 和 FileOutputStream 的自定义实现,为您的应用赋予更安全的流式读写操作。

EncryptedSharedPreferences

封装 SharedPreferences 类,并使用双重方案方法自动加密密钥和值:

  • 密钥使用确定性加密算法进行加密,这样便可以正确查找和加密密钥。
  • 值使用 AES-256 GCM 加密,并且具有不确定性。
使用 EncryptedFile 以更安全的方式读取文件内容:
// Although you can define your own key generation parameter specification, it's
    // recommended that you use the value specified here.
    val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC
    val masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec)

    val fileToRead = "my_sensitive_data.txt"
    val encryptedFile = EncryptedFile.Builder(
        File(directory, fileToRead),
        context,
        masterKeyAlias,
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()

    val contents = encryptedFile.bufferedReader().useLines { lines ->
        lines.fold("") { working, line ->
            "$working\n$line"
        }
    }
    
使用 EncryptedFile 以更安全的方式写入文件内容:
// Although you can define your own key generation parameter specification, it's
    // recommended that you use the value specified here.
    val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC
    val masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec)

    // Creates a file with this name, or replaces an existing file
    // that has the same name. Note that the file name cannot contain
    // path separators.
    val fileToWrite = "my_sensitive_data.txt"
    val encryptedFile = EncryptedFile.Builder(
        File(directory, fileToWrite),
        context,
        masterKeyAlias,
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()

    encryptedFile.openFileOutput().bufferedWriter().use {
        it.write("MY SUPER-SECRET INFORMATION")
    }
    

对于需要额外安全性的用例,请完成以下步骤:

  1. 创建一个 KeyGenParameterSpec.Builder 对象,将 true 传递到 setUserAuthenticationRequired(),并将一个大于 0 的值传递到 setUserAuthenticationValidityDurationSeconds()

  2. 使用 createConfirmDeviceCredentialIntent() 提示用户输入凭据。详细了解如何要求用户验证身份才能使用密钥

    注意:Security 库在加密操作级别不支持 BiometricPrompt

  3. 替换 onActivityResult() 以获取经确认的凭据回调。

如需了解详情,请参阅要求用户验证身份才能使用密钥

修改共享偏好设置

使用 EncryptedSharedPreferences 以更安全的方式修改用户的一组共享偏好设置:

val sharedPreferences = EncryptedSharedPreferences
        .create(
        fileName,
        masterKeyAlias,
        context,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )

    val sharedPrefsEditor = sharedPreferences.edit()

7、测试 - 用於单元和运行时界面测试的 Android 测试框架

https://developer.android.google.cn/training/testing/

8、TV - 有助于开发 Android TV 应用的组件

可让用户在大屏幕上体验沉浸式内容的应用。用户可以在主屏幕上发现内容推荐信息,并且 Leanback 库提供了各种 API,可以帮助您打造绝佳的遥控器使用体验
https://developer.android.google.cn/training/tv

9、Wear OS by Google 谷歌 - 有助于开发 Wear 应用的组件

Wear OS 基于 Android 设计,并且专门针对腕部佩戴进行了优化。如果您已有 Android 开发经验,那么您可能会对应用、通知和 Actions on Google 等功能十分熟悉。 此外,Wear OS 还提供了新的开发选项,例如表盘主题。
https://developer.android.google.cn/training/wearables

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章