参考http://viralpatel.net/blogs/android-install-uninstall-shortcut-example/:
Android 为我们提供了一个意图类 com.android.launcher.action.INSTALL_SHORTCUT,它可用于向主屏幕添加快捷方式。在下面的代码 sn-p 中,我们创建了一个名为 HelloWorldShortcut 的活动 MainActivity 的快捷方式。
首先我们需要将权限 INSTALL_SHORTCUT 添加到 android manifest xml。
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
addShortcut() 方法在主屏幕上创建一个新的快捷方式。
private void addShortcut() {
//Adding shortcut for MainActivity
//on Home screen
Intent shortcutIntent = new Intent(getApplicationContext(),
MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent
.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(getApplicationContext(),
R.drawable.ic_launcher));
addIntent
.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
请注意我们如何创建包含目标活动的快捷方式意图对象。此意图对象作为 EXTRA_SHORTCUT_INTENT 添加到另一个意图中。最后我们广播新的意图。这会添加一个名称为的快捷方式
EXTRA_SHORTCUT_NAME 和由 EXTRA_SHORTCUT_ICON_RESOURCE 定义的图标。
注意:这里值得注意的一点是,当您定义从快捷方式调用的活动时,您必须在标签中定义 android:exported=”true” 属性。
从主屏幕卸载快捷方式:
与 Android 中的安装、卸载或删除快捷方式类似,它使用 Intent (UNINSTALL_SHORTCUT) 来执行任务。在下面的代码中,我们删除了添加在主屏幕上的快捷方式。
再次,我们需要执行卸载快捷方式任务的权限。向 Android 清单 xml 添加以下权限。
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
removeShortcut() 方法与 addShortcut() 完全相反。除了 removeShortcut 调用 UNINSTALL_SHORTCUT 意图之外,大部分代码都相似。
private void removeShortcut() {
//Deleting shortcut for MainActivity
//on Home screen
Intent shortcutIntent = new Intent(getApplicationContext(),
MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent
.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "HelloWorldShortcut");
addIntent
.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
你可以试试这个演示HERE