Reputation: 1968
Do we need to check before creating notification channel that it isn't already created?
private fun createChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// todo: add here check if channel is already created
val defaultChannel = NotificationChannel(MEDIA_UPLOAD_NOTIFICATION_CHANNEL_ID, MEDIA_UPLOAD_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
defaultChannel.description = MEDIA_UPLOAD_NOTIFICATION_CHANNEL_DESC
defaultChannel.enableVibration(true)
notificationManager.createNotificationChannel(defaultChannel)
}
}
Upvotes: 10
Views: 5283
Reputation: 87
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(NotificationManager::class.java) as NotificationManager
if(notificationManager.getNotificationChannel("CHANNEL_ID") == null) {
val serviceChannel = NotificationChannel("CHANNEL_ID", "CHANNEL_NAME", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(serviceChannel)
}
}
As other mentioned above there's no need to check for existence unless you are doing something particular.
Upvotes: 2
Reputation: 3414
As suggested in the documentation.
If creating a NotificationChannel with the same original values there won't be any operation. So, it's safe to call the code.
Please checkout documentation for more details - https://developer.android.com/training/notify-user/channels#CreateChannel
Upvotes: 4
Reputation: 18112
No, you don't really have to check that. If a channel with the same ID exists then Android doesn't create another.
As per docs
Creating an existing notification channel with its original values performs no operation, so it's safe to call this code when starting an app.
More info at https://developer.android.com/training/notify-user/channels#CreateChannel
Upvotes: 13