Skip to content

Instantly share code, notes, and snippets.

@AniketSK
Created December 1, 2018 17:52
Show Gist options
  • Save AniketSK/dc9a09b0346019c2ab1eff3d5e724eac to your computer and use it in GitHub Desktop.
Save AniketSK/dc9a09b0346019c2ab1eff3d5e724eac to your computer and use it in GitHub Desktop.
Creating a list of and registering channels for notifications reliably.
package com.aniketkadam.premail.base.notifications
import android.app.NotificationManager
import androidx.annotation.StringRes
import com.aniketkadam.premail.R
enum class ChannelIds(
@StringRes val channelNameRes: Int, @StringRes val channelDescriptionRes: Int,
val importance: Int
) {
REMINDERS(
R.string.reminders_channel_name,
R.string.reminders_channel_description,
NotificationManager.IMPORTANCE_HIGH
)
}
package com.aniketkadam.premail.base.notifications
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.os.Build
class ChannelRegistration {
/**
* Register every notification channel defined in the enum [ChannelIds]
*/
fun registerChannels(c: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = c.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
ChannelIds.values().forEach {
val name = c.getString(it.channelNameRes)
val descriptionText = c.getString(it.channelDescriptionRes)
val importance = it.importance
val mChannel = NotificationChannel(it.name, name, importance)
mChannel.description = descriptionText
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
notificationManager.createNotificationChannel(mChannel)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment