IT/Android (안드로이드)

Android N.3-1 Using Notification

Edmond Na 2025. 4. 21. 23:23

* 2021. 2. 26 작성

 

### #0 Notification, 알림이란

알림은 사용 중이 아닌 앱의 이벤트에 관한 짧고 시기적절한 정보를 제공합니다.

![enter image description here](https://developer.android.com/images/ui/notifications/notification-basic_2x.png?hl=ko)

안드로이드에서의 가장 기본적인 형태의 알람은 아이콘, 제목, 내용 등이 포함이 됩니다.
또한 클릭이 되면 그 앱에 해당되는 이벤트를 설정할 수 있습니다. (PendingIntent)

### #1 Notification 채널 만들기

Android 8.0 이상에서 알림을 제공하려면 앱의 알림 채널을 만들어 시스템에 등록해야합니다.

``` kotlin
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) 
}  
}
```

Android 8.0 이상에서 알림을 게시하려면 알림을 만들어야 하므로 앱이 시작하자마자 이 코드를 실행해야 합니다. 기존 알림 채널을 만들면 아무 작업도 실행되지 않으므로 이 코드를 반복적으로 호출하는 것이 안전합니다.


### #2 Notification Builder 생성자

알림을 시작하려면 Notification.Builder 객체를 활용하여 컨텐츠와 채널을 설정해야합니다.

```kotlin
var builder = NotificationCompat.Builder(this, CHANNEL_ID)  
.setSmallIcon(R.drawable.notification_icon)  
.setContentTitle(textTitle)  
.setContentText(textContent)  
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
```

-   [setSmallIcon()](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder?hl=ko#setSmallIcon(int))으로 설정한 작은 아이콘. 사용자가 볼 수 있는 유일한 필수 콘텐츠입니다.
-   [setContentTitle()](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder?hl=ko#setContentTitle(java.lang.CharSequence))로 설정한 제목
-   [setContentText()](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder?hl=ko#setContentText(java.lang.CharSequence))로 설정한 본문 텍스트
-   [setPriority()](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder?hl=ko#setPriority(int))로 설정한 알림 우선순위. 우선순위에 따라 Android 7.1 이하에서 알림이 얼마나 강제적이어야 하는지가 결정됩니다. (Android 8.0 이상의 경우 다음 섹션에 표시된 채널 중요도를 대신 설정해야 합니다.)

### #3 Notification 탭 이벤트

모든 알림은 일반적으로 앱에서 알림에 상응하는 활동을 열려면 탭에 응답해야 합니다. 이 작업을 하려면 [PendingIntent](https://developer.android.com/reference/android/app/PendingIntent?hl=ko) 객체로 정의된 콘텐츠 인텐트를 지정하여 [setContentIntent()](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder?hl=ko#setContentIntent(android.app.PendingIntent))에 전달해야 합니다.


``` kotlin
  // Create an explicit intent for an Activity in your app  
  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)
```


### #4 Notification 표시

알림을 표시하려면 [NotificationManagerCompat.notify()](https://developer.android.com/reference/androidx/core/app/NotificationManagerCompat?hl=ko#notify(int,%20android.app.Notification))를 호출하여 알림의 고유 ID와 [NotificationCompat.Builder.build()](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder?hl=ko#build())의 결과를 전달합니다.

``` kotlin
with(NotificationManagerCompat.from(this))  {  
// notificationId is a unique int for each notification that you must define 
notify(notificationId, builder.build())  
}
```