利用應用程式動作,將 Android 應用程式擴充至 Google 助理

1. 總覽

有了應用程式動作,你就能透過語音直接使用 Google 助理開啟應用程式功能及完成各項工作。Android 開發人員可以實作功能元素來新增應用程式動作。你能透過這些功能,讓 Google 助理瞭解哪些應用程式功能支援使用者語音要求,並說明你希望如何達成要求。

本程式碼研究室涵蓋使用應用程式動作進行開發的入門級概念。您應具備開發 Android 應用程式和 Android 意圖的經驗,才能遵循本程式碼研究室。如果您是 Android 新手,建議從 Android 開發人員基礎知識的程式碼研究室著手。

建構項目

在這個程式碼研究室中,您要在健身 Android 範例應用程式中新增兩個應用程式動作內建意圖 (BII),讓使用者透過語音指令啟動及停止運動計時器。

課程內容

您將瞭解如何使用「健康與健身」類別中的 BII,藉此將 Google 助理擴充至 Android 應用程式。您也會瞭解如何使用 Android Studio 適用的 Google 助理外掛程式測試 BII。

必要條件

繼續操作前,請確認您的環境中有下列工具:

  • 已安裝 git 的終端機指令。
  • 最新版 Android Studio
  • 可存取 [Google Play 管理中心][]的 Google 帳戶。
  • 可連上網際網路的實體或虛擬 Android 裝置。

繼續操作前,請先確認同一個 Google 帳戶已登入 Android Studio,以及測試裝置上的 Google 應用程式。

2. 瞭解運作方式

應用程式動作會將 Google 助理使用者連結至您的 Android 應用程式。運作方式

當使用者要求 Google 助理使用應用程式執行工作時,Google 助理會將查詢內容與應用程式 shortcuts.xml XML 資源中定義的應用程式動作 capability 進行比對。

說明 Google 助理如何處理應用程式動作語音查詢的流程圖

圖 1. 說明 Google 助理如何處理應用程式動作語音查詢的流程圖。

每個功能元素都會定義:

  • 意圖:應觸發功能的應用程式動作語音意圖。
  • 一或多個執行要求:Google 助理為了啟動應用程式及執行使用者語音要求而產生的 Android 意圖或深層連結。執行要求定義會指明使用者查詢中預期的參數,以及這些參數應如何編碼到啟動操作說明中。

意圖

在自然語言理解 (NLU) 中,意圖是指具有類似意義的一組使用者詞組。Google 已推出數十種「內建」意圖 (BII),涵蓋應用程式動作可用的多種要求類型。舉例來說,Google 助理經過訓練,會將「點餐披薩」或「顯示甜點菜單」等詞組與 ORDER_MENU_ITEM BII 建立關聯。透過應用程式動作,您可以善用這些 BII,快速將常見的語音要求延伸到應用程式功能。

執行要求

當使用者要求在 shortcuts.xml 中觸發應用程式動作時,您的 Android 活動必須偵測及處理傳入的 Android 意圖或深層連結,並提供使用者所需的功能。這提供透過語音驅動的使用者體驗,Google 助理會根據使用者的查詢叫用您的應用程式。

3. 準備開發環境

本程式碼研究室會使用適用於 Android 的健身範例應用程式。此應用程式可讓使用者啟動和停止運動計時器,並查看有關自己例行運動的統計資料。

下載基礎檔案

如要取得本程式碼研究室的基礎檔案,請執行下列指令,複製 GitHub 存放區

git clone --branch codelab-start https://github.com/actions-on-google/appactions-fitness-kotlin.git

複製存放區後,請在 Android Studio 中開啟:

  1. 在「Welcome to Android Studio」對話方塊中,按一下「Import project」
  2. 找出並選取您複製存放區的資料夾。

更新 Android 應用程式 ID

更新應用程式的應用程式 ID 可在測試裝置上辨識應用程式,避免「套件名稱重複」錯誤訊息。如要更新應用程式 ID,請開啟 app/build.gradle

android {
...
  defaultConfig {
    applicationId "com.MYUNIQUENAME.android.fitactions"
    ...
  }
}

取代「MYUNIQUENAME」在 applicationId 欄位中使用不重複的值。

在裝置上試用應用程式

對應用程式程式碼的進一步變更之前,建議您先瞭解範例應用程式的功能。在開發環境中測試應用程式的步驟如下:

  1. 開啟虛擬或實體 Android 測試裝置。
  2. 正在確認 Google 助理應用程式是否正常運作。
  3. 使用 Android Studio 在裝置上部署及執行範例應用程式。

請按照下列步驟測試應用程式:

  1. 在 Android Studio 中,選取「Run」>「Run app」,或按一下工具列中的「Run」acabcb8f8634af20.png
  2. 如果使用虛擬裝置,請在「Select Deployment Target」對話方塊中選取虛擬裝置,然後按一下「OK」。建議的 OS 版本為 Android 8 (API 級別 26) 以上版本,不過動作可在搭載 Android 5 (API 級別 21) 以下版本的裝置上執行。
  3. 開啟應用程式後,請長按主畫面按鈕,以便設定 Google 助理並確認能正常運作。登入 Google 助理 (如果尚未登入的話)。
  4. 重新開啟應用程式。

手機開啟 Fit Actions 應用程式並顯示運動統計資料。

圖 2. Fit Actions 範例應用程式顯示運動統計資料。

簡短探索這個應用程式的功能。輕觸跑步圖示會開啟運動計時器,然後輕觸 X 圖示,停止計時器。你需利用應用程式動作進行語音控制的工作。

安裝 Google 助理外掛程式

您可以利用 Google 助理外掛程式,在測試裝置上測試應用程式動作。請按照下列步驟將其新增至 Android Studio:

  1. 前往「File」>「Settings」 (在 MacOS 中則為「Android Studio」>「Preferences」)。
  2. 在「外掛程式」部分中,前往 Marketplace 並搜尋「Google Assistant」。
  3. 安裝工具,然後重新啟動 Android Studio。

4. 新增「開始運動 BII」功能

actions.intent.START_EXERCISE BII 可讓使用者透過語音指令開啟應用程式並開始健身。在這個步驟中,您將實作這項 BII 的功能,讓使用者可以要求 Google 助理在健身應用程式中開始跑步。

定義功能

Google 助理會使用 shortcuts.xml 中定義的 capability 元素處理語音指令,步驟如下:

  1. Google 助理會根據使用者語音查詢,比對應用程式功能中定義的 BII。
  2. Google 助理會從查詢中擷取值,並轉換為 BII 參數。每個參數都會新增至 Bundle,並附加至產生的 Intent
  3. Google 助理會使用 Intent 啟動應用程式,為應用程式授予隨附參數的存取權。

START_EXERCISE BII 支援 exercise.name BII 參數。透過此參數,使用者可以指定在應用程式中追蹤的運動類型。

將此 capability 新增至位於 app/src/main/res/xml 範例專案目錄中的 shortcuts.xml,以便將 START_EXERCISE BII 新增至應用程式:

<!-- shortcuts.xml -->

<capability android:name="actions.intent.START_EXERCISE">
  <intent
    android:action="android.intent.action.VIEW"
    android:targetPackage="PUT_YOUR_APPLICATION_ID_HERE"
    android:targetClass="com.devrel.android.fitactions.FitMainActivity">
    <parameter
      android:name="exercise.name"
      android:key="exerciseType"/>
  </intent>
</capability>

PUT_YOUR_APPLICATION_ID_HERE 替換為您在上一個步驟中定義的不重複 applicationId

上述 XML 範例:

  • 宣告 START_EXERCISE BII 的功能。
  • 指定 Google 助理為啟動應用程式而產生的 Android intent
    • targetPackagetargetClass 屬性可指定接收活動。
    • parameter 屬性會將 exercise.name BII 參數對應至活動收到的 Bundle 額外項目中的 exerciseType

使用內嵌目錄處理 BII 參數

BII 參數代表從 Google 助理使用者查詢內容中擷取的元素。舉例來說,當使用者說出「Ok Google,在範例應用程式上開始跑步」時,Google 助理會擷取「跑步」複製到 exercise.name schema.org BII 參數中。針對部分 BII,您可以指示 Google 助理比對 BII 參數與應用程式預期的 ID 組合。

方法是將內嵌目錄元素繫結至 BII 參數。內嵌目錄是一組支援的 BII 參數值 (例如「run」、「hike」和「jog」),以及對應的捷徑 ID (例如 EXERCISE_RUN)。這個商品目錄繫結可讓 Google 助理傳遞相符參數的快速指令 ID (而非原始查詢值) 至執行要求活動。

部分 BII 參數 (例如 exercise.name) 需要內嵌目錄才能運作。如要處理這項參數,請在 shortcuts.xml 中加入下列目錄 shortcut 元素:

<!-- shortcuts.xml -->

<shortcuts>
  <shortcut
    android:shortcutId="running"
    android:shortcutShortLabel="@string/activity_running">
    <capability-binding android:key="actions.intent.START_EXERCISE">
      <parameter-binding
        android:key="exercise.name"
        android:value="@array/runningSynonyms"/>
    </capability-binding>
  </shortcut>

  <shortcut
    android:shortcutId="walking"
    android:shortcutShortLabel="@string/activity_walking">
    <capability-binding android:key="actions.intent.START_EXERCISE">
      <parameter-binding
        android:key="exercise.name"
        android:value="@array/walkingSynonyms"/>
    </capability-binding>
  </shortcut>

  <shortcut
    android:shortcutId="cycling"
    android:shortcutShortLabel="@string/activity_cycling">
    <capability-binding android:key="actions.intent.START_EXERCISE">
      <parameter-binding
        android:key="exercise.name"
        android:value="@array/cyclingSynonyms"/>
    </capability-binding>
  </shortcut>

  <capability> ... </capability>
</shortcuts>

在上述程式碼中,您已定義三個捷徑,代表應用程式支援的運動類型 (跑步、步行和騎自行車) 內嵌目錄。每個捷徑會以下列方式繫結至功能:

  • 每個 capability-binding 元素的 android:key 屬性都參照為功能定義的相同 START_EXCERCISE BII。
  • 每個快速鍵 exercise.name BII 參數的 parameter-binding 元素。

新增內嵌目錄同義詞

上述商品目錄捷徑中,parameter-binding 元素的 android:value 屬性會參照每個商品目錄元素的同義詞陣列資源。同義詞可啟用元素類型的變化版本,例如「跑步」、「慢跑」和「短跑」參照同一個 shortcutId。將下列同義詞項目新增至專案的 array.xml 資源:

<!-- array.xml -->
<array name="runningSynonyms">
  <item>Run</item>
  <item>Jog</item>
  <item>Jogging</item>
  <item>Sprint</item>
</array>

<array name="walkingSynonyms">
  <item>Walk</item>
  <item>Hike</item>
  <item>Hiking</item>
</array>

<array name="cyclingSynonyms">
  <item>Biking</item>
  <item>Riding</item>
  <item>Pedaling</item>
</array>

執行傳入的 Android 意圖

Android 意圖是 Android 用來向其他應用程式要求動作的訊息物件。Google 助理能滿足使用者的從已觸發功能中的設定詳細資料產生意圖,以產生語音查詢。為了執行 START_EXERCISE 功能的意圖,請更新 FitMainActivity 目標類別來處理傳入的意圖和 BII 參數。

首先,將 Intent.handleIntent 函式替換為以下程式碼:

//FitMainActivity.kt

private fun Intent.handleIntent() {
  when (action) {
    // When the BII is matched, Intent.Action_VIEW will be used
    Intent.ACTION_VIEW -> handleIntent(data)
    // Otherwise start the app as you would normally do.
    else -> showDefaultView()
  }
}

接著,使用下列程式碼在類別中新增 handleIntent 函式:

//FitMainActivity.kt

/**
 * Use extras provided by the intent to handle the different BIIs
 */

private fun handleIntent(data: Uri?) {
  // path is normally used to indicate which view should be displayed
  // i.e https://fit-actions.firebaseapp.com/start?exerciseType="Running" -> path = "start"
  var actionHandled = true

  val startExercise = intent?.extras?.getString(START_EXERCISE)
  // Add stopExercise variable here

  if (startExercise != null){
    val type = FitActivity.Type.find(startExercise)
    val arguments = Bundle().apply {
      putSerializable(FitTrackingFragment.PARAM_TYPE, type)
    }
    updateView(FitTrackingFragment::class.java, arguments)
  } // Add conditional for stopExercise
  else{
   // path is not supported or invalid, start normal flow.
   showDefaultView()

   // Unknown or invalid action
   actionHandled = false
  }
  notifyActionSuccess(actionHandled)
}

在上述 Intent.handleIntent 函式中,觸發 ACTION_VIEW 時,應用程式動作意圖資料會傳遞到 handleIntent 函式。START_EXERCISE 意圖中隨附的 BII 參數是透過 intent?.extras?.getString(START_EXERCISE) 存取。其餘函式會更新 FitTrackingFragment,以顯示所選的 startExercise 健身類型。

測試應用程式動作

在開發應用程式動作期間,您可以使用 Google 助理外掛程式,在測試裝置上預覽動作。您也可以使用這個外掛程式調整動作的意圖參數值,以測試應用程式如何處理使用者向 Google 助理要求應用程式語句的各種方式。

如要使用外掛程式測試應用程式動作,請按照下列步驟操作:

  1. 選擇「Run」>,在 Android Studio 中執行應用程式「Run App」,或按一下頂端工具列的「Run」圖示。
  2. 前往「工具」>應用程式動作 >Google 助理 >應用程式動作測試工具
  3. 按一下「Create Preview」。如果收到系統提示,請詳閱並接受應用程式動作政策和服務條款。
  4. 選取 actions.intent.START_EXERCISE 內建意圖。
  5. 在「運動」方塊中,保留預設的 running 值。
  6. 按一下「Run App Action」。確認 Google 助理深層連結到應用程式的運動計時器,並且計時器已經開始跑步類型的運動。

您已使用 START_EXERCISE BII 實作第一個應用程式動作。恭喜!接著,使用者可以停止應用程式中的跑步運動。

5. 新增停止運動 BII 功能

actions.intent.STOP_EXERCISE BII 可讓使用者透過「Ok Google,在範例應用程式上停止跑步」這類指令,停止健身工作階段。如要在健身應用程式中實作這個 BII,請在 shortcuts.xml 中新增第二個 capability

<!-- shortcuts.xml -->

<capability android:name="actions.intent.STOP_EXERCISE">
  <intent
    android:action="android.intent.action.VIEW"
    android:targetPackage="PUT_YOUR_APPLICATION_ID_HERE"
    android:targetClass="com.devrel.android.fitactions.FitMainActivity">
    <!-- Eg. name = "Running" -->
    <parameter
        android:name="exercise.name"
        android:key="stopExercise"/>
  </intent>
</capability>

PUT_YOUR_APPLICATION_ID_HERE 替換成您專屬的 applicationId

使用內嵌目錄處理 BII 參數

這個 BII 支援與 START_EXERCISE BII 相同的 exercise.name 參數,可讓使用者指定要結束哪些進行中的運動。如要啟用這項功能,請在 shortcuts.xml 中加入第二組商品目錄捷徑元素:

<!-- shortcuts.xml -->

<shortcut
  android:shortcutId="running"
  android:shortcutShortLabel="@string/activity_running">
  <capability-binding android:key="actions.intent.STOP_EXERCISE">
      <parameter-binding
          android:key="exercise.name"
          android:value="@array/runningSynonyms"/>
  </capability-binding>
</shortcut>

<shortcut
  android:shortcutId="walking"
  android:shortcutShortLabel="@string/activity_walking">
  <capability-binding android:key="actions.intent.STOP_EXERCISE">
      <parameter-binding
          android:key="exercise.name"
          android:value="@array/walkingSynonyms"/>
  </capability-binding>
</shortcut>

<shortcut
  android:shortcutId="cycling"
  android:shortcutShortLabel="@string/activity_cycling">
  <capability-binding android:key="actions.intent.STOP_EXERCISE">
      <parameter-binding
          android:key="exercise.name"
          android:value="@array/cyclingSynonyms"/>
  </capability-binding>
</shortcut>

執行傳入的 Android 意圖

更新 FitMainActivity 類別,讓應用程式能夠處理傳入的 STOP_EXERCISE Android 意圖。首先,在 handleIntent 函式中新增變數來存放 STOP_EXERCISE 意圖資料:

// FitMainActivity.kt

private fun handleIntent(data: Uri?) {
  val stopExercise = intent?.extras?.getString(STOP_EXERCISE)
  //...
}

接著,請更新 handleIntent 函式的條件邏輯,以便處理 STOP_EXERCISE 意圖:

// FitMainActivity.kt

private fun handleIntent(data: Uri?) {
  //...
  if (startExercise != null){
    val type = FitActivity.Type.find(startExercise)
    val arguments = Bundle().apply {
      putSerializable(FitTrackingFragment.PARAM_TYPE, type)
    }
    updateView(FitTrackingFragment::class.java, arguments)
  } // Add conditional for stopExercise
  <strong>
  } else if(stopExercise != null){
    // Stop the tracking service if any and return to home screen.
    stopService(Intent(this, FitTrackingService::class.java))
    updateView(FitStatsFragment::class.java)
  }
  </strong>
  //...
}

在上述程式碼中,您已更新 handleIntent 函式,以便檢查傳入的 Android 意圖中的 STOP_EXERCISE BII。如果找到,此函式會停止執行中的計時器,並將使用者帶回主畫面。

測試應用程式動作

使用 Google 助理外掛程式測試應用程式動作的步驟如下:

  1. 選擇「Run」>,在 Android Studio 中執行應用程式「Run App」,或按一下頂端工具列的「Run」圖示。
  2. 在應用程式中,啟動新的「跑步」運動。
  3. 在 Android Studio 中開啟這個外掛程式:前往「Tools」>應用程式動作 >Google 助理 >應用程式動作測試工具
  4. 按一下「Create Preview」
  5. 選取 actions.intent.STOP_EXERCISE 內建意圖。
  6. 在「運動」方塊中,保留預設的 running 值。
  7. 按一下「Run App Action」。確認 Google 助理停止運動並返回主畫面。

6. 後續步驟

恭喜!

您已瞭解如何使用 Google 助理內建意圖,為 Android 應用程式啟用語音功能。在本程式碼研究室中,您已瞭解以下內容:

  • 如何讓使用者透過 Google 助理深入探索特定的應用程式功能。
  • 如何使用內嵌目錄。
  • 如何使用 Google 助理外掛程式測試 BII。

後續步驟

從這裡,您可以嘗試進一步修正健身應用程式。如要參照完成的專案,請參閱 GitHub 上的主要分支版本

歡迎參考下列建議,進一步瞭解如何利用應用程式動作擴充這個應用程式:

如要繼續進行 Actions on Google 流程,請參閱下列資源:

在 Twitter 上追蹤 @ActionsOnGoogle,以隨時掌握最新公告,並透過 #appactions 使用 Twitter 分享自己的成果!

意見回饋問卷調查

最後,請填寫這份問卷調查,與我們分享您使用本程式碼研究室的感想。