28

This issue has arisen when I was developing an android application. I thought of sharing the knowledge I gathered during my development.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Chanaka udaya
  • 5,134
  • 4
  • 27
  • 34
  • 1
    to the mods that marked as duplicate: pls note that the answers on your duplicate do not fully address the question. Hence the OP decided to [ask a new question](http://stackoverflow.com/questions/ask), as advised. You will see that his self answer contains very different info to the accepted answer on the duplicate. Pls consider for reopening. – Richard Le Mesurier Nov 17 '13 at 09:35
  • This seems like an easy way to gain reputation as he's almost reproducing an older article without even giving credits:http://viralpatel.net/blogs/android-install-uninstall-shortcu t-example/ – igorsantos07 Sep 10 '14 at 13:48

1 Answers1

72

Android provide us an intent class com.android.launcher.action.INSTALL_SHORTCUT which can be used to add shortcuts to home screen. In following code snippet we create a shortcut of activity MainActivity with the name HelloWorldShortcut.

First we need to add permission INSTALL_SHORTCUT to android manifest xml.

<uses-permission
        android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

The addShortcut() method creates a new shortcut on Home screen.

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);
}

Note how we create shortcutIntent object which holds our target activity. This intent object is added into another intent as EXTRA_SHORTCUT_INTENT.

Finally we broadcast the new intent. This adds a shortcut with name mentioned as EXTRA_SHORTCUT_NAME and icon defined by EXTRA_SHORTCUT_ICON_RESOURCE.

Also put this code to avoid multiple shortcuts :

  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);
      }
SMR
  • 6,628
  • 2
  • 35
  • 56
Chanaka udaya
  • 5,134
  • 4
  • 27
  • 34