Android ShortcutManager 使用指南

Quibbler 1月前 140

Android ShortcutManager 使用指南


       ShortcutManager 是 Android 7.1+ 系统中提供的快捷方式管理工具,允许应用创建和管理三种类型的快捷方式:静态快捷方式、动态快捷方式和固定快捷方式。这些快捷方式可以显著提升用户体验,让用户快速访问应用的核心功能。


1、ShortcutManager 概述


1.1、三种快捷方式类型

       静态快捷方式:在 XML 文件中定义,随 APK 发布,应用更新后才能修改。适用于应用的核心功能,如"新建消息"、"搜索"等。

       动态快捷方式:由应用在运行时通过代码发布,可以动态添加、更新或删除。适用于"最近联系人"、"常用功能"等需要实时更新的场景。

       固定快捷方式:用户手动确认后,"钉"在主屏幕上的图标,类似于桌面图标。用户可以自由添加或删除。


1.2、添加依赖

       ShortcutManager 包含在 AndroidX Core 库中,通常新建项目时已默认包含。在模块级的 build.gradle 文件中加入以下代码:

dependencies {
    // ShortcutManager 包含在 AndroidX Core 库中
    implementation "androidx.core:core:1.15.0"
}


2、静态快捷方式


2.1、创建快捷方式配置文件

       在 res/xml 目录下新建 shortcuts.xml 文件,定义静态快捷方式:

<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
    <shortcut
        android:shortcutId="static_new_message"
        android:enabled="true"
        android:icon="@drawable/ic_new_message"
        android:shortcutShortLabel="@string/new_message_short"
        android:shortcutLongLabel="@string/new_message_long">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example.app"
            android:targetClass="com.example.app.NewMessageActivity" />
        <categories android:name="android.shortcut.conversation" />
    </shortcut>

    <shortcut
        android:shortcutId="static_search"
        android:enabled="true"
        android:icon="@drawable/ic_search"
        android:shortcutShortLabel="@string/search_short"
        android:shortcutLongLabel="@string/search_long">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example.app"
            android:targetClass="com.example.app.SearchActivity" />
        <categories android:name="android.shortcut.search" />
    </shortcut>
</shortcuts>


2.2、在 AndroidManifest 中注册

       在 <activity> 标签内添加 <meta-data> 标签,引用快捷方式配置文件:

<activity
    android:name=".MainActivity"
    android:exported="true">
    <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>


2.3、静态快捷方式属性说明

       shortcutId:快捷方式的唯一标识符 enabled:快捷方式是否启用 icon:快捷方式图标 shortcutShortLabel:简短标签,限制在 10 个字符以内 shortcutLongLabel:长标签,限制在 25 个字符以内 intent:点击快捷方式后跳转的目标 Activity categories:快捷方式分类,用于系统分组


3、动态快捷方式


3.1、创建动态快捷方式

       使用 ShortcutManager 的 setDynamicShortcuts() 方法创建动态快捷方式:

fun createDynamicShortcuts(context: Context) {
    val shortcutManager = context.getSystemService(ShortcutManager::class.java)

    val shortcut = ShortcutInfo.Builder(context, "dynamic_recent_contact")
        .setShortLabel("张三")
        .setLongLabel("联系张三")
        .setIcon(Icon.createWithResource(context, R.drawable.ic_contact))
        .setIntent(
            Intent(context, ChatActivity::class.java).apply {
                action = Intent.ACTION_VIEW
                putExtra("contact_id", "123")
            }
        )
        .build()

    shortcutManager?.setDynamicShortcuts(listOf(shortcut))
}


3.2、更新动态快捷方式

       使用 updateShortcuts() 方法更新已存在的动态快捷方式:

fun updateDynamicShortcut(context: Context) {
    val shortcutManager = context.getSystemService(ShortcutManager::class.java)

    val updatedShortcut = ShortcutInfo.Builder(context, "dynamic_recent_contact")
        .setShortLabel("李四")
        .setLongLabel("联系李四")
        .setIcon(Icon.createWithResource(context, R.drawable.ic_contact))
        .setIntent(
            Intent(context, ChatActivity::class.java).apply {
                action = Intent.ACTION_VIEW
                putExtra("contact_id", "456")
            }
        )
        .build()

    shortcutManager?.updateShortcuts(listOf(updatedShortcut))
}


3.3、删除动态快捷方式

       使用 removeDynamicShortcuts() 方法删除动态快捷方式:

fun removeDynamicShortcut(context: Context) {
    val shortcutManager = context.getSystemService(ShortcutManager::class.java)
    shortcutManager?.removeDynamicShortcuts(listOf("dynamic_recent_contact"))
}


3.4、获取动态快捷方式列表

       使用 getDynamicShortcuts() 方法获取当前所有动态快捷方式:

fun getDynamicShortcuts(context: Context): List<ShortcutInfo> {
    val shortcutManager = context.getSystemService(ShortcutManager::class.java)
    return shortcutManager?.dynamicShortcuts ?: emptyList()
}


3.5、动态快捷方式数量限制

       动态快捷方式有数量限制,不同 Android 版本限制不同:

  • Android 8.0+:最多 5 个

  • Android 7.1:最多 4 个

       可以使用 getMaxDynamicShortcutCount() 方法获取当前设备的最大数量:

fun getMaxDynamicShortcutCount(context: Context): Int {
    val shortcutManager = context.getSystemService(ShortcutManager::class.java)
    return shortcutManager?.maxDynamicShortcutCount ?: 0
}


4、固定快捷方式


4.1、创建固定快捷方式

       使用 requestPinShortcut() 方法创建固定快捷方式,需要用户手动确认:

fun createPinnedShortcut(context: Context) {
    val shortcutManager = context.getSystemService(ShortcutManager::class.java)

    if (shortcutManager?.isRequestPinShortcutSupported == true) {
        val shortcut = ShortcutInfo.Builder(context, "pinned_favorite")
            .setShortLabel("收藏")
            .setLongLabel("我的收藏")
            .setIcon(Icon.createWithResource(context, R.drawable.ic_favorite))
            .setIntent(
                Intent(context, FavoriteActivity::class.java).apply {
                    action = Intent.ACTION_VIEW
                }
            )
            .build()

        val pinnedShortcutCallbackIntent = shortcutManager.createShortcutResultIntent(shortcut)

        val successReceiver = PendingIntent.getBroadcast(
            context,
            0,
            pinnedShortcutCallbackIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        shortcutManager.requestPinShortcut(shortcut, successReceiver.intentSender)
    }
}


4.2、监听固定快捷方式结果

       创建 BroadcastReceiver 监听固定快捷方式的结果:

class PinnedShortcutReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.hasExtra(ShortcutManager.EXTRA_SHORTCUT_ID)) {
            val shortcutId = intent.getStringExtra(ShortcutManager.EXTRA_SHORTCUT_ID)
            if (shortcutId == "pinned_favorite") {
                Toast.makeText(context, "快捷方式已固定到主屏幕", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

       在 AndroidManifest 中注册 Receiver:

<receiver
    android:name=".PinnedShortcutReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.content.action.SHORTCUT_ADDED" />
    </intent-filter>
</receiver>


4.3、检查固定快捷方式支持

       在创建固定快捷方式之前,需要检查设备是否支持:

fun isPinnedShortcutSupported(context: Context): Boolean {
    val shortcutManager = context.getSystemService(ShortcutManager::class.java)
    return shortcutManager?.isRequestPinShortcutSupported == true
}


       ShortcutManager 提供了三种快捷方式类型,分别适用于不同的使用场景:

       静态快捷方式:适合应用的核心功能,随 APK 发布 动态快捷方式:适合需要实时更新的功能,如最近联系人 固定快捷方式:适合用户常用的功能,需要用户手动确认

       合理使用快捷方式可以显著提升用户体验,让用户更快速地访问应用的核心功能。在实际开发中,应该根据应用的特点和用户需求,选择合适的快捷方式类型。


不忘初心的阿甘
最新回复 (0)
    • AI笔记本-欢迎来到 AI 驱动博客时代 🚀
      2
        登录 注册 QQ
返回
仅供学习交流,切勿用于商业用途。如有错误欢迎指出:fluent0418@gmail.com