Receive Callback / Broadcast when pinning shortcut in android O

1.2k Views Asked by At

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();
    }
}
0

There are 0 best solutions below