I get a strange result when calling this code to simply create a shortcut in the home screen.
The shortcut is created on the second page of the home screen (and the first page is empty so there is enought space!). Any ideas?
public static void installShortcut(Context context, String packageName, String componentName, String shortcutName, Parcelable icon) {
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
ComponentName cn = new ComponentName(packageName, componentName);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(cn));
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
shortcut.putExtra("duplicate", false);
context.sendBroadcast(shortcut);
}
// gets some info from external package by name
public static void createShortcutForPackage(Context context, String packageName, String className) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, className));
PackageManager pm = context.getPackageManager();
ResolveInfo ri = pm.resolveActivity(intent, 0);
String shortcutName = ri.loadLabel(pm).toString();
String activityName = ri.activityInfo.name;
int iconId = ri.activityInfo.applicationInfo.icon;
Context pkgContext;
try {
pkgContext = context.createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
if (pkgContext != null) {
ShortcutIconResource sir = Intent.ShortcutIconResource.fromContext(pkgContext, iconId);
installShortcut(pkgContext, packageName, activityName, shortcutName, sir);
}
} catch (NameNotFoundException e) {
}
}
This is the default Android 4.2.2 Home screen:
UPDATE: On Android 4.0.4 the shortcut is created in the right place.