AWS 入門

建置 Android 應用程式

使用 AWS Amplify 建立簡單的 Android 應用程式

第二單元︰初始化 Amplify

在本單元中,您將安裝和設定 Amplify CLI。

簡介

現在,我們已建立一個 Android 應用程式,我們希望繼續開發並新增功能。

若要開始在您的應用程式中使用 AWS Amplify,必須安裝 Amplify 命令列,初始化 Amplify 專案目錄,將您的專案設定為使用 Amplify 程式庫,然後在執行時間初始化 Amplify 程式庫。

您將學到的內容

  • 初始化新的 Amplify 專案
  • 將 Amplify 程式庫新增至您的專案
  • 在執行時間初始化 Amplify 程式庫

主要概念

Amplify CLI – Amplify CLI 讓您可以直接從終端機建立、管理和移除 AWS 服務。

Amplify 程式庫 – Amplify 程式庫讓您可以透過 Web 或行動應用程式與 AWS 服務進行互動。

 完成時間

10 分鐘

 使用的服務

實作

  • AWS Amplify CLI 取決於 Node.js,請參閱簡介中的先決條件部分以安裝 Node.js

    若要安裝 AWS Amplify CLI,請開啟一個終端機,然後鍵入以下命令:

    ## Install Amplify CLI
    npm install -g @aws-amplify/cli
    
    ## Verify installation and version
    amplify --version
    # Scanning for plugins...
    # Plugin scan successful
    # 4.29.4
  • 若要建立後端的基本結構,我們首先需要初始化 Amplify 專案目錄,然後建立我們的雲端後端。

    開啟終端機,然後切換至專案目錄。例如,如果您在 ~/AndroidStudioProjects/android-getting-started 資料夾中建立了專案,則可以輸入:

    cd ~/AndroidStudioProjects/android-getting-started  

    驗證是否處於正確的目錄,應如下所示:

    ➜  android-getting-started git:(main) ✗ ls -al
    total 32
    drwxr-xr-x  14 stormacq  admin   448 Oct  6 14:06 .
    drwxr-xr-x  16 stormacq  admin   512 Oct  6 11:28 ..
    -rw-r--r--   1 stormacq  admin   208 Oct  6 14:04 .gitignore
    drwxr-xr-x   6 stormacq  admin   192 Oct  6 14:04 .gradle
    drwxr-xr-x  13 stormacq  admin   416 Oct  6 15:19 .idea
    drwxr-xr-x   8 stormacq  admin   256 Oct  6 14:06 app
    drwxr-xr-x   3 stormacq  admin    96 Oct  6 14:06 build
    -rw-r--r--   1 stormacq  admin   642 Oct  6 14:04 build.gradle
    drwxr-xr-x   3 stormacq  admin    96 Oct  6 14:04 gradle
    -rw-r--r--   1 stormacq  admin  1162 Oct  6 14:04 gradle.properties
    -rwxr--r--   1 stormacq  admin  5296 Oct  6 14:04 gradlew
    -rw-r--r--   1 stormacq  admin  2260 Oct  6 14:04 gradlew.bat
    -rw-r--r--   1 stormacq  admin   437 Oct  6 14:04 local.properties
    -rw-r--r--   1 stormacq  admin    59 Oct  6 14:04 settings.gradle

    初始化 Amplify 專案結構和組態檔案。執行以下命令

    amplify init
    
    ? Enter a name for your project (androidgettingstarted): accept the default, press enter
    ? Enter a name for the environment (dev): accept the default, press enter
    ? Choose your default editor: use the arrow key to select your favorite text editor an press enter
    ? Choose the type of app that you're building: android is already selected, press enter
    ? Where is your Res directory: accept the default, press enter
    ? Do you want to use an AWS profile?, Y, press enter
    ? Please choose the profile you want to use: use the arrow keys to select your profile and press enter.

    如果還沒有,可以透過 AWS CLI 使用 aws configure --profile <name> 建立設定檔。

    Amplify 在雲端初始化您的專案,這可能需要幾分鐘。幾分鐘後,您應看到如下訊息:

    ✔ Successfully created initial AWS cloud resources for deployments.
    ✔ Initialized provider successfully.
    Initialized your environment successfully.
    
    Your project has been successfully initialized and connected to the cloud!
  • Amplify for Android 作為 Apache Maven 套件分發。在這部分中,您會將套件和其他必要的指令新增至建置組態。

    返回 Android Studio,展開 Gradle Scripts (Gradle 指令碼),然後開啟 build.gradle (Project: Android_Getting_Started)。在 buildscript 和 allprojects 區塊的 repository 區塊內新增行 mavenCentral()。

    buildscript {
        ext.kotlin_version = "1.4.10"
        repositories {
            google()
            jcenter()
    
            // Add this line into `repositories` in `buildscript`
            mavenCentral()
        }
        dependencies {
            classpath "com.android.tools.build:gradle:4.0.1"
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }
    
    allprojects {
        repositories {
            google()
            jcenter()
    
            // Add this line into `repositories` in `buildscript`
            mavenCentral()
        }
    }

    Gradle Scripts (Gradle 指令碼) 下,開啟 build.gradle (Module:app),然後在實作區塊中新增 Amplify 框架核心相依項。

    dependencies {
        implementation fileTree(dir: "libs", include: ["*.jar"])
        implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
        implementation 'androidx.core:core-ktx:1.3.2'
        implementation 'androidx.appcompat:appcompat:1.2.0'
        implementation 'com.google.android.material:material:1.2.1'
        implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
        implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0'
        implementation 'androidx.navigation:navigation-ui-ktx:2.3.0'
        testImplementation 'junit:junit:4.13'
        androidTestImplementation 'androidx.test.ext:junit:1.1.2'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    
        // Amplify core dependency
        implementation 'com.amplifyframework:core:1.4.0'
    }

    若您使用 Java 或者目標 Android SDK 21 或更早版本進行開發,請檢查文件以進行額外的組態變更。

    現在,執行 Gradle Sync (Gradle 同步)

    一段時間後,您應看到

    BUILD SUCCESSFUL in 1s
  • 我們來建立一個後端類別,對程式碼進行分組,以便與我們的後端互動。我使用 singleton 設計模式,使其可輕鬆用於應用程式,並確保 Amplify 程式庫僅初始化一次。

    類別初始化程式負責初始化 Amplify 程式庫。

    在 java/com.example.androidgettingstarted 下建立一個新的 kotlin 檔案 Backend.kt,將其開啟並新增以下程式碼:

    package com.example.androidgettingstarted
    
    import android.content.Context
    import android.util.Log
    import com.amplifyframework.AmplifyException
    import com.amplifyframework.core.Amplify
    
    object Backend {
    
        private const val TAG = "Backend"
    
        fun initialize(applicationContext: Context) : Backend {
            try {
                Amplify.configure(applicationContext)
                Log.i(TAG, "Initialized Amplify")
            } catch (e: AmplifyException) {
                Log.e(TAG, "Could not initialize Amplify", e)
            }
            return this
        }
    }

    應用程式啟動後,我們初始化 singleton 後端物件。

    在 java/com.example.androidgettingstarted 下建立一個新的 kotlin 檔案 Application.kt,將其開啟並新增以下程式碼:

    package com.example.androidgettingstarted
    
    import android.app.Application
    
    class AndroidGettingStartedApplication : Application() {
    
        override fun onCreate() {
            super.onCreate()
    
            // initialize Amplify when application is starting
            Backend.initialize(applicationContext)
        }
    }

    在清單下,開啟 AndroidManifest.xml 並將應用程式類別的名稱新增至 <application> 元素。

        <!-- add the android:name attribute to the application node  -->
        <application
            android:name="AndroidGettingStartedApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.GettingStartedAndroid">
    ...

    開啟此檔案後,新增一些應用程式在本教學後續步驟中需要的許可:

        <!-- add these nodes between manifest and application  -->
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  • 若要驗證是否一切如預期,請建置並執行專案。按一下工具列中的 Run (執行) 圖示 ▶️,或鍵入 ^ R

    若要驗證是否一切如預期,請建置並執行專案。按一下工具列中的 Run (執行) 圖示 ▶️ 或鍵入 ^ R

    應不會發生錯誤。

    BUILD SUCCESSFUL in 6s
    23 actionable tasks: 8 executed, 15 up-to-date

結論

您已經初始化了 Amplify 專案,現在可以開始新增功能了! 在下一個單元中,我們將僅使用幾行程式碼,新增完整的使用者身份驗證流程。

這個單元對您是否有幫助?

新增身份驗證