Search code examples
javaandroidkotlinpush-notificationandroid-notifications

Is check that notification channel is already created needed?


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)
    }
}

Solution

  • 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