Android in A..Z - Notification (기본)
Notification
사용자에게 알림을 보내야할 때 사용한다.
- 앱 또는 사용자가 닫을 때까지 알림창에 표시된다.
- Head Up Notification 처럼 즉각적으로 알림을 보여줄 수 있다. (Android 5.0(API 21) 이상 가능)
- Lock Screen에 표시할 수 있고, 보여주는 내용을 지정할 수 있다. (Android 5.0(API 21) 이상 가능)
- Launcher에서 지원하는 경우 알림 뱃지를 설정할 수 있다. (Android 8.0(API 26) 이상 가능)
Notification 구성
- Small Icon : 필수 구성요소이며 setSmallIcon을 통해 설정할 수 있다.
- App Name : 앱 이름, 시스템에서 제공한다.
- Time : 시스템에서 제공하지만 setWhen으로 설정하거나 setShowWhen으로 숨길 수 있다.
- Big Icon : setLargeIcon으로 설정할 수 있다.
- Content Title : setContentTitle로 설정할 수 있다.
- Content Text : setContentText로 설정할 수 있다.
Notification Channel 만들기
Android 8.0(API 26)이상에서 알림을 게시하려면 알림을 만들어야 하므로 앱이 시작하자마자 이 코드를 실행해야 합니다. 기존 알림 채널을 만들면 아무 작업도 실행되지 않으므로 이 코드를 반복적으로 호출하는 것이 안전합니다.
companion object {
private const val CHANNEL_ID = "com.taetae98.notification.NORMAL"
private const val CHANNEL_NAME = "Normal"
private const val CHANNEL_DESCRIPTION = "Normal Notification"
}
private val manager by lazy { context.getSystemService(NotificationManager::class.java) }
@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)
}
Notification 만들기
NotificationCompat.Builder를 사용하여 Builder 패턴으로 Notification을 만들 수 있다.
fun notify(message: Message) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_android) // Icon
.setContentTitle(message.title) // Title
.setContentText(message.message) // Content
.setPriority(NotificationCompat.PRIORITY_MAX) // 우선순위 (Android 7.1 이하에서 작동, Android 8.0 이상의 경우 Channel 우선순위 적용)
.build()
manager.notify(message.id, notification)
}
NotificationManager의 notify로 알림을 전송할 수 있으며 알림을 업데이트 할 경우 같은 ID로 새로운 Notification을 생성하여 notify하면 된다.
Notification 취소
NotificationManager의 cancel로 Notification의 ID를 통해 취소할 수 있다.
fun cancel(message: Message) {
manager.cancel(message.id)
}
Notification 중요도
Notification의 중요도에 따라 알림의 형태가 달라진다. Android 8.0(API 26)이상은 Notification Channel에 중요도를 설정하고 Android 7.1(API 25)이하는 Notification에 중요도를 설정한다.
중요도 | Android 8.0(API 26) 이상 Channel Importance |
Android 7.1(API 25) 이하 Notification Priority |
긴급 알림음이 울리며 헤드업 알림으로 표시됩니다. |
IMPORTANCE_HIGH | PRIORITY_HIGH, PRIORITY_MAX |
높음 알림음이 울립니다. |
IMPORTANCE_DEFAULT | PRIORITY_DEFAULT |
중간 알림음이 없습니다. |
IMPORTANCE_LOW | PRIORITY_LOW |
낮음 알림음이 없고 상태 표시줄에 표시되지 않습니다. |
IMPORTANCE_MIN | PRIORITY_MIN |
Notification 민감도
setVisibility를 설정해서 잠금 화면에서 알림의 표현 정도를 설정할 수 있다.
- VISIBILITY_PUBLIC 알림의 전체 콘텐츠를 표시합니다.
- VISIBILITY_SECRET 알림의 어느 부분도 잠금 화면에 표시하지 않습니다.
- VISIBILITY_PRIVATE 알림 아이콘과 콘텐츠 제목 등의 기본 정보는 표시하지만 알림의 전체 콘텐츠는 숨깁니다.
기타 설정
- setCategory : Message, Call, Alarm 등 카테고리를 설정할 수 있다. (방해 금지 모드에서 알림을 표시할 때 사용한다.)
- setOngoing : 사용자가 알림을 지울 수 없다.
- setAutoCancel : 알림을 클릭시 알림이 지워진다.
- setUsesChronometer : Time대신 Chronometer가 표시된다.
- setTicker : Status Bar에 한줄로 표시되는 메시지
- setTimeoutAfter : 지정된 시간 후에 알림이 사라진다.
코드
@Singleton
class NormalNotificationManager @Inject constructor(
@ApplicationContext
private val context: Context
) {
companion object {
private const val CHANNEL_ID = "com.taetae98.notification.NORMAL"
private const val CHANNEL_NAME = "Normal"
private const val CHANNEL_DESCRIPTION = "Normal Notification"
}
private val manager by lazy { context.getSystemService(NotificationManager::class.java) }
fun notify(message: Message) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_android) // Icon
.setContentTitle(message.title) // Title
.setContentText(message.message) // Content
.setPriority(NotificationCompat.PRIORITY_MAX) // 우선순위 (Android 7.1 이하에서 작동, Android 8.0 이상의 경우 Channel 우선순위 적용)
.build()
manager.notify(message.id, notification)
}
fun cancel(message: Message) {
manager.cancel(message.id)
}
@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