如何在Android O上以编程方式知道通知渠道是否已启用?

12

看文档我可以看到检查通知频道所有属性的方法,但我找不到检查频道本身是否已启用或禁用的方法。

我有什么遗漏吗?

2个回答

16

官方文档中有你需要的答案:

您可以调用以下两种方法来发现用户应用于通知渠道的设置:

  • 要检索单个通知渠道,可以调用 getNotificationChannel()
  • 要检索属于您的应用的所有通知渠道,可以调用 getNotificationChannels()

获取 NotificationChannel 后,您可以使用诸如 getVibrationPattern()getSound() 等方法查找用户当前的设置。要找出用户是否阻止了通知渠道,可以调用 getImportance()。如果通知渠道被阻止,则 getImportance() 返回IMPORTANCE_NONE

因此,getImportance() 将告诉您通知渠道是否被阻止。


你能提供一个示例来演示如何调用 getNotificationChannels() 方法以检索属于你的应用程序的所有通知渠道吗?我需要帮助获取应用程序通道声音 URI。 - Sagar

2
这是我的完整代码:

public static boolean isNotificationChannelEnabled(@NonNull String groupId, @NonNull String... channelIds) {
    boolean appNotificationEnable = NotificationManagerCompat.from(AppContext.getContext()).areNotificationsEnabled();
    if (!appNotificationEnable) {
        return false;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager manager = (NotificationManager) AppContext.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            List<NotificationChannelGroup> groupList = manager.getNotificationChannelGroups();
            for (NotificationChannelGroup group : groupList) {
                if (TextUtils.equals(group.getId(), groupId)) {
                    if (group.isBlocked()) {
                        return false;
                    }
                }
            }
        }

        for (String channelId : channelIds) {
            NotificationChannel channel = manager.getNotificationChannel(channelId);
            if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
                return false;
            }
        }
        return true;
    }

    return false;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接