建立捷徑

捷徑協助使用者快速存取應用程式的部分功能,藉此提供特定類型的內容。

至於如何透過捷徑提供內容,則是決於您的用途,以及捷徑的情境是由應用程式驅動還是使用者驅動。雖然靜態捷徑的情境不會改變,而動態捷徑的情境會持續改變,但這兩者的情境都是由應用程式驅動。若是使用者選擇應用程式傳送內容的方式 (例如使用固定捷徑),則是由使用者定義情境。以下列舉每個捷徑類型適用的幾種用途:

  • 靜態捷徑最適用於在使用者與應用程式互動的生命週期內,使用一致的結構連結內容的應用程式。由於大多數的啟動器一次只能顯示四個捷徑,因此靜態捷徑適合用於一般活動。例如,如果使用者希望以特定方式查看日曆或電子郵件,使用靜態捷徑可確保他們執行日常工作時擁有一致的使用體驗。
  • 動態捷徑適用於與情境相關的應用程式動作。系統會根據使用者在應用程式中執行的動作,顯示與情境相關的捷徑。舉例來說,假設您打造的遊戲允許使用者在啟動時從目前的關卡開始遊戲,則您應該經常更新捷徑。使用動態捷徑可在使用者每次過關時更新捷徑。
  • 固定捷徑適用於使用者驅動的特定動作。舉例來說,使用者可能會將特定網站固定到啟動器畫面上。這種做法有助於讓使用者執行自訂動作,例如直接前往該網站,因為這會比使用瀏覽器的預設執行個體更快。

建立靜態捷徑

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

如要建立靜態捷徑,請完成下列步驟:

  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. 在新的資源檔案中新增 <shortcuts> 根元素,其中包含 <shortcut> 元素清單。每個 <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 物件執行作業時所在的捷徑。

注意:您無法將這個屬性的值設為資源字串,例如 @string/foo

android:shortcutShortLabel

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

詳情請參閱 setShortLabel()

注意:這個屬性的值必須為資源字串,例如 @string/shortcut_short_label

android:shortcutLongLabel

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

詳情請參閱 setLongLabel()

注意:這個屬性的值必須為資源字串,例如 @string/shortcut_long_label

android:shortcutDisabledMessage

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

注意:這個屬性的值必須為資源字串,例如 @string/shortcut_disabled_message

android:enabled

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

android:icon

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

注意:捷徑圖示不得包含色調

設定內部元素

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

intent

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

注意:這個 intent 元素不得包含字串資源。

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

categories

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

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

capability-binding

宣告與此捷徑連結的功能

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

建立動態捷徑

動態捷徑提供連結,以指向應用程式內與情境相關的特定動作。這些動作可能在每次使用應用程式時變更,且在應用程式執行時也可變更。動態捷徑的用途實例包括撥號給特定人員、導航到特定地點,以及從使用者的最後儲存點載入遊戲。您也可以使用動態捷徑開啟對話。

ShortcutManagerCompat Jetpack 資料庫是 ShortcutManager API 的輔助工具,可用來管理應用程式中的動態捷徑。使用 ShortcutManagerCompat 資料庫可減少樣板程式碼,並確保捷徑在 Android 各版本上的運作方式保持一致。必須使用這個資料庫才能推送動態捷徑,使捷徑能夠顯示在 Google 助理等 Google 途徑,並搭配 Google 捷徑整合資料庫運作。

ShorcutManagerCompat 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


ShortcutInfo 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,在 ExampleApp 上傳送訊息給 Alex」,Google 助理就會啟動 ExampleApp,並會自動設定傳送訊息給 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'
               ...
             }
    
          
  3. 將資料庫依附元件加進 Android 專案後,應用程式即可使用 ShortcutManagerCompat pushDynamicShortcut() 方法推送動態捷徑,且可在啟動器和參與的 Google 介面顯示。

    注意:建議您使用 pushDynamicShortcut,透過 Google 捷徑整合資料庫推送動態捷徑。您的應用程式可以使用其他方法發布捷徑,但如果捷徑數目達到上限,就可能無法發布。

建立固定捷徑

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

注意:當您嘗試將捷徑固定在支援的啟動器時,使用者會收到確認對話方塊,請他們允許固定捷徑的權限。如果使用者不允許固定捷徑,啟動器就會取消要求。

顯示應用程式捷徑與固定捷徑兩者對比的螢幕截圖
圖 1. 應用程式捷徑和固定捷徑的外觀

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

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

    1. 如果捷徑已存在,請建立僅包含現有捷徑 ID 的 ShortcutInfo 物件。系統會自動尋找並固定其他與捷徑有關的資訊。
    2. 如果您要固定新的捷徑,請建立包含新捷徑 ID、意圖和簡短標籤的 ShortcutInfo 物件。

    注意:由於系統會自動在固定捷徑執行備份與還原,因此這些捷徑的 ID 應包含穩定、固定的字串或伺服器端 ID,而非在本機產生且可能不適用於其他裝置的 ID。

  3. 呼叫 requestPinShortcut() 即可將捷徑固定在裝置啟動器。在此過程中,您可以傳入 PendingIntent 物件;這個物件只會在捷徑成功固定時,向應用程式傳送通知。

    注意:如果使用者不允許將捷徑固定在啟動器中,應用程式就不會收到回呼。

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

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

注意:ShortcutManager 類別的執行個體必須使用 Context.getSystemService(Class) 搭配引數 ShortcutManager.class 或使用 Context.getSystemService(String) 搭配引數, Context.SHORTCUT_SERVICE 取得。

Kotlin

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

if (shortcutManager!!.isRequestPinShortcutSupported) {
    // Assumes there's already a shortcut with the ID "my-shortcut".
    // The shortcut must be enabled.
    val pinShortcutInfo = ShortcutInfo.Builder(context, "my-shortcut").build()

    // Create the PendingIntent object only if your app needs to be notified
    // that the user allowed the shortcut to be pinned. Note that, if the
    // pinning operation fails, your app isn't notified. We assume here that the
    // app has implemented 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()) {
    // Assumes there's already a shortcut with the ID "my-shortcut".
    // The shortcut must be enabled.
    ShortcutInfo pinShortcutInfo =
            new ShortcutInfo.Builder(context, "my-shortcut").build();

    // Create the PendingIntent object only if your app needs to be notified
    // that the user allowed the shortcut to be pinned. Note that, if the
    // pinning operation fails, your app isn't notified. We assume here that the
    // app has implemented 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());
}

注意:請一併查看在 Android 7.1 (API 級別 25) 以下版本運行的支援資料庫 API ( isRequestPinShortcutSupported() requestPinShortcut())。支援資料庫會改回使用已淘汰的 EXTRA_SHORTCUT_INTENT 附加服務,以嘗試固定流程。

建立自訂捷徑活動

自訂對話方塊活動會顯示提示:「要在主螢幕上新增 Gmail 啟動器圖示嗎?」,自訂選項有「不用了,謝謝」和「新增圖示」。
圖 2. 自訂應用程式捷徑對話方塊活動範例

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

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

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

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

測試捷徑

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

  • 長按應用程式的啟動器圖示以查看您為應用程式定義的捷徑。
  • 輕觸並拖曳捷徑,以將其固定至裝置的啟動器。