Android 添加快捷方式指南
在 Android 系统中,可以通过多种方式创建桌面快捷方式,包括静态快捷方式(Static Shortcuts)、动态快捷方式(Dynamic Shortcuts)以及 Pinned Shortcuts(固定快捷方式)。下面详细介绍每种方式的实现方法和使用场景。
1、静态快捷方式(Static Shortcuts)
适用于固定的功能入口,比如 App 的主要页面跳转。
1.1、定义快捷方式(XML配置)
在 res/xml/shortcuts.xml 文件中声明快捷方式:
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 定义一个打开搜索功能的快捷方式 -->
<shortcut
android:shortcutId="search"
android:enabled="true"
android:icon="@drawable/search_icon"
android:shortcutShortLabel="@string/search_short_label"
android:shortcutLongLabel="@string/search_long_label"
android:disabledMessage="@string/search_disabled_msg">
<!-- Intent 指向目标 Activity -->
<intent
android:action="android.intent.action.VIEW"
android:targetPackage="com.example.myapp"
android:targetClass="com.example.myapp.SearchActivity"/>
<!-- 可选分类标签 -->
<categories android:name="android.shortcut.conversation"/>
</shortcut>
</shortcuts>
1.2、在 Manifest 中引用快捷方式
在 <activity> 节点下关联 XML 文件:
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts"/>
这样安装 App 后,长按图标即可看到定义的快捷方式列表。
2、动态快捷方式(Dynamic Shortcuts)
运行时动态更新快捷方式,适合个性化推荐等功能。
2.1、获取 ShortcutManager
val shortcutManager = getSystemService(Context.SHORTCUT_SERVICE) as ShortcutManager
2.2、添加动态快捷方式
// 创建一个新快捷方式
val dynamicShortcut = ShortcutInfo.Builder(context, "dynamic_search")
.setShortLabel("Search Now!")
.setIcon(Icon.createWithResource(this, R.drawable.search))
.setIntent(
Intent(Intent.ACTION_MAIN).apply {
setClassName(packageName, "${packageName}.SearchActivity")
}
)
.build()
// 添加到当前快捷方式列表
shortcutManager.dynamicShortcuts += listOf(dynamicShortcut)
2.3、移除动态快捷方式
shortcutManager.removeDynamicShortcuts(listOf("dynamic_search"))
3、固定快捷方式(Pinned Shortcuts)
允许用户在桌面上直接放置一个独立的快捷方式图标。
3.1、判断设备是否支持 Pin Shortcut
if (shortcutManager.isRequestPinShortcutSupported) {
// 可以创建固定快捷方式
}
3.2、创建并固定快捷方式
val pinShortcut = ShortcutInfo.Builder(context, "pin_chat")
.setShortLabel("Chat Directly")
.setIcon(Icon.createWithResource(this, R.drawable.chat))
.setIntent(
Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse("https://example.com/chat")
}
)
.build()
// 发送 PIN 请求
shortcutManager.requestPinShortcut(
pinShortcut,
null // Optional: PendingIntent for success callback
) 此时会弹出确认对话框,用户点击确定后会在桌面创建独立图标。
3.3、取消固定快捷方式
只能由用户手动删除(无法程序化移除)。
4、总结对比
类型 适用场景 能否动态更新 是否需要权限
静态快捷方式 常用固定功能入口 ❌ No ✅ Yes
动态快捷方式 个性化推荐、临时入口 ✔️ Yes ✅ Yes
固定快捷方式 长期使用的快速访问 ❌ No* ⚠️ Depends
注:固定快捷方式一旦创建,除非用户手动删除,否则无法自动撤销。
这份指南能帮助开发灵活运用 Android 快捷方式!