限制
从Android 7.1 开始支持
快捷方式类型
静态
以xml形式配置,并在主Activity中的
<meta-data>
标签下置顶Android Studio并不能很好的支持,暂时没找到问题所在
动态
可以随时改变,即使是程序运行过程中
固定
固定到屏幕底部的快捷启动栏中(对于国内很多手机来说,并不是底部,而是多了一个icon入口而已,一般会弹出一个框,请求添加快捷方式)
动态
ShortcutManager
支持以下几种操作:
Publish
- 重新定义快捷方式入口 :
setDynamicShortcuts()
- 添加新的入口 :
addDynamicShortcuts()
- 重新定义快捷方式入口 :
Update
updateShortcuts()
Remove
- 移除部分:
removeDynamicShortcuts()
- 移除全部:
removeAllDynamicShortcuts()
- 移除部分:
val shortcutManager = getSystemService<ShortcutManager>(ShortcutManager::class.java)
val shortcut = ShortcutInfo.Builder(context, "id1")
.setShortLabel("Website")
.setLongLabel("Open the website")
.setIcon(Icon.createWithResource(context, R.drawable.icon_website))
.setIntent(Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.mysite.example.com/")))
.build()
shortcutManager!!.dynamicShortcuts = Arrays.asList(shortcut)
不过一般还是使用ShortcutManagerCompat
等兼容类.
固定
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)
}
使用固定快捷方式的时候,一定要注意返回的Intent,这样返回的时候可以直接返回首页了.