1 回答
TA贡献2003条经验 获得超2个赞
如果您在安装应用程序自动创建快捷方式后在 Google Play 商店中发布您的应用程序,但如果您想处理 Android 为我们提供了一个意图类 com.android.launcher.action.INSTALL_SHORTCUT,它可用于向主屏幕添加快捷方式。在下面的代码片段中,我们创建了一个名为 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);
}
添加回答
举报
