61

What I want to do is:

1) I'm inside an activity, there are 2 buttons. If I click the first one a shortcut is created in my home screen. The shortcut open an html page that has been previously downloaded, so I want it to use the default browser but I don't want to use internet cause I already have the page.

2)The second button create another shortcut that starts an activity. And i want to pass to the activity some extra arguments (As strings for example)...........

Are those things possible? I found some link and some similar questions like Android: Is there a programming way to create a web shortcut on home screen

They seem to be the answer to my question but someone told me that this code is not gonna work on all devices and that is deprecated and that what i want to do is not possible.......

This technique is not recommended. This is an internal implementation, not part of the Android SDK. It will not work on all home screen implementations. It may not work on all past versions of Android. It may not work in future versions of Android, as Google is not obligated to maintain internal undocumented interfaces. Please do not use this

What means internal implementation? Is that code trustable or not.....help me pls.....

Community
  • 1
  • 1
Sgotenks
  • 1,723
  • 4
  • 20
  • 34
  • 6
    You should accept a few answers. People will be more inclined to assist you. – ahodder Jun 13 '11 at 23:24
  • 1
    Looks like it's not allowed anymore : "Apps and their ads must not modify or add browser settings or bookmarks, add homescreen shortcuts, or icons on the user’s device as a service to third parties or for advertising purposes. " but I am not sure, because of the last sentence. (from the new policy: http://play.google.com/intl/en/about/developer-content-policy.html) – Samuel Mar 31 '14 at 07:27

10 Answers10

86

The example code uses undocumented interfaces (permission and intent) to install a shortcut. As "someone" told you, this may not work on all phones, and may break in future Android releases. Don't do it.

The correct way is to listen for a shortcut request from the home screen-- with an intent filter like so in your manifest:

<activity android:name=".ShortCutActivity" android:label="@string/shortcut_label">
  <intent-filter>
    <action android:name="android.intent.action.CREATE_SHORTCUT" />
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>

Then in the activity that receives the intent, you create an intent for your shortcut and return it as the activity result.

// create shortcut if requested
ShortcutIconResource icon =
    Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);

Intent intent = new Intent();

Intent launchIntent = new Intent(this,ActivityToLaunch.class);

intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, someNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

setResult(RESULT_OK, intent);
legoscia
  • 39,593
  • 22
  • 116
  • 167
antlersoft
  • 14,636
  • 4
  • 35
  • 55
  • 1
    permission and intent are undocumented? What you mean, there is a lot about intent in the documentation,and you are yousing intent too,what's teh difference? amyway, tnx a lot, just one thing let's say that my application is called "Myapplication" i have to add permission in its manifest and the second part in the activity showing the 2 buttons to create shortcuts....but what you mean wirh "The correct way is to listen for a shortcut request from the home screen-- with an intent filter like so in your manifest:" How and when the home screen is asking for a shortcuts? My application does..... – Sgotenks Jun 14 '11 at 00:11
  • 5
    @user280560 -- All applications will use permissions and intents; it's just that some permissions and intents are undocumented-- Android uses them for its internal implementation (since the source code is public, it's easy to find these), but you shouldn't in a third-part app-- because since they are undocumented they may change without notice. – antlersoft Jun 14 '11 at 13:41
  • 1
    i tried your code,it doesn't do what i want,instead the one in the link i posted does........This is what your code does: if i long press on the home screen and i select shortcuts, my MARKET is shown in the list, and if i select it an intent is thrown (but no shortcuts are created on the desktop). What i want is that when i'm inside my Market and i click on a button, a shortcut with an icon is added in the homescreen..addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); this.sendBroadcast(addIntent); these 2 lines makes the diffrence what's wronk and evil with them? – Sgotenks Jun 14 '11 at 14:01
  • 2
    nothing's wrong and evil. He's just saying that this interface may change and then your app will not work anymore. – DallaRosa Aug 10 '11 at 10:49
  • 5
    You can check if the device is able to handle the shortcut creation using this snippet: if(getPackageManager().queryBroadcastReceivers(new Intent(INSTALL_SHORTCUT_ACTION), 0).size() > 0) – Fernando Gallego Aug 20 '12 at 15:10
  • antlersoft solution doesn't work for me. Does this still work ? – toto_tata Jun 20 '13 at 16:34
  • How to create at Installtion time? – Pratik Butani Oct 26 '13 at 11:59
  • 1
    Don't forget to specify `android:exported="true"` for `ActivityToLaunch` in your manifest so that the activity can be accessed through the shortcut. – Sam Jan 31 '15 at 23:41
  • How can you remove such created icon ? I mean for the Activity which only has: – Adam Styrc Jun 09 '15 at 11:19
  • It's documented, see for example: SDK_DIR/samples/android-22/legacy/ApiDemos/src/com/example/android/apis/app/LauncherShortcuts.java – aleb Jul 21 '15 at 20:57
  • 1
    https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/app/LauncherShortcuts.java – aleb Jul 21 '15 at 21:15
  • This shortcut activity is not getting called by launcher can anyone help me on how to call this from my activity to home launcher? – Manikanta Mar 21 '17 at 11:31
  • @antlersoft How to make this ShortCutActivity called? Does my app still need to call ShortcutManagerCompat.requestPinShortcut? – tuantv.dev Jul 04 '23 at 07:20
  • I tested on Android 13, after added these codes, long-click on app icon in App screen > shown Widgets > click Widgets > choose Add > shown the ShortCutActivity > added shortcut. This is not expected because I need to show ShortCutActivity without user's actions – tuantv.dev Jul 04 '23 at 07:31
68

I have developed one method below for creating the shortcut icon on android Homescreen [Tested on my own app]. Just call it.

private void ShortcutIcon(){

    Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.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, "Test");
    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);
}

Don't forget to change your activity name, icon resource & permission.

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

Happy coding !!!

Edit:

For Duplicate Issue, First Option is to add below line in the code otherwise it creates new one every time.

addIntent.putExtra("duplicate", false);

Second Option is to First uninstall The App Shortcut Icon and then Install It Again If the First Option Didn't Work.

Jamil
  • 5,457
  • 4
  • 26
  • 29
Siddiq Abu Bakkar
  • 1,949
  • 1
  • 13
  • 24
21

The com.android.launcher.action.INSTALL_SHORTCUT broadcast no longer has any effect since android oreo. LINK

If you want to support all android versions, especially android 8.0 or oreo and newer, use the code below to create shortcut:

public static void addShortcutToHomeScreen(Context context)
{
    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context))
    {
        ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(context, "#1")
                .setIntent(new Intent(context, YourActivity.class).setAction(Intent.ACTION_MAIN)) // !!! intent's action must be set on oreo
                .setShortLabel("Test")
                .setIcon(IconCompat.createWithResource(context, R.drawable.ic_launcher))
                .build();
        ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null);
    }
    else
    {
        // Shortcut is not supported by your launcher
    }
}

Add permission in manifest file:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
Run
  • 2,148
  • 2
  • 12
  • 29
  • 1
    @FunGapApp you need to add the permission for this to work on android < 8.0: `` – Dominik Weber Aug 24 '18 at 22:33
  • 1
    Thanks, it worked (my device has API 27). Is it possible to add the shortcut without having to confirm the "Add to Home screen" window? While this may be default behavior for apps on Google Store, my app is private. – Erlend K.H. Jan 27 '19 at 09:02
11

Starting from Android O, this is the way to create a shortcut:

if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
    final ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);

    ShortcutInfo pinShortcutInfo = new ShortcutInfo.Builder(context, shortcutId)
            .setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher))
            .setShortLabel(label)
            .setIntent(new Intent(context, MainActivity.class).setAction(Intent.ACTION_MAIN))
            .build();
    shortcutManager.requestPinShortcut(pinShortcutInfo, null);
}

It has a lot of limitations, sadly:

  1. Requires the user to accept adding it.
  2. Can't be added/removed in the background.
  3. Won't be removed if the targeted app is removed. Only the one which created it.
  4. Can't create the icon based on a resource of the targeted app, except if it's of the current app. You can do it from a bitmap though.

For pre-Android O, you can use ShortcutManagerCompat to create new shortcuts too, without any of those limitations.

Minas Mina
  • 2,058
  • 3
  • 21
  • 35
android developer
  • 114,585
  • 152
  • 739
  • 1,270
8

I improved a little bit a solution above. Now it 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();
}
Denis Kutlubaev
  • 15,320
  • 6
  • 84
  • 70
  • Will it add a shortcut before opening the application. How this code will run without opening an activity from a just installed application. – Suresh Sharma Oct 28 '14 at 09:22
  • Using shared preferences seems to be the perfect way to go. The other attempts to **uninstall** and **reinstall** or **adding an extra with "duplicate, false"** don't work on most devices. – Dut A. Feb 17 '15 at 20:39
3

@Siddiq Abu Bakkar Answer works. But in order to prevent creating shortcut every time app launches use shared Preferences.

final String PREF_FIRST_START = "AppFirstLaunch";
 SharedPreferences settings = getSharedPreferences(PREF_FIRST_START, 0);
    if(settings.getBoolean("AppFirstLaunch", true)){

        // record the fact that the app has been started at least once
        settings.edit().putBoolean("AppFirstLaunch", false).commit();
        ShortcutIcon();

    }
Krishnadas PC
  • 5,981
  • 2
  • 53
  • 54
3

Since API level 26, using com.android.launcher.action.INSTALL_SHORTCUT is deprecated. The new way of creating shortcuts are using ShortcutManager.

It mentions that there are 3 kinds of shortcuts, static, dynamic and pinned. Based on your requirements, you can choose to create them.

0xC0DED00D
  • 19,522
  • 20
  • 117
  • 184
  • The Android O is not official yet (correct me if i'm wrong AND "official" means the official stable release). By now the use of Intents is OK –  Aug 30 '17 at 00:34
  • @CodigosTutoriales The SDK is available in a stable release already and phones are going to come preloaded with Oreo release soon. It's a good practice to always have your apps targeted and compiled with latest API level available. This answer is for someone who doesn't want to see deprecation warning in their code. – 0xC0DED00D Aug 30 '17 at 06:05
2

To add a shortcut to the home screen use this code.

public void addShortcutToHomeScreen(Context context) {
        if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
            ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(context, "#1")
                    .setIntent(new Intent(context, MainActivity.class).setAction(Intent.ACTION_MAIN)) // !!! intent's action must be set on oreo
                    .setShortLabel("Label Goes Here")
                    .setIcon(IconCompat.createWithResource(context, R.mipmap.ic_launcher_shortcut))
                    .build();
            ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null);
        } else {
            Toast.makeText(context, R.string.no_shortcut, Toast.LENGTH_SHORT).show();
        }
    }

and no extra permission need !!!

Kundan Singh
  • 91
  • 1
  • 6
1
final Intent shortcutIntent = new Intent(this, SomeActivity.class);

final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
// Sets the custom shortcut's title
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
// Set the custom shortcut icon
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
// add the shortcut
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(intent);
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
1
public static void addShortcutToHomeScreen(Context context)
{
    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context))
    {
        ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(context, "#1")
                .setIntent(new Intent(context, YourActivity.class).setAction(Intent.ACTION_MAIN)) // !!! intent's action must be set on oreo
                .setShortLabel("Test")
                .setIcon(IconCompat.createWithResource(context, R.drawable.ic_launcher))
                .build();
        ShortcutManagerCompat.requestPinShortcut(context, shortcutInfo, null);
    }
    else
    {
        // Shortcut is not supported by your launcher
    }
}

I've used it, but some devices on the home screen adds 2 icons. I did not understand??

selçuk doğan
  • 406
  • 4
  • 12