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

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