安装后如何添加应用程序的主屏幕快捷方式



在启动应用程序之前,如何将应用程序的快捷方式添加到Android主屏幕?

我需要在安装应用程序后立即添加它。

如果您在安装应用程序自动创建快捷方式后在google play商店中发布应用程序,但如果您想处理此问题,Android为我们提供了一个意向类com.Android.loncher.action.INSTALL_shortcut,可用于向主屏幕添加快捷方式。在下面的代码片段中,我们创建了一个名为HelloWorldShortcut的活动MainActivity的快捷方式。

首先,我们需要将权限INSTALL_SHORTCUT添加到android清单XML中。

<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_SSHORTCUT_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);
}

最新更新