我使用下面的代码为我的应用程序创建快捷方式,我在我的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;
}
答案 0 :(得分: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);
}