Android create shortcuts on the home screen

前端 未结 10 924
忘掉有多难
忘掉有多难 2020-11-22 13:16

What I want to do is:

1) I\'m inside an activity, there are 2 buttons. If I click the first one a shortcut is created in my home screen. The shortcut open an

10条回答
  •  醉话见心
    2020-11-22 13:44

    Starting from Android O, this is the way to create a shortcut:

    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
        final ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
    
        ShortcutInfo pinShortcutInfo = new ShortcutInfo.Builder(context, shortcutId)
                .setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher))
                .setShortLabel(label)
                .setIntent(new Intent(context, MainActivity.class).setAction(Intent.ACTION_MAIN))
                .build();
        shortcutManager.requestPinShortcut(pinShortcutInfo, null);
    }
    

    It has a lot of limitations, sadly:

    1. Requires the user to accept adding it.
    2. Can't be added/removed in the background.
    3. Won't be removed if the targeted app is removed. Only the one which created it.
    4. Can't create the icon based on a resource of the targeted app, except if it's of the current app. You can do it from a bitmap though.

    For pre-Android O, you can use ShortcutManagerCompat to create new shortcuts too, without any of those limitations.

提交回复
热议问题