Android应用创建桌面快捷图标

这篇博客详细介绍了如何在Android应用中声明权限,并实现为用户创建桌面快捷图标的功能,涉及INSTALL_SHORTCUT和UNINSTALL_SHORTCUT权限的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 public static void addShortcut(Activity cx, String name) {
        // TODO: 2017/6/25  创建快捷方式的intent广播
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // TODO: 2017/6/25 添加快捷名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
        //  快捷图标是允许重复
        shortcut.putExtra("duplicate", false);
        // 快捷图标
        Intent.ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(cx, R.mipmap.ic_launcher);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
        // TODO: 2017/6/25 我们下次启动要用的Intent信息
        Intent carryIntent = new Intent(Intent.ACTION_MAIN);
        carryIntent.putExtra("name", name);
        carryIntent.setClassName(cx.getPackageName(),cx.getClass().getName());
        carryIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //添加携带的Intent
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, carryIntent);
        // TODO: 2017/6/25  发送广播
        cx.sendBroadcast(shortcut);
    }

声明权限:
INSTALL_SHORTCUT

UNINSTALL_SHORTCUT

个人公众号“`

### 如何在 Android Studio 中为应用创建桌面快捷方式图标Android 应用开发中,可以通过动态或静态方式为应用创建桌面快捷方式图标。以下是关于如何实现这一功能的详细说明。 #### 动态创建桌面快捷方式 从 Android 7.1(API 级别 25)开始,Android 提供了 `ShortcutManager` API 来动态创建桌面快捷方式。以下是一个简单的代码示例: ```java Intent shortcutIntent = new Intent(context, MainActivity.class); shortcutIntent.setAction(Intent.ACTION_VIEW); // 创建快捷方式对象 ShortcutInfo shortcut = new ShortcutInfo.Builder(context, "shortcut_id") .setShortLabel("快捷方式名称") .setLongLabel("这是快捷方式的详细描述") .setIcon(Icon.createWithResource(context, R.drawable.ic_launcher)) .setIntent(shortcutIntent) .build(); // 请求系统创建快捷方式 context.getSystemService(ShortcutManager.class).requestPinShortcut(shortcut, null); ``` 上述代码片段展示了如何使用 `ShortcutManager` API 创建一个动态快捷方式[^1]。 #### 静态创建桌面快捷方式 如果需要在应用安装时自动创建快捷方式,可以利用 `AndroidManifest.xml` 文件中的 `<intent-filter>` 配置。例如: ```xml <application> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.CREATE_SHORTCUT" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> ``` 通过配置 `CREATE_SHORTCUT` 动作,用户可以在安装后手动添加快捷方式到桌面[^2]。 #### 注意事项 1. **图标路径**:确保快捷方式使用的图标资源存在且路径正确。如果使用自定义 `.png` 文件作为图标,请保证其路径为绝对路径,例如 `/home/yourname/icons/ic_launcher.png`,并避免使用符号链接(如 `~`)[^3]。 2. **权限问题**:某些设备可能要求用户手动确认是否允许创建快捷方式。因此,在调用 `requestPinShortcut` 方法时,应做好异常处理。 3. **兼容性**:动态快捷方式仅支持 Android 7.1 及以上版本。对于更低版本,可以考虑使用 `Intent.ACTION_CREATE_SHORTCUT` 实现类似功能。 #### 示例代码总结 动态快捷方式适用于需要根据用户操作实时生成的情况,而静态快捷方式则适合在应用安装时提供固定入口。开发者可以根据实际需求选择合适的方式实现。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值