Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add shortcut to Home screen in android programmatically [duplicate]

Tags:

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

like image 673
Chanaka udaya Avatar asked Jun 01 '13 13:06

Chanaka udaya


People also ask

How do I automatically put apps on my Home screen?

Under the General section of the Settings menu, you will see a check box labeled "Add icon to home screen." Tap on it to tick the box. This will enable downloaded apps to be immediately shown on your home screen.


Video Answer


1 Answers

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);       } 
like image 67
Chanaka udaya Avatar answered Sep 19 '22 13:09

Chanaka udaya