How to add shortcut to Home screen in Android programmatically

3 comments on How to add shortcut to Home screen in Android programmatically

Written by

in

I improved a little bit a solution that was found in StackOverflow. Now program saves in preferences whether a shortcut was already added and doesn’t add it in new launches of an app if user deleted it. This also saves a little bit time, since the code to add an existing shortcut doesn’t run anymore.

final static public String PREFS_NAME = "PREFS_NAME";
final static private String PREF_KEY_SHORTCUT_ADDED = "PREF_KEY_SHORTCUT_ADDED";


// Creates shortcut on Android widget screen
private void createShortcutIcon(){

    // Checking if ShortCut was already added
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    boolean shortCutWasAlreadyAdded = sharedPreferences.getBoolean(PREF_KEY_SHORTCUT_ADDED, false);
    if (shortCutWasAlreadyAdded) return;

    Intent shortcutIntent = new Intent(getApplicationContext(), IntroActivity.class);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    Intent addIntent = new Intent();
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "YourAppName");
    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.ic_launcher));
    addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    getApplicationContext().sendBroadcast(addIntent);

    // Remembering that ShortCut was already added
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(PREF_KEY_SHORTCUT_ADDED, true);
    editor.commit();
}

In Android Manifest:


Comments

3 responses to “How to add shortcut to Home screen in Android programmatically”

  1. Jonnie Avatar

    I see you share interesting things here, you can earn some
    additional money, your website has huge potential, for the monetizing method, just
    search in google – K2 advices how to monetize a website

  2. Bridgett Avatar

    I read a lot of interesting content here. Probably you spend
    a lot of time writing, i know how to save you a lot of work,
    there is an online tool that creates unique, google friendly
    articles in minutes, just search in google – laranitas free content source

  3. Timilehin Ajiboye Avatar
    Timilehin Ajiboye

    Does this work the exact same way “Add To Homescreen” works in Chrome for Progressive Web Apps?

Leave a Reply

Your email address will not be published. Required fields are marked *