建立捷徑

捷徑可協助使用者快速存取應用程式的某些部分,進而提供特定類型的內容。

這張圖片顯示應用程式捷徑和固定捷徑之間的對比
圖 1:應用程式捷徑和固定捷徑。

至於如何透過捷徑提供內容,則取決於您的用途,以及捷徑的結構定義是由應用程式驅動還是使用者驅動。雖然靜態捷徑的情境不會改變,且動態捷徑的情境會不斷改變,但您的應用程式會在這兩種情況下驅動結構定義。如果使用者選擇應用程式傳遞內容的方式 (例如使用固定捷徑),則情境是由使用者定義。以下列舉各個捷徑類型的幾種用途:

  • 靜態捷徑 最適合在使用者與應用程式互動的整個生命週期內,使用一致的結構連結至內容的應用程式。由於大部分的啟動器只會一次顯示四個捷徑,因此靜態捷徑就適合以一致的方式執行例行工作,例如使用者想以特定方式查看日曆或電子郵件時。
  • 動態捷徑適用於與情境相關的應用程式動作。系統會根據使用者在應用程式中執行的操作,提供與情境相關的捷徑。舉例來說,如果您建構的遊戲可讓使用者在啟動時從目前的關卡開始遊戲,則需要經常更新捷徑。使用動態捷徑可讓您在每次使用者清除關卡時更新捷徑。
  • 固定捷徑則用於使用者驅動的特定動作。舉例來說,使用者可能會想將特定網站固定到啟動器中。這種做法的好處是可以讓使用者執行自訂動作 (例如透過一個步驟前往網站),速度比使用瀏覽器的預設執行個體更快。

建立靜態捷徑

靜態捷徑會提供應用程式內一般動作的連結,而且這些動作必須在應用程式的目前版本的生命週期中保持一致。靜態捷徑的適用選項包括查看已傳送的訊息、設定鬧鐘,以及顯示當天的使用者運動活動。

如要建立靜態捷徑,請執行下列步驟:

  1. 在應用程式的 AndroidManifest.xml 檔案中,找出意圖篩選器設為 android.intent.action.MAIN 動作和 android.intent.category.LAUNCHER 類別的活動。

  2. <meta-data> 元素加入此活動,該活動會參照定義應用程式捷徑的資源檔案:

      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
                package="com.example.myapplication">
        <application ... >
          <activity android:name="Main">
            <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            
            <meta-data android:name="android.app.shortcuts"
                       android:resource="@xml/shortcuts" /> 
          </activity>
        </application>
      </manifest>
      
  3. 建立名為 res/xml/shortcuts.xml 的新資源檔案。

  4. 在新資源檔案中,新增包含 <shortcut> 元素清單的 <shortcuts> 根元素。在每個 <shortcut> 元素中,加入靜態捷徑的相關資訊,包括圖示、說明標籤,以及在應用程式中啟動的意圖:

      <shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
        <shortcut
          android:shortcutId="compose"
          android:enabled="true"
          android:icon="@drawable/compose_icon"
          android:shortcutShortLabel="@string/compose_shortcut_short_label1"
          android:shortcutLongLabel="@string/compose_shortcut_long_label1"
          android:shortcutDisabledMessage="@string/compose_disabled_message1">
          <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example.myapplication"
            android:targetClass="com.example.myapplication.ComposeActivity" />
          <!-- If your shortcut is associated with multiple intents, include them
               here. The last intent in the list determines what the user sees when
               they launch this shortcut. -->
          <categories android:name="android.shortcut.conversation" />
          <capability-binding android:key="actions.intent.CREATE_MESSAGE" />
        </shortcut>
        <!-- Specify more shortcuts here. -->
      </shortcuts>
      

自訂屬性值

以下清單包含靜態捷徑中不同屬性的說明。提供 android:shortcutIdandroid:shortcutShortLabel 的值。其他值皆為選用值。

android:shortcutId

字串常值,代表 ShortcutManager 物件執行作業時所在的捷徑。

android:shortcutShortLabel

說明捷徑用途的簡短詞語。請盡可能將簡短說明限制在 10 個半形字元以內。

詳情請參閱 setShortLabel()

android:shortcutLongLabel

說明捷徑用途的擴充詞組。如果空間足夠,啟動器會顯示這個值,而不是 android:shortcutShortLabel。請盡可能將此詳細說明長度限制在 25 個字元以內。

詳情請參閱 setLongLabel()

android:shortcutDisabledMessage

當使用者嘗試啟動已停用的捷徑時,支援的啟動器中顯示的訊息。這則訊息必須向使用者說明停用捷徑的原因。如果 android:enabledtrue,這個屬性的值不會有任何作用。

android:enabled

決定使用者是否能透過支援的啟動器與捷徑互動。android:enabled 的預設值為 true。如果設為 false,請設定 android:shortcutDisabledMessage 以說明停用捷徑的原因。如果認為不需要提供這類訊息,請從 XML 檔案中完全移除捷徑。

android:icon

啟動器在向使用者顯示捷徑時使用的點陣圖自動調整圖示。這個值可以是圖片的路徑,或是包含圖片的資源檔案。請盡可能使用自動調整圖示,以改善效能和一致性。

設定內部元素

列出應用程式靜態捷徑的 XML 檔案在每個 <shortcut> 元素中支援下列元素。您定義的每個靜態捷徑都必須加入 intent 內部元素。

intent

當使用者選取捷徑時,系統會啟動的動作。這個意圖必須提供 android:action 屬性的值。

可為單一捷徑提供多個意圖。詳情請參閱「管理多個意圖和活動」、「設定意圖」及 TaskStackBuilder 類別參考資料。

categories

針對應用程式捷徑執行的動作類型提供分組,例如建立新的即時通訊訊息。

如需支援的捷徑類別清單,請參閱 ShortcutInfo 類別參考資料。

capability-binding

宣告與捷徑連結的功能

在上一個範例中,捷徑連結至為 CREATE_MESSAGE 宣告的功能,這是應用程式動作內建意圖。這項功能繫結可讓使用者透過 Google 助理使用語音指令叫用捷徑。

建立動態捷徑

動態捷徑提供應用程式中與情境相關的特定動作連結。這些動作可能會在應用程式使用期間和執行期間發生變化。動態捷徑的建議做法包括呼叫特定使用者、前往特定位置,以及從使用者的最後儲存點載入遊戲。你也可以使用動態捷徑開啟會話群組。

ShortcutManagerCompat Jetpack 程式庫是 ShortcutManager API 的輔助程式,可讓您管理應用程式中的動態捷徑。使用 ShortcutManagerCompat 程式庫可減少樣板程式碼,並有助於確保捷徑在各個 Android 版本上都能一致。此外,推送動態捷徑時也必須使用這個程式庫,才能利用 Google 捷徑整合資料庫在 Google 途徑 (如 Google 助理) 顯示捷徑。

ShortcutManagerCompat API 可讓應用程式透過動態捷徑執行下列作業:

如要進一步瞭解如何執行捷徑作業,請參閱「管理捷徑」和 ShortcutManagerCompat 參考資料。

以下範例說明如何建立動態捷徑,並將其與應用程式建立關聯:

Kotlin


val shortcut = ShortcutInfoCompat.Builder(context, "id1")
        .setShortLabel("Website")
        .setLongLabel("Open the website")
        .setIcon(IconCompat.createWithResource(context, R.drawable.icon_website))
        .setIntent(Intent(Intent.ACTION_VIEW,
                Uri.parse("https://www.mysite.example.com/")))
        .build()

ShortcutManagerCompat.pushDynamicShortcut(context, shortcut)

Java


ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(context, "id1")
    .setShortLabel("Website")
    .setLongLabel("Open the website")
    .setIcon(IconCompat.createWithResource(context, R.drawable.icon_website))
    .setIntent(new Intent(Intent.ACTION_VIEW,
                   Uri.parse("https://www.mysite.example.com/")))
    .build();

ShortcutManagerCompat.pushDynamicShortcut(context, shortcut);

新增 Google 捷徑整合資料庫

Google 捷徑整合資料庫是選用的 Jetpack 資料庫,可讓您推送可在 Android 介面 (例如啟動器) 和 Google 途徑 (例如 Google 助理) 上顯示的動態捷徑。使用這個程式庫可協助使用者找到捷徑,以便快速存取應用程式中的特定內容或重播動作。

例如,訊息應用程式可能會在使用者傳送訊息給聯絡人後,推送名為「Alex」的動態捷徑。推送動態捷徑後,如果使用者向 Google 助理詢問「Ok Google,在範例應用程式上傳送訊息給 Alex」,Google 助理可以啟動範例應用程式並自動設定,藉此傳送訊息給 Alex。

透過這個程式庫推送的動態捷徑,不受每裝置強制執行的快速鍵限制。這麼做可讓應用程式在每次使用者在應用程式中完成相關動作時推送捷徑。透過這種方式推送常用的捷徑,可讓 Google 瞭解使用者的使用模式,並建議與這些動作相關的捷徑。

舉例來說,Google 助理可從由健身追蹤應用程式推送的捷徑學習,使用者每天早上通常都會執行該捷徑,並在使用者早上拿起手機時主動建議「開始跑步」捷徑。

Google 捷徑整合資料庫本身不提供任何可定址的功能。將此程式庫新增至應用程式後,Google 途徑就能使用 ShortcutManagerCompat 在應用程式推送的捷徑。

如要在應用程式中使用這個程式庫,請按照下列步驟操作:

  1. 更新 gradle.properties 檔案以支援 AndroidX 程式庫

          
          android.useAndroidX=true
          # Automatically convert third-party libraries to use AndroidX
          android.enableJetifier=true
          
          
  2. app/build.gradle 中,新增 Google 捷徑整合資料庫和 ShortcutManagerCompat 的依附元件:

          
          dependencies {
            implementation "androidx.core:core:1.6.0"
            implementation 'androidx.core:core-google-shortcuts:1.0.0'
            ...
          }
          
          

將程式庫依附元件新增至 Android 專案後,應用程式即可使用 ShortcutManagerCompat 中的 pushDynamicShortcut() 方法推送可在啟動器和參與 Google 途徑顯示的動態捷徑。

建立固定捷徑

您可以在 Android 8.0 (API 級別 26) 以上版本中建立固定捷徑。與靜態和動態捷徑不同,固定捷徑會在支援的啟動器中以個別圖示顯示。圖 1 顯示了這兩種捷徑之間的差異。

如要使用應用程式將捷徑固定到支援的啟動器,請完成下列步驟:

  1. 使用 isRequestPinShortcutSupported() 驗證裝置的預設啟動器支援應用程式內的捷徑固定功能。
  2. 視捷徑是否存在而定,透過下列任一方式建立 ShortcutInfo 物件:

    1. 如果捷徑存在,請建立僅包含現有捷徑 ID 的 ShortcutInfo 物件。系統會自動尋找並固定與捷徑相關的所有其他資訊。
    2. 如要固定新捷徑,請建立含有新捷徑 ID、意圖和簡短標籤的 ShortcutInfo 物件。
  3. 呼叫 requestPinShortcut() 將捷徑固定至裝置啟動器。在此程序中,您可以傳入 PendingIntent 物件,只有當捷徑固定成功時,應用程式才會通知應用程式。

    固定捷徑後,應用程式可以透過 updateShortcuts() 方法更新其內容。詳情請參閱「更新捷徑」。

下列程式碼片段說明如何建立固定捷徑。

Kotlin

val shortcutManager = getSystemService(ShortcutManager::class.java)

if (shortcutManager!!.isRequestPinShortcutSupported) {
    // Enable the existing shortcut with the ID "my-shortcut".
    val pinShortcutInfo = ShortcutInfo.Builder(context, "my-shortcut").build()

    // Create the PendingIntent object only if your app needs to be notified
    // that the user let the shortcut be pinned. If the pinning operation fails,
    // your app isn't notified. Assume here that the app implements a method
    // called createShortcutResultIntent() that returns a broadcast intent.
    val pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(pinShortcutInfo)

    // Configure the intent so that your app's broadcast receiver gets the
    // callback successfully. For details, see PendingIntent.getBroadcast().
    val successCallback = PendingIntent.getBroadcast(context, /* request code */ 0,
            pinnedShortcutCallbackIntent, /* flags */ 0)

    shortcutManager.requestPinShortcut(pinShortcutInfo,
            successCallback.intentSender)
}

Java

ShortcutManager shortcutManager =
        context.getSystemService(ShortcutManager.class);

if (shortcutManager.isRequestPinShortcutSupported()) {
    // Enable the existing shortcut with the ID "my-shortcut".
    ShortcutInfo pinShortcutInfo =
            new ShortcutInfo.Builder(context, "my-shortcut").build();

    // Create the PendingIntent object only if your app needs to be notified
    // that the user let the shortcut be pinned. If the pinning operation fails,
    // your app isn't notified. Assume here that the app implements a method
    // called createShortcutResultIntent() that returns a broadcast intent.
    Intent pinnedShortcutCallbackIntent =
            shortcutManager.createShortcutResultIntent(pinShortcutInfo);

    // Configure the intent so that your app's broadcast receiver gets the
    // callback successfully. For details, see PendingIntent.getBroadcast().
    PendingIntent successCallback = PendingIntent.getBroadcast(context, /* request code */ 0,
            pinnedShortcutCallbackIntent, /* flags */ 0);

    shortcutManager.requestPinShortcut(pinShortcutInfo,
            successCallback.getIntentSender());
}

建立自訂捷徑活動

這張圖片顯示自訂對話方塊活動,其中顯示「Do you want to add the Gmail launcher icon to your Home in screen」(您要將 Gmail 啟動器圖示新增到主螢幕嗎?) 的提示中。自訂選項為「不用了,謝謝」和「新增圖示」。
圖 2 自訂應用程式捷徑對話方塊活動範例。

您也可以建立特殊活動,協助使用者建立捷徑、使用自訂選項完成自訂選項和確認按鈕。圖 2 是 Gmail 應用程式中這類活動的範例。

在應用程式的資訊清單檔案中,將 ACTION_CREATE_SHORTCUT 加入活動的 <intent-filter> 元素。這個宣告會在使用者嘗試建立捷徑時設定下列行為:

  1. 系統啟動應用程式的特殊活動。
  2. 使用者設定捷徑的選項。
  3. 使用者選取確認按鈕。
  4. 應用程式會使用 createShortcutResultIntent() 方法建立捷徑。這個方法會傳回 Intent,應用程式使用 setResult() 轉發回先前執行的活動。
  5. 應用程式在用來建立自訂捷徑的活動上呼叫 finish()

同樣地,應用程式也可提示使用者在安裝或首次啟動應用程式後,將固定捷徑新增至主畫面。這個方法很有效,因為可協助使用者在一般工作流程中建立捷徑。

測試快速鍵

如要測試應用程式捷徑,請在裝置 (需具備支援捷徑的啟動器) 上安裝應用程式。然後執行下列動作:

  • 按住應用程式的啟動器圖示即可查看您為應用程式定義的捷徑。
  • 將捷徑拖曳至裝置的啟動器。