首页 > 解决方案 > 在android O中固定快捷方式时接收回调/广播

问题描述

我正在尝试一次添加两个快捷方式。但是 android 8 显示了一个对话框并请求用户允许添加快捷方式,并且其中两个对话框不能同时出现。

所以我需要一种方法来在第一个对话框关闭时获得回调或广播,以便之后可以添加另一个快捷方式。目前,当用户允许请求时,我能够获得广播。但我想知道用户是否取消了对话框。

我正在使用以下代码:

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

标签: javaandroidandroid-broadcastandroid-shortcutandroid-shortcutmanager

解决方案


推荐阅读