Search code examples
androidandroid-shortcut

Shortcut creation not working


I have this code for making a shortcut of my application on home screen , it works on API 21+ but it doesn't work below it.

this is my code:

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);

How can I make it work on all android versions?


Solution

  • add this line

    shortcutIntent.setAction(Intent.ACTION_MAIN);
    

    and add permission in Manifest

    <uses-permission
        android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />