Android添加快捷方式到手机桌面

本文介绍如何在Android应用中创建桌面快捷方式,包括设置关联程序、图标及名称等,并提供了具体的代码实现。此外还讨论了如何避免重复创建以及如何在首次运行时自动创建快捷方式。

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

[size=large]添加快捷方式[/size]
 private void addShortcut(String name) {
// 设置关联程序
Intent launcherIntent = new Intent(this, SplashActivity.class);
launcherIntent.setAction(Intent.ACTION_MAIN);
launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);

Intent addShortcutIntent = new Intent();
addShortcutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
// 不允许重复创建
addShortcutIntent.putExtra("duplicate", false);

// 名字
addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);

// 图标
addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(SplashActivity.this,
R.drawable.icon));
addShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);

// 发送广播
sendBroadcast(addShortcutIntent);
}


[size=medium]不要忘了在manifest中添加权限哦[/size]
<!-- 添加快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<!-- 移除快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
<!-- 查询快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />


[size=medium]这样程序在第一次运行的时候会自动创建快捷方式,以后每次启动的时候会提示已创建快捷方式,这样会觉得很烦,所以我在程序中做了下面的操作:[/size]
 SharedPreferences sharedPraferences = getSharedPreferences("com.rosevision.ofashion", Context.MODE_PRIVATE);
if (sharedPraferences.getInt("addShortcut", 0) == 0) {
addShortcut(getResources().getString(R.string.app_name));
sharedPraferences.edit().putInt("addShortcut",1).apply();
}

[size=medium]这样处理以后,程序只有在每一次运行的时候自动创建快捷方式,以后每次启动的时候会判断是否已经创建了快捷方式,如果没有的话再去创建[/size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值