如何以编程方式在android中添加主屏幕快捷方式

Cha*_*aya 24 android homescreen

我在开发Android应用程序时出现了这个问题.我想到分享我在开发过程中收集到的知识.

Cha*_*aya 69

Android为我们提供了一个intent类com.android.launcher.action.INSTALL_SHORTCUT,可用于向主屏幕添加快捷方式.在下面的代码片段中,我们使用名称HelloWorldShortcut创建活动MainActivity的快捷方式.

首先我们需要为INSTALL_SHORTCUTandroid manifest xml 添加权限.

<uses-permission
        android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

请注意我们如何创建保存目标活动的shortcutIntent对象.此意图对象被添加到另一个意图中EXTRA_SHORTCUT_INTENT.

最后,我们广播新的意图.这会添加一个快捷方式,名称为 EXTRA_SHORTCUT_NAMEand和icon定义的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);
      }
Run Code Online (Sandbox Code Playgroud)

  • 不要为我工作 (7认同)
  • 添加这个`addIntent.putExtra("duplicate",false)`停止创建多个快捷方式 (7认同)
  • 我认为你最后需要一个`.commit()` (7认同)
  • 我认为现在Play商店会自动为用户执行此操作.(可以在设置中更改)因此这只会在桌面上生成2个图标. (2认同)