Создание ярлыка не работает

У меня есть этот код для создания ярлыка моего приложения на домашнем экране, он работает на API 21+, но не работает под ним.

это мой код:

Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Intent addIntent = new Intent();
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
        addIntent.putExtra("duplicate", false);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher));
        addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        getApplicationContext().sendBroadcast(addIntent);

Как я могу заставить его работать на всех версиях Android?

1 ответ

Решение

Добавить эту строку

shortcutIntent.setAction(Intent.ACTION_MAIN);

и добавить разрешение в манифест

<uses-permission
    android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
Другие вопросы по тегам