【发布时间】:2018-08-05 00:30:18
【问题描述】:
我需要将我的 Android 应用程序作为快捷方式添加到主屏幕。
请给出这个想法。如果可能,请告诉我如何管理现有的快捷方式(删除和添加更多快捷方式)。
【问题讨论】:
-
我认为 api 不会公开该功能。默认情况下,您会在上拉对话框中看到一个应用程序图标。
标签: android
我需要将我的 Android 应用程序作为快捷方式添加到主屏幕。
请给出这个想法。如果可能,请告诉我如何管理现有的快捷方式(删除和添加更多快捷方式)。
【问题讨论】:
标签: android
在您的第一个屏幕的 onCreate() 方法中调用此方法。还要确保 像我一样使用 SharedPreferences 检查应用程序是否第一次运行 做了:
private void addShortcut() {
//Adding shortcut for MainActivity on Home screen
Intent shortcutIntent = new Intent(getApplicationContext(),MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, this.getResources().getString(R.string.app_name));
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(getApplicationContext(),
R.drawable.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
// TO check app is installed first time.
SharedPreferences prefs = getSharedPreferences("ShortCutPrefs", MODE_PRIVATE);
if(!prefs.getBoolean("isFirstTime", false)){
addShortcut();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}
【讨论】:
我花了很多时间尝试从 stackoverflow 尝试不同的解决方案,但大多数都没有用,因为它们正在启动新的 Activity 实例。我需要的快捷方式与应用列表中的快捷方式或 Google Play 自动安装的快捷方式完全相同(启动活动或将已启动的活动放在前面)。
@Override
public void onCreate(Bundle savedInstanceState) {
//Save the flag to SharedPreferences to prevent duplicated shortcuts
if (!settings.isShortcutAdded()) {
addShortcut();
settings.setShortcutAdded(true);
}
}
private void addShortcut() {
Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
shortcutIntent.addCategory(Intent.CATEGORY_LAUNCHER);
int flags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT;
shortcutIntent.addFlags(flags);
Intent addIntent = new Intent();
addIntent.putExtra("duplicate", false);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getResources().getString(R.string.app_name));
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
.fromContext(getApplicationContext(), R.drawable.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
别忘了更新你的清单:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
【讨论】: