如何以编程方式在Android中将快捷方式添加到主屏幕
当我开发一个android应用程序时出现了这个问题.我想分享我在开发过程中收集到的知识.
This issue has arisen when I was developing an android application. I thought of sharing the knowledge I gathered during my development.
Android向我们提供了一个意图类com.android.launcher.action.INSTALL_SHORTCUT
,可用于向主屏幕添加快捷方式.在下面的代码片段中,我们创建了一个名为MainActivity的活动快捷方式,其名称为HelloWorldShortcut.
Android provide us an intent class com.android.launcher.action.INSTALL_SHORTCUT
which can be used to add shortcuts to home screen. In following code snippet we create a shortcut of activity MainActivity with the name HelloWorldShortcut.
首先,我们需要向Android清单xml添加权限INSTALL_SHORTCUT
.
First we need to add permission INSTALL_SHORTCUT
to android manifest xml.
<uses-permission
android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
addShortcut()
方法在主屏幕上创建一个新的快捷方式.
The addShortcut()
method creates a new shortcut on Home screen.
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对象.该意图对象作为EXTRA_SHORTCUT_INTENT
被添加到另一个意图中.
Note how we create shortcutIntent object which holds our target activity. This intent object is added into another intent as EXTRA_SHORTCUT_INTENT
.
最后,我们广播了新的意图.这将添加一个快捷方式,其名称提到为
EXTRA_SHORTCUT_NAME
和EXTRA_SHORTCUT_ICON_RESOURCE
定义的图标.
Finally we broadcast the new intent. This adds a shortcut with name mentioned as
EXTRA_SHORTCUT_NAME
and icon defined by EXTRA_SHORTCUT_ICON_RESOURCE
.
还要放置此代码以避免出现多个快捷方式:
Also put this code to avoid multiple shortcuts :
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);
}