Friday, October 23, 2020

How to detect whether the Notification is turned off by the user or not

Users can turn off the notification from the Android Settings.

Here's how to detect it programmatically.


For Android O+, also need to check the channel you're looking for is turned off.


private fun isNotificationEnabled(context: Context, channelId: String): Boolean {
try {
var enabled = NotificationManagerCompat.from(context).areNotificationsEnabled()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
isChannelBlocked(context, channelId)) {
enabled = false
}
return enabled
} catch (e: Exception) {
}
return false
}


@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(Build.VERSION_CODES.M)
private fun isChannelBlocked(context: Context, channelId: String): Boolean {
try {
val manager = context.getSystemService(NotificationManager::class.java)
val channel = manager.getNotificationChannel(channelId)
return channel != null && channel?.importance == NotificationManager.IMPORTANCE_NONE
} catch (e: Exception) {
}
return false
}