如何在Android中以编程方式创建主屏幕URL快捷方式
Android 编程创建主屏幕URL快捷方式实现方案
前置配置
首先在AndroidManifest.xml中添加权限声明:
<!-- 所有版本都需要的快捷方式安装权限,Android 8.0及以上为普通权限,无需动态申请 --> <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
实现逻辑
根据Android系统版本分两种适配方案:
方案1:ShortcutManager实现(适配Android 8.0/API 26及以上,官方推荐方案)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val shortcutManager = getSystemService(ShortcutManager::class.java) // 校验当前桌面Launcher支持固定快捷方式 if (shortcutManager.isRequestPinShortcutSupported) { // 构建点击快捷方式打开URL的Intent val targetUrlIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://你的目标URL")) // 构建快捷方式配置 val shortcutInfo = ShortcutInfo.Builder(this, "自定义唯一快捷方式ID") .setShortLabel("桌面显示的短名称") .setLongLabel("快捷方式完整名称") .setIcon(Icon.createWithResource(this, R.mipmap.你的快捷方式图标资源)) .setIntent(targetUrlIntent) .build() // 发起创建请求,系统会弹出用户确认弹窗,用户同意后自动在桌面生成快捷方式 shortcutManager.requestPinShortcut(shortcutInfo, null) } }
方案2:广播实现(适配Android 7.1/API 25及以下旧版本)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { val installShortcutBroadcast = Intent("com.android.launcher.action.INSTALL_SHORTCUT") // 配置快捷方式点击跳转逻辑 val targetUrlIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://你的目标URL")) installShortcutBroadcast.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetUrlIntent) // 配置快捷方式显示名称 installShortcutBroadcast.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式显示名称") // 配置快捷方式图标 installShortcutBroadcast.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.mipmap.你的快捷方式图标资源)) // 可选配置:禁止重复生成相同快捷方式 installShortcutBroadcast.putExtra("duplicate", false) // 发送广播触发创建 sendBroadcast(installShortcutBroadcast) }
常见问题说明
- 小米、华为等国产定制系统默认会拦截快捷方式创建请求,需要提前引导用户手动开启应用的「创建桌面快捷方式」权限,可跳转至应用权限设置页让用户操作。
- 如需自定义URL打开逻辑(比如用应用内部WebView打开),只需要将上述代码中跳转URL的Intent替换为指向你应用内WebView页面的Intent,携带URL参数即可。
内容的提问来源于stack exchange,提问作者Draško
相关产品推荐
相关产品推荐

