How to create shortcut for your application in the Desktop in Android?

By | April 7, 2012

Shortcuts are really useful feature in android. This example also explains how to create shortcut for your app in the desktop of your android phone.

This is the complete code of an application which creates a shortcut of this app in the homescreen.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;

public class ShortCutDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent shortcutIntent;
        shortcutIntent = new Intent();
        shortcutIntent.setComponent(new ComponentName(
                getApplicationContext().getPackageName(), ".classname"));

        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        final Intent putShortCutIntent = new Intent();
        putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
                shortcutIntent);

        // Sets the custom shortcut's title
        putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,  "My Icon");
        putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(
        		ShortCutDemo.this, R.drawable.icon));
        putShortCutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
     	sendBroadcast(putShortCutIntent);
    }
}

Note : You need to add permission for this to work.

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

Now the AndroidManifest looks like this.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ShortCutDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
        </activity>

    </application>
</manifest>