我想通过按一下按钮轻松地将我的应用程序添加到主屏幕。所以我在想什么,是我应用程序底部的一个按钮,上面写着“添加到主屏幕”,当按下该按钮时,它会在不关闭应用程序的情况下将快捷方式添加到主屏幕。
我应该添加什么代码来做到这一点?

最佳答案

发送带有结果Intent的INSTALL_SHORTCUT广播作为额外消息(在这种情况下,结果Intent直接打开了一些 Activity )。

    //where this is a context (e.g. your current activity)
    final Intent shortcutIntent = new Intent(this, SomeActivity.class);

    final Intent intent = new Intent();
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    // Sets the custom shortcut's title
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
    // Set the custom shortcut icon
    intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
    // add the shortcut
    intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    sendBroadcast(intent);

您还需要在 list 中获得此许可权:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

10-07 19:28
查看更多