【问题标题】:How to add shortcut to Home screen in android programmatically [duplicate]如何以编程方式在android中添加主屏幕的快捷方式[重复]
【发布时间】:2013-06-01 13:31:52
【问题描述】:

这个问题是在我开发安卓应用程序时出现的。我想分享我在开发过程中收集到的知识。

【问题讨论】:

  • 对于标记为重复的模组:请注意,您的副本上的答案并不能完全解决问题。因此,按照建议,OP 决定ask a new question。您会看到他的自我回答包含与副本上接受的答案非常不同的信息。请考虑重新开放。
  • 这似乎是一种获得声誉的简单方法,因为他几乎是在复制一篇较旧的文章,甚至没有给出信用:viralpatel.net/blogs/android-install-uninstall-shortcut-example/

标签: android homescreen


【解决方案1】:

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

请注意我们如何创建包含目标活动的快捷方式意图对象。这个意图对象作为EXTRA_SHORTCUT_INTENT 添加到另一个意图中。

最后我们广播了新的意图。这会添加一个名称为的快捷方式 EXTRA_SHORTCUT_NAMEEXTRA_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);
      }

【讨论】:

  • 不要为我工作
  • 我认为现在 Play 商店会自动为用户执行此操作。 (可以在设置中更改)所以这只会在桌面上生成 2 个图标。
  • 添加这个addIntent.putExtra("duplicate", false) 停止创建多个快捷方式
  • 我认为你最后需要一个.commit()
  • 无法解析符号“Utils”我收到此错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多