【问题标题】:How can I add homescreen shortcut for app after installing安装后如何为应用程序添加主屏幕快捷方式
【发布时间】:2018-11-12 01:39:24
【问题描述】:

如何在启动应用之前将应用的快捷方式添加到 Android 主屏幕?

我需要在安装应用程序后立即添加它。

【问题讨论】:

  • 您的应用应该已经添加到“应用抽屉”中。并非所有启动器都有“主屏幕”
  • 不要,太讨厌了。

标签: java android shortcut


【解决方案1】:

如果您在安装应用程序自动创建快捷方式后在 Google Play 商店中发布您的应用程序,但如果您想处理 Android 为我们提供了一个意图类 com.android.launcher.action.INSTALL_SHORTCUT,它可用于将快捷方式添加到主屏幕。在下面的代码 sn-p 中,我们创建了一个名为 HelloWorldShortcut 的活动 MainActivity 的快捷方式。

首先,我们需要向 android manifest 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);
}

请注意我们如何创建保存目标活动的快捷方式 Intent 对象。此意图对象作为 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);
      }

【讨论】:

  • 但是这段代码只有在我运行 app 后才会添加快捷方式。但是如何在没有快捷方式的情况下启动我的应用程序?安装后,我在应用列表中找不到它。我只能在“设置”->“应用程序”中找到它。而且没有“运行”按钮。
  • 可能只是从商店安装的应用程序没有直接安装
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2013-08-22
相关资源
最近更新 更多