我想为我的应用程序添加一个快捷方式,但我无法设法不复制本机手动创建的快捷方式(例如,通过使用应用程序菜单中的应用程序图标拖放到主屏幕)。
这是我的代码:
public void addShortcut(Context context)
{
this.manageShortcutAction(context, "com.android.launcher.action.INSTALL_SHORTCUT");
}
public void deleteShortcut(Context context)
{
this.manageShortcutAction(context, "com.android.launcher.action.UNINSTALL_SHORTCUT");
}
private void manageShortcutAction(Context context, String intentAction)
{
Context applicationContext = context.getApplicationContext();
Intent shortcut = new Intent(intentAction);
ApplicationInfo appInfo = applicationContext.getApplicationInfo();
PackageManager packageManager= applicationContext.getPackageManager();
String applicationName = (String) packageManager.getApplicationLabel(appInfo);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, applicationName); // Shortcut name
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, packageManager.getLaunchIntentForPackage(appInfo.packageName));// Setup activity should be shortcut object
shortcut.putExtra("duplicate", false); // Just create once
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(applicationContext, appInfo.icon));// Set shortcut icon
applicationContext.sendBroadcast(shortcut);
}
以及我的清单所需的权限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
顺便说一下,我已经覆盖了现在MainApplication
扩展Application
的应用程序代码。我已经尝试创建一个组件来创建 Intent.EXTRA_SHORTCUT_INTENT
,没有预期的结果。
如果有人有想法...
我发现为了防止应用程序创建在应用程序安装时创建的快捷方式的副本(或通过从菜单复制),我必须创建一个具有与现有快捷方式相同的参数 - 使用相同的快捷方式名称是不够的。
经过大量测试并感谢logcat,我已经能够创建一个精确的副本,如下所示:
private void installShortcut() {
final Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
final Intent intent = new Intent();
intent.putExtra("duplicate", false);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(intent);
}
与我在SO上找到的其他答案的区别在于这3行:
shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
我通过使用系统创建的快捷方式手动启动应用程序时打印的日志条目而发现的
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.myapp/.activities.main.MainActivity bnds=[365,73][475,191] } from pid 279
在与索尼的开发人员讨论后,没有办法不复制手动创建的快捷方式......
我为三星找到了一些方法,但这些方法不是通用的。