AWS 入门

构建 Android 应用程序

使用 AWS Amplify 创建简易 Android 应用程序

模块 2:初始化 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 并打开 build.gradle (Project: Android_Getting_Started)。在 buildscript 和 allprojects 数据块的 repositories 数据块内添加行 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 下,打开 build.gradle (Module:app),并在 implementations 数据块中添加 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

      过一会儿您将看到

      BUILD SUCCESSFUL in 1s
    • 我们来创建一个后端类对代码进行分组,以便与后端交互。我使用单例设计模式,使其通过应用程序轻松可用,并确保 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
          }
      }

      应用程序启动时,初始化单例 Backend 对象。

      在 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)
          }
      }

      在“manifests”下,打开 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"/>
    • 要验证一切是否都按预期运行,请构建并运行项目。单击工具栏中的运行图标 ▶️,或按 ^ R

      要验证一切是否都按预期运行,请构建并运行项目。单击工具栏中的 运行 图标 ▶️ 或按 ^ R

      应该不会出现错误。

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

    结论

    您已成功初始化 Amplify 项目,现在可以开始添加功能了!在下一个模块中,我们将仅用几行代码添加完整的用户身份验证流程。

    添加身份验证