On Android 4.2.2, Intent INSTALL_SHORTCUT creates

2019-06-14 01:25发布

问题:

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.

回答1:

There are hundreds of home screen implementations, both pre-installed and ones installable via the Play Store. Each is welcome to either:

  • ignore your Intent entirely, by simply not having an <intent-filter> for it, or
  • put the shortcut wherever it wants

On Android 4.0.4 the shortcut is created in the right place.

No, it is put in "the right place" in both cases, as it is the authors of the home screen -- not you -- who determines what "the right place" is.