On Android 4.2.2, Intent INSTALL_SHORTCUT creates shortcut in the second page

雨燕双飞 提交于 2019-12-23 05:44:33

问题


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.



来源:https://stackoverflow.com/questions/22613320/on-android-4-2-2-intent-install-shortcut-creates-shortcut-in-the-second-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!