这个问题是在我开发android应用程序时出现的。我想分享我在开发过程中收集到的知识。
Android为我们提供了一个intent类com.android.launcher.action.INSTALL_SHORTCUT
,它可以用来为主屏幕添加快捷方式。在下面的代码片段中,我们创建了一个名为HelloWorldShortcut的活动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);
}
注意我们是如何创建保存目标活动的shortcutIntent对象的。这个intent对象作为EXTRA_SHORTCUT_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);
}