You can check if the user is allowing notifications for your application with this command:
NotificationManagerCompat.from(context).areNotificationsEnabled()
This one-liner works from API level 19+. However, starting with android O, notification channels are introduced. This allows the user to disable only particular notification channels from the application settings screen and also disable all notifications from the app. With the command above, you can only check if the notifications are allowed or not for the whole app, not specific channels. Meaning, you cannot see any notifications even tho the command above gives a value of true
The code below returns true
only if all notifications are allowed for the application and also all of the existing notification channels are enabled. Works from API level 19+ including the changes needed starting from Android O:
Java
public boolean areNotificationsEnabled() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (!manager.areNotificationsEnabled()) {
return false;
}
List<NotificationChannel> channels = manager.getNotificationChannels();
for (NotificationChannel channel : channels) {
if (channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
return false;
}
}
return true;
} else {
return NotificationManagerCompat.from(context).areNotificationsEnabled();
}
}
Kotlin
fun areNotificationsEnabled(notificationManager: NotificationManagerCompat) = when {
notificationManager.areNotificationsEnabled().not() -> false
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
notificationManager.notificationChannels.firstOrNull { channel ->
channel.importance == NotificationManager.IMPORTANCE_NONE
} == null
}
else -> true
}