在Android 4.2.2上,Intent INSTALL_SHORTCUT在第二页中创建快捷方式

时间:2014-03-24 15:13:34

标签: android android-intent shortcut android-4.2-jelly-bean homescreen

调用此代码只是在主屏幕中创建快捷方式时,我得到一个奇怪的结果。

快捷键在主屏幕的第二页上创建(第一页是空的,因此有空间!)。有什么想法吗?

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) {
    }
}

这是默认的Android 4.2.2主屏幕:

enter image description here

更新 在Android 4.0.4上,快捷方式在正确的位置创建。

1 个答案:

答案 0 :(得分:1)

有数百个主屏幕实现,既可以预先安装,也可以通过Play商店安装。欢迎各自:

  • 完全忽略您的Intent,只是没有<intent-filter>,或
  • 将快捷方式放在任何地方
  

在Android 4.0.4上,快捷方式会在正确的位置创建。

不,它在两种情况下都被置于“正确的位置”,因为它是主屏幕的作者 - 而不是你 - 谁决定了什么是“正确的地方”。