Notification (알림)
공식 문서
https://developer.android.com/training/notify-user/build-notification?hl=ko
알림 만들기 | Android 개발자 | Android Developers
알림 만들기 알림은 사용 중이 아닌 앱의 이벤트에 관한 짧고 시기적절한 정보를 제공합니다. 이 페이지에서는 Android 4.0(API 레벨 14) 이상의 다양한 기능을 사용하여 알림을 만드는 방법을 설명
developer.android.com

가장 기본적이고 간단한 형태(축소된 형태) 의 알림에는 아이콘, 제목, 소량의 콘텐츠 텍스트가 표시된다.
기본 메인 로직
1. 알림 콘텐츠 설정 및 알람의 탭 작업 설정
2. 채널 만들기 및 중요도 설정
3. 알림 표시
알림 콘텐츠 설정
NotificationCompat.Builder 객체를 사용해 알림 콘텐츠와 채널을 설정
- setSmallIcon() : 작은 아이콘, 사용자가 볼 수 있는 유일한 필수 콘텐츠
- setContentTitle() : 제목
- setContentText() : 본문 텍스트
- setPriority() : 알림 우선순위
var builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
알림의 탭 작업 설정
모든 알림은 앱에서 활동을 열려면 탭에 응답해야 한다. 이 작업을 하려면 PendingIntent 객체로 정의된 콘텐츠 인텐트를 지정하여 setContentIntent() 에 전달해야 한다.
※ PendingIntent 개념 https://kje0915.tistory.com/10
알림의 인텐트 구성하는 방법
https://developer.android.com/training/notify-user/navigation?hl=ko
val intent = Intent(this, AlertDetails::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(pendingIntent)
.setAutoCancel(true)
- setAutoCancel() : 사용자가 알림을 탭하면 자동으로 알림을 삭제
- setFlags() : 사용자가 알림을 통해 앱을 연 후 예상되는 탐색 환경을 유지하는데 도움이 되는 메서드
채널 만들기 및 중요도 설정
Android8.0 이상에서 알림을 제공하려면 NotificationChannel 인스턴스를 createNotificationChannel() 에 전달하여 앱의 알림 채널을 시스템에 등록해야 한다. 따라서 디바이스에 notification 을 띄우려면 먼저 channel 을 생성해야 한다.
다음 코드는 SDK_INT 버전에서 조건에 의해 차단된다.
private fun createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
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)
}
}
NotificationChannel 생성자에는 importance 가 필요하므로 NotificationManager 클래스의 상수 중 하나를 사용한다. 이 매개변수에 따라 채널에 속하는 모든 알림을 사용자에게 전달하는 방법이 결정된다.
단 Android7.1 이하를 지원하려면 위에 표시된 대로 setPriority() 를 사용해 우선순위도 설정해야 한다.
NotificationChannel 인자
- Channel ID : 앱마다 고유한 ID 생성
- Channel Name : 사용자에게 보여지는 채널의 이름
- Channel Importance : 채널의 중요도, IMPORTANCE_DEFAULT, IMPORTANCE_HIGH 등으로 설정 가능
알림 표시 (Notification 등록)
알림을 표시하려면 NotificationManagerCompat.notify() 를 호출하여 알림의 고유ID 와 NotificationCompat.Builder.build() 의 결과를 전달한다.
with(NotificationManagerCompat.from(this)) {
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
notify(notificationId, builder.build())
}