6

Below is My code to create a shortcut to a selected application. I have really no problem and the application work quite well.

The problem is that I am able to create a shortcut with a ressource from my application:

    intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));

But I really would like with a custom drawable. ( Drawable myDrawable=.....)

How can I do?

   ResolveInfo launchable=adapter.getItem(position);
   final Intent shortcutIntent = new Intent();
    ActivityInfo activity=launchable.activityInfo;
    ComponentName name=new ComponentName(activity.applicationInfo.packageName,activity.name);       
    shortcutIntent.setComponent(name);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final Intent intent = new Intent();
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    // Sets the custom shortcut's title
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, launchable.loadLabel(pm));
    // 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);
    finish();

Thank a lot for any clue

Waza_Be
  • 39,545
  • 47
  • 176
  • 256
  • ShortcutIconResource.fromContext(pkgContext, iconId) do the trick! http://stackoverflow.com/questions/17339231/create-shortcut-for-thrid-party-app-is-that-possible/17561676#17561676 – thecr0w Jul 10 '13 at 02:50

2 Answers2

28

Finally found a solution; I was stupid to use Intent.EXTRA_SHORTCUT_ICON_RESOURCE:

Here is the correct code:

Drawable iconDrawable = (....); 
BitmapDrawable bd = (BitmapDrawable) iconDrawable;
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bd.getBitmap());
Hamid
  • 4,200
  • 10
  • 40
  • 71
Waza_Be
  • 39,545
  • 47
  • 176
  • 256
3

I can't comment since I have only 23 reputation, but I used your code and it was usefull. But my image didn't scaled correctly on the shortcut, so I found two interesting topics that can complete the solution:

To get the correct size for a shortcut icon: https://stackoverflow.com/a/19003905/3741926

To scale your drawable (using the size you calculated with the previous function) https://stackoverflow.com/a/10703256/3741926

With all that I got a shortcut with a correctly scaled icon, hope it will help

Community
  • 1
  • 1
Bartho
  • 93
  • 1
  • 8