Android (안드로이드)/Notification
Android in A..Z - Notification (Group)
강태종
2021. 7. 15. 16:33
그룹
Android 7.0(API 24)부터는 관련된 알림을 그룹으로 표시할 수 있습니다. 예를 들어, 앱에서 수신된 이메일의 알림을 표시하려면 모든 알림을 동일한 그룹에 포함하여 함께 축소할 수 있도록 해야 합니다.
Android에서 기본적으로 그룹을 지정하지 않은 경우 4개 이상의 알림을 자동으로 그룹화 합니다.
Notification 만들기
Notification을 만들 때 setGroup을 통해 그룹을 정해줍니다.
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_android)
.setContentTitle(message.title)
.setContentText(message.message)
.setGroup(GROUP_KEY)
.build()
manager.notify(message.id, notification)
Summary Notification 만들기
요약 정보를 가진 Notification을 만들고 setGroupSummary를 통해 요약할 수 있습니다.
val summaryNotification = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getString(R.string.n_message, list.size))
.setContentText(context.getString(R.string.tab_to_open))
.setSubText(context.getString(R.string.group))
.setSmallIcon(R.drawable.ic_android)
.setGroup(GROUP_KEY)
.setGroupSummary(true)
.build()
manager.notify(1234, summaryNotification)
코드
class GroupNotificationManager @Inject constructor(
@ApplicationContext
private val context: Context
) {
companion object {
private const val CHANNEL_ID = "com.taetae98.notification.GROUP"
private const val CHANNEL_NAME = "Group"
private const val CHANNEL_DESCRIPTION = "This is Group Notification"
private const val GROUP_KEY = "com.taetae98.notification.GROUP.KEY"
}
private val manager by lazy {
NotificationManagerCompat.from(context)
}
fun notify(list: List<Message>) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
for (message in list) {
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_android)
.setContentTitle(message.title)
.setContentText(message.message)
.setGroup(GROUP_KEY)
.build()
manager.notify(message.id, notification)
}
val summaryNotification = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getString(R.string.n_message, list.size))
.setContentText(context.getString(R.string.tab_to_open))
.setSubText(context.getString(R.string.group))
.setSmallIcon(R.drawable.ic_android)
.setGroup(GROUP_KEY)
.setGroupSummary(true)
.build()
manager.notify(1234, summaryNotification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel() {
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH).apply {
description = CHANNEL_DESCRIPTION
}
manager.createNotificationChannel(channel)
}
}
Git
https://github.com/KangTaeJong98/Example/tree/main/Android/Notification
KangTaeJong98/Example
My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.
github.com