我在开发一个安卓应用时遇到了这个问题,现在想分享一下我在开发过程中积累的知识。
我在开发一个安卓应用时遇到了这个问题,现在想分享一下我在开发过程中积累的知识。
Android提供了一个意图类com.android.launcher.action.INSTALL_SHORTCUT
,可以用来将快捷方式添加到主屏幕。在下面的代码片段中,我们创建了一个名为HelloWorldShortcut的MainActivity活动的快捷方式。
首先,我们需要在android清单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);
}
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);
}
addIntent.putExtra("duplicate", false)
,以防止创建多个快捷方式。 - Elshan.commit()
。 - Jason John