Debbi Story

Notification badge 설정하기! 본문

안드로이드/Tip

Notification badge 설정하기!

Debbi 2021. 10. 26. 01:55
728x90

 

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val channel = NotificationChannel(channelData.id,
        channelData.name,
        NotificationManager.IMPORTANCE_DEFAULT)
    channel.enableVibration(true)
    channel.setShowBadge(true)
    notificationManager.createNotificationChannel(channel)
}else {
    Intent("android.intent.action.BADGE_COUNT_UPDATE")
        .putExtra("badge_count", count)
        .putExtra("badge_count_package_name", packageName)
        .putExtra("badge_count_class_name", getLauncherClassName(this))
        .run { sendBroadcast(this) }
}

 

fun getLauncherClassName(context: Context): String? {
    val intent = Intent(Intent.ACTION_MAIN)
    intent.addCategory(Intent.CATEGORY_LAUNCHER)
    intent.setPackage(context.applicationContext.packageName)
    val resolveInfoList =
        context.applicationContext.packageManager.queryIntentActivities(intent, 0)
    return if (resolveInfoList != null && resolveInfoList.size > 0) {
        resolveInfoList[0].activityInfo.name
    } else ""
}

 

안드로이드 8.0 오레오 버전 부터는 NotificationChannel를 설정해주어야 합니다!

8.0이상 버전은 channel.setShowBadge(true) 이렇게만 하면 설정이 되고,

알림을 확인하면 알아서 배지 카운트도 사라지지만!

8.0 미만 버전은 sendBroadcast 로 카운트값을 수동으로 설정해주어야 합니다..