【发布时间】:2018-11-12 01:39:24
【问题描述】:
如何在启动应用之前将应用的快捷方式添加到 Android 主屏幕?
我需要在安装应用程序后立即添加它。
【问题讨论】:
-
您的应用应该已经添加到“应用抽屉”中。并非所有启动器都有“主屏幕”
-
不要,太讨厌了。
如何在启动应用之前将应用的快捷方式添加到 Android 主屏幕?
我需要在安装应用程序后立即添加它。
【问题讨论】:
如果您在安装应用程序自动创建快捷方式后在 Google Play 商店中发布您的应用程序,但如果您想处理 Android 为我们提供了一个意图类 com.android.launcher.action.INSTALL_SHORTCUT,它可用于将快捷方式添加到主屏幕。在下面的代码 sn-p 中,我们创建了一个名为 HelloWorldShortcut 的活动 MainActivity 的快捷方式。
首先,我们需要向 android manifest XML 添加权限 INSTALL_SHORTCUT。
<uses-permission
android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
addShortcut() 方法在主屏幕上创建一个新的快捷方式。
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, "HelloWorldShortcut");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(getApplicationContext(),
R.drawable.ic_launcher));
addIntent
.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
addIntent.putExtra("duplicate", false); //may it's already there so don't duplicate
getApplicationContext().sendBroadcast(addIntent);
}
请注意我们如何创建保存目标活动的快捷方式 Intent 对象。此意图对象作为 EXTRA_SHORTCUT_INTENT 添加到另一个意图中。
最后,我们广播了新的意图。这会添加一个快捷方式,其名称为 EXTRA_SHORTCUT_NAME,图标由 EXTRA_SHORTCUT_ICON_RESOURCE 定义。
也放这段代码以避免多个快捷方式:
if(!getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).getBoolean(Utils.IS_ICON_CREATED, false)){
addShortcut();
getSharedPreferences(Utils.APP_PREFERENCE, Activity.MODE_PRIVATE).edit().putBoolean(Utils.IS_ICON_CREATED, true);
}
【讨论】: