这个问题是在我开发安卓应用程序时出现的。我想分享我在开发过程中收集到的知识。
最佳答案
Android 为我们提供了一个 Intent 类 com.android.launcher.action.INSTALL_SHORTCUT
,它可以用来添加快捷方式到主屏幕。在下面的代码 fragment 中,我们创建了一个名为 HelloWorldShortcut 的 Activity MainActivity 的快捷方式。
首先我们需要添加权限INSTALL_SHORTCUT
到android manifest 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);
}
请注意我们如何创建包含目标 Activity 的快捷方式 Intent 对象。此 Intent 对象作为 EXTRA_SHORTCUT_INTENT
添加到另一个 Intent 中。
最后我们广播了新的 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);
}
关于android - 如何以编程方式在android中添加到主屏幕的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873256/