Notification ?
안드로이드의 Notification은 사용자에게 시스템 이벤트, 애플리케이션 상태 또는 기타 중요한 정보를 알리기 위해 사용되는 메세지입니다. 이 메세지는 상태 표시줄 (상단바)에 표시되며 사용자가 알림을 탭하면 해당 앱이나 관련 작업으로 이동할 수 있도록 합니다.
예제
간단한 예제로 알아보겠습니다.
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
var builder = NotificationCompat.Builder(this, "CHANNEL_ID")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Hello world")
.setContentText("notificationText")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
NotificationCompat.Builder
객체를 사용하여 알림 콘텐츠와 채널을 설정해야 합니다. 다음 예에서는 다음 항목이 포함된 알림을 만드는 방법을 보여줍니다.
setSmallIcon()
: 작은 아이콘. 사용자가 볼 수 있는 유일한 필수 콘텐츠입니다.setContentTitle()
: 설정한 제목setContentText()
: 본문 텍스트setPriority()
: 알림 우선순위. 우선순위에 따라 Android 7.1 이하에서 알림이 얼마나 강제적이어야 하는지가 결정됩니다. (Android 8.0 이상의 경우 다음 섹션에 표시된 채널 중요도를 대신 설정해야 합니다.)setAutoCancel()
: 사용자가 알림을 탭하면 자동으로 알림을 삭제합니다.모든 알림은 일반적으로 앱에서 알림에 상응하는 활동을 열려면 탭에 응답해야 합니다. 이 작업을 하려면 PendingIntent
객체로 정의된 콘텐츠 인텐트를 지정하여 setContentIntent()
에 전달해야 합니다.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "channel_name"
val descriptionText = "descriptionText"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("CHANNEL_ID", name, importance).apply {
description = descriptionText
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
Android 8.0 이상에서 알림을 게시하려면 알림을 만들어야 하므로 앱이 시작하자마자 이 코드를 실행해야 합니다. 기존 알림 채널을 만들면 아무 작업도 실행되지 않으므로 이 코드를 반복적으로 호출하는 것이 안전합니다.
notificationManager.notify(1, builder.build());
https://developer.android.com/training/notify-user/build-notification?hl=ko