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