1. 添加权限
首先在AndroidManifest.xml中添加创建快捷方式的权限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
2. 创建快捷方式的方法
fun createShortcut(
context: Context,
shortcutName: String,
iconResId:Int,
targetActivity: Class<*>?
) {
if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
// Android 8.0及以上使用ShortcutManager
val shortcut = ShortcutInfoCompat.Builder(context, "shortcut_$shortcutName")
.setShortLabel(shortcutName)
.setIcon(IconCompat.createWithResource(context, iconResId))
.setIntent(
Intent(context, targetActivity)
.setAction(Intent.ACTION_VIEW)
.putExtra("from_shortcut", true)
).build()
ShortcutManagerCompat.requestPinShortcut(context, shortcut, null)
}else {
// 旧版方法
val shortcutIntent = Intent(context, targetActivity)
shortcutIntent.putExtra("from_shortcut", true)
shortcutIntent.setAction(Intent.ACTION_VIEW)
val addIntent = Intent()
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent)
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName)
addIntent.putExtra(
Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(context, iconResId)
)
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT")
context.sendBroadcast(addIntent)
}
}
3、调用快捷方式
// 在Activity中调用
createShortcut(this, "打开设置", R.drawable.ic_settings, SettingsActivity.class);
4、在目标Activity中处理快捷方式启动
在目标Activity的onCreate方法中检查是否来自快捷方式:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent() != null && getIntent().getBooleanExtra("from_shortcut", false)) {
// 处理来自快捷方式的特殊逻辑
// 例如直接跳转到特定Fragment或显示特定内容
}
// 正常初始化代码...
}
5、检查快捷方式是否已存在(可选)
public static boolean isShortcutExist(Context context, String shortcutName) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// 旧版Android没有官方API检查快捷方式是否存在
return false;
}
ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
if (shortcutManager != null) {
for (ShortcutInfo shortcut : shortcutManager.getPinnedShortcuts()) {
if (shortcut.getShortLabel().equals(shortcutName)) {
return true;
}
}
}
return false;
}
6、 注意事项
- 从Android 8.0 (API 26)开始,Google推荐使用ShortcutManager而不是旧的广播方式
- 某些厂商ROM可能对快捷方式有特殊限制或要求
- 用户可以拒绝创建快捷方式的请求
- 多次调用会创建多个相同的快捷方式(除非特别处理)