创建快捷方式

快捷方式可帮助用户快速访问应用的某些部分,从而为用户提供特定类型的内容。

对比应用快捷方式与固定快捷方式的图片
图 1. 应用快捷方式和固定快捷方式。

如何使用快捷方式传送内容取决于您的用例以及快捷方式的上下文是由应用驱动还是由用户驱动。虽然静态快捷方式的上下文不会改变,动态快捷方式的上下文会不断变化,但您的应用在这两种情况下都会驱动上下文。如果用户选择您的应用向其传送内容的方式(例如通过固定快捷方式),则上下文由用户定义。以下场景介绍了每种快捷方式类型的一些用例:

  • 静态快捷方式 最适合在用户与应用互动的整个生命周期内使用一致结构链接到内容的应用。由于大多数启动器一次仅显示四个快捷方式,因此静态快捷方式有助于以一致的方式执行日常任务,例如当用户希望以特定方式查看日历或电子邮件时。
  • 动态快捷方式用于应用中与上下文相关的操作。上下文相关快捷方式是针对用户在应用中执行的操作而定制的。例如,如果您构建的游戏允许用户在启动时从当前关卡开始,您需要经常更新该快捷方式。借助动态快捷方式,您可以在用户每次过关时更新快捷方式。
  • 固定快捷方式用于用户驱动的特定操作。例如,用户可能需要将特定网站固定到启动器。这种做法非常有用,因为与使用浏览器的默认实例相比,用户可更快地执行自定义操作,例如一步导航到网站。

创建静态快捷方式

静态快捷方式提供指向应用内常规操作的链接,这些操作必须在应用的当前版本的生命周期内保持一致。对于静态快捷方式,一些不错的选择包括查看已发邮件、设置闹钟以及显示用户当天的锻炼活动。

如需创建静态快捷方式,请执行以下操作:

  1. 在应用的 AndroidManifest.xml 文件中,找到 intent 过滤器设置为 android.intent.action.MAIN 操作和 android.intent.category.LAUNCHER 类别的 activity。

  2. 向此 Activity 添加 <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> 元素中,添加静态快捷方式的相关信息,包括其图标、说明标签及其在应用中启动的 intent:

      <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

系统在用户选择快捷方式时启动的操作。 此 intent 必须为 android:action 属性提供一个值。

您可以为一个快捷方式提供多个 intent。如需了解详情,请参阅管理多个 intent 和 activity设置 intentTaskStackBuilder 类参考文档。

categories

为应用快捷方式执行的操作类型(例如创建新的聊天消息)提供分组。

如需查看支持的快捷方式类别的列表,请参阅 ShortcutInfo 类参考文档。

capability-binding

声明与该快捷方式关联的功能

在前面的示例中,快捷方式与为 CREATE_MESSAGE 声明的功能相关联,后者是与应用有关的 Action 内置 intent。此功能绑定可让用户通过语音指令与 Google 助理调用快捷方式。

创建动态快捷方式

动态快捷方式提供指向应用内特定上下文相关操作的链接。这些操作可能会在应用的不同使用情况以及应用运行时发生变化。动态快捷方式的良好用途包括致电特定人员、导航到特定位置,以及从用户的上一个存档点加载游戏。您也可以使用动态快捷方式打开对话。

ShortcutManagerCompatJetpack 库是 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 surface(例如启动器)和 Google surface(例如 Google 助理)上显示的动态快捷方式。使用此库有助于用户发现您的快捷方式,以便快速访问应用中的特定内容或重放操作。

例如,即时通讯应用可能会在用户给名为“Alex”的联系人发送消息后,推送该联系人的动态快捷方式。推送动态快捷方式后,如果用户对 Google 助理说“Hey Google,在 ExampleApp 上给 Alex 发消息”,Google 助理就可以启动 ExampleApp 并自动将其配置为向 Alex 发送消息。

使用此库推送的动态快捷方式不受针对每台设备强制执行的快捷方式限制的约束。这样一来,每当用户在您的应用中完成一项关联操作时,您的应用都会推送快捷方式。通过这种方式推送常用快捷方式可让 Google 了解用户的使用模式,并向他们推荐与上下文相关的快捷方式。

例如,Google 助理可以从健身跟踪应用推送的快捷方式中学习,用户通常每天早上都会运行快捷方式,并在用户早上拿起手机时主动推荐“开始跑步”快捷方式。

Google 快捷方式集成库本身不提供任何可寻址功能。将此库添加到您的应用后,Google surface 就会采用您的应用使用 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 surface 上显示的动态快捷方式。

创建固定快捷方式

在 Android 8.0(API 级别 26)及更高版本中,您可以创建固定快捷方式。与静态和动态快捷方式不同,固定快捷方式在受支持的启动器中显示为单独的图标。图 1 显示了这两种快捷方式之间的区别。

如需将快捷方式固定到使用您的应用的受支持启动器上,请完成以下步骤:

  1. 使用 isRequestPinShortcutSupported() 验证设备的默认启动器是否支持应用内固定快捷方式。
  2. 通过以下两种方式之一创建 ShortcutInfo 对象,具体取决于快捷方式是否存在:

    1. 如果快捷方式存在,请创建仅包含现有快捷方式 ID 的 ShortcutInfo 对象。系统会自动查找与该快捷方式相关的所有其他信息,并将其固定。
    2. 如果您要固定新的快捷方式,请创建包含新快捷方式的 ID、intent 和简短标签的 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());
}

创建自定义快捷方式 Activity

一张图片,显示自定义对话框 Activity 以及“您想将 Gmail 启动器图标添加到主屏幕吗?”提示。自定义选项为“不用了”和“添加图标”。
图 2. 示例:自定义应用快捷方式对话框 activity。

您还可以创建一个专门的 activity 来帮助用户创建快捷方式,并使用自定义选项和确认按钮来完成。图 2 显示了 Gmail 应用中此类 activity 的示例。

在应用的清单文件中,将 ACTION_CREATE_SHORTCUT 添加到 activity 的 <intent-filter> 元素中。当用户尝试创建快捷方式时,此声明会设置以下行为:

  1. 系统启动应用的专用 Activity。
  2. 用户为快捷方式设置选项。
  3. 用户选择确认按钮。
  4. 您的应用使用 createShortcutResultIntent() 方法创建该快捷方式。此方法会返回一个 Intent,您的应用会使用 setResult() 将其中继回先前执行的 activity。
  5. 您的应用会对用于创建自定义快捷方式的 activity 调用 finish()

同样,您的应用可以在安装后或首次启动时提示用户向主屏幕添加固定快捷方式。此方法非常有效,因为它可以帮助用户在日常工作流中创建快捷方式。

测试快捷方式

如需测试应用的快捷方式,请在具有支持快捷方式的启动器的设备上安装应用。然后,执行以下操作:

  • 轻触并按住应用的启动器图标,即可查看您为应用定义的快捷方式。
  • 拖动快捷方式,将其固定到设备的启动器。