2

我使用下面的代码为我的应用程序创建快捷方式,我在我的 Splashscreen(这是我的第一个屏幕)页面中添加了这个方法,在第一次执行时会创建快捷方式,现在的问题是每次创建快捷方式我的活动启动。

public boolean setShortCut(Context context, String appName) {
        System.out.println("in the shortcutapp on create method ");
        boolean flag = false;
        int app_id = -1;
        PackageManager p = context.getPackageManager();
        Intent i = new Intent(Intent.ACTION_MAIN);
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> res = p.queryIntentActivities(i, 0);
        System.out.println("the res size is: " + res.size());

        for (int k = 0; k < res.size(); k++) {
            System.out.println("the application name is: "
                    + res.get(k).activityInfo.loadLabel(p));
            if (res.get(k).activityInfo.loadLabel(p).toString().equals(appName)) {
                flag = true;
                app_id = k;
                break;
            }
        }

        if (flag) {
            ActivityInfo ai = res.get(app_id).activityInfo;

            Intent shortcutIntent = new Intent();
            shortcutIntent.setClassName(ai.packageName, ai.name);
            shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            Intent intent = new Intent();
            intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);

            intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);

            intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                    Intent.ShortcutIconResource.fromContext(context,
                            R.drawable.app_icon));
            // intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
            context.sendBroadcast(intent);
            System.out.println("in the shortcutapp on create method completed");
        } else
            System.out.println("appllicaton not found");
        return true;
    }
4

1 回答 1

2

在您的应用程序的共享首选项中维护一个布尔值,一旦您创建快捷方式,该值就会设置为 true。

if (flag && !isShortcutCreatedAlready()) {

    // Your code to create shortcut. Put the below code at the end of your try block

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("isShortcutCreated", true);
            editor.commit();
    }


    private boolean isShortcutCreatedAlready(){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return prefs.getBoolean("isShortcutCreated", false);
    }
于 2013-09-23T18:37:39.363 回答