How to create shortcuts on Android O, when targetting less than it?

心不动则不痛 提交于 2019-12-04 08:33:33

The right way is to call requestPinShortcut method. You don't need to target android O but you need to have at least compile SDK to 26. Compile SDK and target SDK are two different things.

It seems like I beat on this forever, but...

if(Build.VERSION.SDK_INT < 26) {
    ...
}
else {
    ShortcutManager shortcutManager
        = c.getSystemService(ShortcutManager.class);
    if (shortcutManager.isRequestPinShortcutSupported()) {
        Intent intent = new Intent(
            c.getApplicationContext(), c.getClass());
        intent.setAction(Intent.ACTION_MAIN);
        ShortcutInfo pinShortcutInfo = new ShortcutInfo
            .Builder(c,"pinned-shortcut")
            .setIcon(
                Icon.createWithResource(c, R.drawable.qmark)
            )
            .setIntent(intent)
            .setShortLabel(c.getString(R.string.app_label))
            .build();
        Intent pinnedShortcutCallbackIntent = shortcutManager
            .createShortcutResultIntent(pinShortcutInfo);
        //Get notified when a shortcut is pinned successfully//
        PendingIntent successCallback
            = PendingIntent.getBroadcast(
                c, 0
                , pinnedShortcutCallbackIntent, 0
            );
        shortcutManager.requestPinShortcut(
            pinShortcutInfo, successCallback.getIntentSender()
        );
    }
}

Is working for me. I know there were changes in 7.1 and don't know if this works for them and I don't know about the launcher issues mentioned above.
This was tested on a Samsung Galaxy Tab S3 running Android 8.0.0.

I put a simple app that does nothing but install a shortcut for itself on your homepage on github. It works for versions before and after Android 8. Pre Android 8 uses the sendBroadcast method and after creats a pinned shortcut.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!