以下是 Android 开发中管理应用程序快捷方式的常用指令代码及方法总结,涵盖静态、动态、固定快捷方式等不同场景的实现方式:
一、静态快捷方式
适用场景:功能固定且长期不变的操作(如导航到主页、常用设置)。
实现方法:
1. 配置清单文件:
在 `AndroidManifest.xml` 的主 Activity 中添加 `
xml
android:name="android.app.shortcuts android:resource="@xml/shortcuts" /> 2. 创建 XML 资源文件: 在 `res/xml/shortcuts.xml` 中定义快捷方式属性: xml android:enabled="true android:icon="@drawable/icon android:shortcutShortLabel="@string/short_label android:shortcutLongLabel="@string/long_label"> android:action="android.intent.action.VIEW android:targetPackage="com.example.app android:targetClass="com.example.app.TargetActivity" /> 适用场景:需要根据用户行为或上下文动态更新的功能(如最近浏览、游戏存档)。 实现代码: java if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { ShortcutManager shortcutManager = getSystemService(ShortcutManager.class); ShortcutInfo shortcut = new ShortcutInfo.Builder(context, "dynamic_id") setShortLabel("动态快捷方式") setLongLabel("跳转到动态页面") setIcon(Icon.createWithResource(context, R.drawable.icon)) setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("app://dynamic"))) build; shortcutManager.addDynamicShortcuts(Collections.singletonList(shortcut)); 适用场景:用户主动将特定操作固定到桌面(如常用网址、快捷支付)。 实现代码: java if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ShortcutManager shortcutManager = getSystemService(ShortcutManager.class); if (shortcutManager.isRequestPinShortcutSupported) { ShortcutInfo pinShortcut = new ShortcutInfo.Builder(context, "pin_id") setShortLabel("固定快捷方式") setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("app://pinned"))) build; shortcutManager.requestPinShortcut(pinShortcut, null); 适用场景:兼容 Android 7.1 以下版本,通过发送广播添加快捷方式。 代码示例: java Intent addShortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式"); addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.drawable.icon)); Intent launchIntent = new Intent(context, MainActivity.class); addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent); context.sendBroadcast(addShortcutIntent); 权限声明: xml 1. 数量限制:静态和动态快捷方式最多显示 4 个(不同厂商可能不同),固定快捷方式无限制。 2. 适配问题:部分厂商需额外声明权限(如华为、小米等 Launcher 权限)。 3. 图标规范:建议使用 48x48dp 的透明背景图标。 4. 版本兼容:动态和固定快捷方式需 Android 7.1+,传统广播方式兼容性更好但可能被部分 Launcher 拦截。 | 指令代码 | 功能描述 | ||| | `ShortcutManagerdisableShortcuts` | 禁用指定 ID 的快捷方式 | | `ShortcutManagerremoveDynamicShortcuts` | 删除动态快捷方式 | | `ShortcutManagerupdateShortcuts` | 更新快捷方式属性 | 更多细节可参考 [Android 官方文档]。二、动态快捷方式
三、固定快捷方式
四、传统广播方式(兼容旧版本)
五、注意事项
六、快捷方式管理命令