Android桌面快捷方式图标生成与删除,使用Intent与launcher交互

本文详细介绍了如何使用Intent来生成和删除Android设备上的应用快捷方式。通过具体代码示例,展示了设置快捷方式名称、图标资源及目标Activity等关键步骤。

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

通过分析Launcher的生成快捷方式的过程,找出了使用Intent发送请求,Launcher通过自己注册的InstallShortCutReceiver和UnInstallShortCutReceiver实现了快捷方式图标的生成与移除过程。本文主要分析外部apk如何使用Intent请求生成快捷方式和移除快捷方式图标的问题。

生成快捷方式代码:

Java代码 收藏代码
  1. privatestaticfinalStringACTION_INSTALL_SHORTCUT=
  2. "com.android.launcher.action.INSTALL_SHORTCUT";
  3. /**
  4. *是否可以有多个快捷方式的副本
  5. */
  6. staticfinalStringEXTRA_SHORTCUT_DUPLICATE="duplicate";
  7. IntentshortcutIntent=newIntent(ACTION_INSTALL_SHORTCUT);
  8. shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
  9. getString(R.string.app_name));
  10. //是否可以有多个快捷方式的副本,参数如果是true就可以生成多个快捷方式,如果是false就不会重复添加
  11. shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE,false);
  12. Intentintent2=newIntent(Intent.ACTION_MAIN);
  13. intent2.addCategory(Intent.CATEGORY_LAUNCHER);
  14. //要删除的应用程序的ComponentName,即应用程序包名+activity的名字
  15. intent2.setComponent(newComponentName(this.getPackageName(),
  16. this.getPackageName()+".Main"));
  17. shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,intent2);
  18. shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
  19. Intent.ShortcutIconResource.fromContext(this,
  20. R.drawable.icon));
  21. sendBroadcast(shortcutIntent);

注:Intent intent2 = new Intent(Intent.ACTION_MAIN); 这个也可以换成的构造参数也可以是Intent.ACTION_CREATE_SHORTCUT,也可以生成快捷方式图标,但是这样不标准,在删除的时候如果不和这个对于相同则无法删除。所以还是用Intent.ACTION_MAIN。

那么删除快捷方式的代码是:

Java代码 收藏代码
  1. privatestaticfinalStringACTION_UNINSTALL_SHORTCUT=
  2. "com.android.launcher.action.UNINSTALL_SHORTCUT";
  3. Intentintent=newIntent(ACTION_UNINSTALL_SHORTCUT);
  4. intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,appName);
  5. //要删除的应用程序的ComponentName,即应用程序包名+activity的名字
  6. ComponentNamecomp=newComponentName(info.activityInfo.packageName,
  7. info.activityInfo.name);
  8. intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,newIntent()
  9. .setComponent(comp).setAction("android.intent.action.MAIN"));
  10. sendBroadcast(intent);
  11. 最后要记得加上权限:
  12. 添加的权限:<uses-permissionandroid:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
  13. 删除的权限:<uses-permissionandroid:name="com.android.launcher.permission.UNINSTALL_SHORTCUT"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值