查看通知通道是否被用户静音

Find out whether notification channel is muted by the user

在我的 Android 应用程序中有一个长 运行 服务(导出数据),它显示进度并以通知用户共享导出的文件结束。需要明确的是,这不是推送通知,而是 new NotificationCompat.Builder(…).set…().build() 在本地创建的 Notification

有相当多的用户将通知通道静音(或全局禁用我的应用程序的通知)。我不知道为什么,因为它真的不是很冗长,顺便说一句。但这些用户觉得该应用程序无法正常工作。如果通知被静音,我想警告他们。

我可以预先查明特定 NotificationChannel 是否被用户静音了吗?

我只找到了 NotificationManager.areNotificationsEnabled(),但我不确定它是否有其他用途。

我相信您可以结合使用以下两种方法来检测特定频道或整个包裹的通知是否被阻止。

来自官方文档

isBlocked()

public boolean isBlocked ()
Returns whether or not notifications posted to channels belonging to this group are blocked. This value is independent of NotificationManager.areNotificationsEnabled() and NotificationChannel.getImportance().

areNotificationsEnabled()

public boolean areNotificationsEnabled ()
Returns whether notifications from the calling package are blocked.

要检索通知渠道,我们可以在 NotificationManager 上调用方法 getNotificationChannel()

我们需要通过相关频道的channel_id。

此外,要检索所有 NotificationChannels 的列表,我们可以调用方法 getNotificationChannels().

NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    List<NotificationChannel> notificationChannels = notificationManager.getNotificationChannels();
}

现在使用您的频道 ID 从列表中检索该频道的属性。 例如:如果我创建了 ID 为 "Backup alerts"

的频道

然后我应该检查那个通道的属性。

如果您需要提示用户调整该频道的设置:您可以使用如下 Intent 从应用程序本身触发一个 Intent:

Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID, notificationChannel.getId());
/*intent.putExtra(Settings.EXTRA_CHANNEL_ID, "Backup alerts");*/
/* Above line is example   */
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
startActivity(intent);

我们传递频道ID和应用程序包名称。这专门打开了特定的频道 ID。

希望对您有所帮助 ;)