如何在Android程序中以编程的方式添加快捷方式到主屏幕

28

我在开发一个安卓应用时遇到了这个问题,现在想分享一下我在开发过程中积累的知识。


1
给标记为重复的版主们:请注意,您的重复问题上的答案并没有完全回答问题。因此,OP决定提出新问题,如建议所示。您会发现他的自我回答包含与重复问题上的被接受答案非常不同的信息。请考虑重新打开问题。 - Richard Le Mesurier
这似乎是一种轻松获得声誉的方式,因为他几乎是在未经授权的情况下复制了一篇旧文章:http://viralpatel.net/blogs/android-install-uninstall-shortcut-example/ - igorsantos07
1个回答

72

Android提供了一个意图类com.android.launcher.action.INSTALL_SHORTCUT,可以用来将快捷方式添加到主屏幕。在下面的代码片段中,我们创建了一个名为HelloWorldShortcut的MainActivity活动的快捷方式。

首先,我们需要在android清单xml中添加INSTALL_SHORTCUT权限。

<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");
    addIntent.putExtra("duplicate", false);  //may it's already there so don't duplicate
    getApplicationContext().sendBroadcast(addIntent);
}

注意如何创建shortcutIntent对象以保存我们的目标活动。将此意图对象作为“EXTRA_SHORTCUT_INTENT”添加到另一个意图中。
最后,我们广播新意图。这将添加一个名为“EXTRA_SHORTCUT_NAME”的快捷方式,并使用“EXTRA_SHORTCUT_ICON_RESOURCE”定义的图标。
还要添加以下代码以避免多个快捷方式:
  if(!getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).getBoolean(Utils.IS_ICON_CREATED, false)){
          addShortcut();
          getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).edit().putBoolean(Utils.IS_ICON_CREATED, true);
      }

8
不起作用(该短语通常表示某个东西或某项任务无法完成或没有达到预期的效果) - David
2
我认为现在Play商店会自动为用户完成这个操作(可以在设置中更改),因此这只会在桌面上生成两个图标。 - Gal Bracha
7
请添加 addIntent.putExtra("duplicate", false),以防止创建多个快捷方式。 - Elshan
11
我认为你需要在末尾加上 .commit() - Jason John
1
什么是utils?我得到了“无法解析符号utils”。 - user3304007
显示剩余13条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接