5

I am trying to add two shortcuts at once. But android 8 shows a dialog and requests permission from the user to add shortcut and two of those dialogs cannot be presented at once.

So I need a way by which I can get a callback or broadcast when the first dialog is closed so that I can add another shortcut afterwards. Currently I am able to get the broadcast when user allows the request. But I want to know if the user has canceled the dialog.

I am using the following code:

@RequiresApi(api = Build.VERSION_CODES.O)
private static void addShortcutNew(Context context, Intent shortcutIntent, String label, int iconRes, int color) {
    ShortcutManager manager = context.getSystemService(ShortcutManager.class);
    if (manager != null && manager.isRequestPinShortcutSupported()) {

        ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(context, label)
                .setIcon(prepareIcon(context, iconRes, color)) // prepareIcon is my own method which returns an Icon.
                .setIntent(shortcutIntent)
                .setShortLabel(label)
                .setLongLabel(label)
                .build();

        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "Broadcast", Toast.LENGTH_SHORT).show();
                context.unregisterReceiver(this);
            }
        }, new IntentFilter("test_action"));

        Intent intent = new Intent("test_action");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 123, intent, 0);
        manager.requestPinShortcut(shortcutInfo, pendingIntent.getIntentSender());

    } else {
        Toast.makeText(context, R.string.add_shortcut_error, Toast.LENGTH_SHORT).show();
    }
}
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
  • If anyone else comes up with this problem, I did a temporary workaround by storing the `ShortcutInfo` object in a field before adding it and checking if it is not null in the `onResume` method. – Nabin Bhandari Jun 07 '18 at 09:31
  • Unfortunately the docs explicitly say they will not call back on a failure. What I did was to call an alertdialog and let the user say yes/no. If no, I start the next alert dialog in the no button. If yes, I let the android callback completion start the next dialog. It makes the user day yes twice but I couldn't think of anything else. – steven smith Oct 16 '18 at 02:47

0 Answers0