android 共支持三种快捷方式,
- 静态快捷方式
- 动态快捷方式
- 固定快捷方式
如果要把快捷方式创建到桌面 需要创建固定快捷方式 【官方文档】
代码如下:
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());
}
如果创建的时候报这个错
Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified
修改这行代码
PendingIntent successCallback = PendingIntent.getBroadcast(context, /* request code */ 0,
pinnedShortcutCallbackIntent, /* flags */ 0);
为
PendingIntent successCallback = PendingIntent.getBroadcast(this, /* request code */ 0,
pinnedShortcutCallbackIntent, /* flags */ PendingIntent.FLAG_IMMUTABLE);