我的应用程序在按下特定按钮时在主屏幕上创建快捷方式。但是当我下次创建另一个快捷方式时按下相同的按钮而不删除上一个快捷方式。我的代码中是否有任何问题
private void ShortcutIcon(){
final String PREF_KEY_SHORTCUT_ADDED="Poo";
// Checking if ShortCut was already added
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
boolean shortCutWasAlreadyAdded = sharedPreferences.getBoolean(PREF_KEY_SHORTCUT_ADDED, false);
Toast.makeText(getApplicationContext(), "creating shortcut on desktop",
Toast.LENGTH_LONG).show();
// if (shortCutWasAlreadyAdded) return;
Intent shortcutIntent = new Intent(getApplicationContext(), Shortcut.class);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "SOS");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.sos));
if (shortCutWasAlreadyAdded)
{
Intent shortcut = new Intent();
shortcutIntent.setAction(Intent.ACTION_VIEW);
shortcutIntent.setClassName(MainActivity.this, "com.example.urltesting.Shortcut");
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent removeIntent = new Intent();
removeIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcut);
removeIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "SOS");
removeIntent.putExtra("duplicate", false);
removeIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
Toast.makeText(getApplicationContext(), "trying to remove shortcut",
Toast.LENGTH_LONG).show();
getApplicationContext().sendBroadcast(removeIntent);
}
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
// Remembering that ShortCut was already added
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(PREF_KEY_SHORTCUT_ADDED, true);
editor.commit();
}
}
答案 0 :(得分:0)
您是否在清单文件中添加了以下权限?
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" /
您是否在手机上使用第三方启动器(除了Stock安卓启动器)?只要您使用的启动器支持该操作,创建和删除应用程序快捷方式就可以正常工作。
如果您使用默认的Android启动器,那么您可以尝试以下代码来删除/卸载应用程序快捷方式:
shortcutIntent = new Intent();
shortcutIntent.setClassName("com.abc.xyz", "XYZActivity");
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
Intent intentShortcut = new Intent();
intentShortcut.putExtra("android.intent.extra.shortcut.INTENT", shortcutIntent);
intentShortcut.putExtra("android.intent.extra.shortcut.NAME", getResources().getString(R.string.app_name));
intentShortcut.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", icon);
intentShortcut.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
sendBroadcast(intentShortcut);