Add notifications to your app/About notifications

2024. 5. 21. 19:37IT/Android

728x90

알림

시의 적절한 정보를 제공하기 위해 Android가 앱 UI 외부에 표시하는 메세지로, 잠금화면과 상태 표시줄 알림창, 잠금 화면이 해제된 상태에서의 플로팅 창으로 표현이 가능하다.

 

알림 채널

사용자가 앱에서 발생할 수 있는 각각의 알림을 분류하고 설정하기 위해 Android 8.0 (API 수준 26)부터 도입된 개념으로, 알림 채널에 등록되지 않은 알림은 보내지지 않는다. 

 

알림 채널 만들고 등록 하는 법

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // Create the NotificationChannel.
    val name = getString(R.string.channel_name)
    val descriptionText = getString(R.string.channel_description)
    val importance = NotificationManager.IMPORTANCE_DEFAULT
    val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
    mChannel.description = descriptionText
    // Register the channel with the system. You can't change the importance
    // or other notification behaviors after this.
    val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.createNotificationChannel(mChannel)
}

*NotificationChannel() : 차례대로 고유 채널 ID, 채널 이름, 중요도를 전달하여 알림 채널 객체를 생성한다.

*getSystemService(NOTIFICATION_SERVICE) : 시스템 서비스를 얻기 위한 메서드로, 이를 사용하여 NotificationManager 객체를 가져온다.

*NotificationManager.createNotificationChannel() : 생성한 알림 채널을 등록한다.

 

설정 가능한 중요도 수준

 

사용자의 알림 채널 설정을 읽어 특정 설정에 맞는 작업을 정의할 수 있다.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    // Get the specific notification channel
    val notificationChannel = notificationManager.getNotificationChannel(CHANNEL_ID)
    if (notificationChannel != null) {
        // Get vibration pattern
        val vibrationPattern = notificationChannel.vibrationPattern
        if (vibrationPattern != null) {
            println("Vibration Pattern: ${vibrationPattern.joinToString()}")
        } else {
            println("Vibration Pattern: Not set")
        }

        // Get sound
        val soundUri = notificationChannel.sound
        if (soundUri != null) {
            println("Sound URI: $soundUri")
        } else {
            println("Sound URI: Not set")
        }

        // Get importance
        val importance = notificationChannel.importance
        println("Importance: $importance")
    } else {
        println("Notification channel not found")
    }

    // Get all notification channels
    val notificationChannels = notificationManager.getNotificationChannels()
    for (channel in notificationChannels) {
        println("Channel ID: ${channel.id}, Name: ${channel.name}, Importance: ${channel.importance}")
    }
}

*NotificationManager.getNotificationChannel() : 파라미터로 전달된 ID에 해당하는 알림 채널을 가져온다.

*NotificationManager.getNotificationChannels() : 모든 알림 채널을 가져온다.

 

사용자가 앱의 의도와 맞지 않는 알림 설정을 하는 경우, 변경을 위해 인텐트를 사용하여 시스템 설정으로 리디렉션 시킬 수 있다. 시스템 설정 화면의 메뉴는 개발자가 설정 UI를 통해 재구성할 수 있다.

val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS).apply {
    putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
    putExtra(Settings.EXTRA_CHANNEL_ID, myNotificationChannel.getId())
}
startActivity(intent)

*Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS : 알림 채널의 시스템 설정 화면.

*putExtra(Settings.EXTRA_APP_PACKAGE, packageName) : 앱의 패키지 이름을 지정.

*putExtra(Settings.EXTRA_CHANNEL_ID, myNotificationChannel.getId()) : 수정할 채널을 지정.

 

알림 채널을 삭제할 수 있다.

// The id of the channel.
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val id: String = "my_channel_01"
notificationManager.deleteNotificationChannel(id)

*NotificationManager.deleteNotificationChannel() : 파라미터로 전달된 ID에 해당하는 알림 채널을 삭제한다.

 

알림 채널 그룹을 생성하여 이름이 동일한 채널을 구분할 수 있다.

// The id of the group.
val groupId = "my_group_01"
// The user-visible name of the group.
val groupName = getString(R.string.group_name)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannelGroup(NotificationChannelGroup(groupId, groupName))
val channel = NotificationChannel(channelId, channelName, importance).apply {
    description = channelDescription
    setGroup(groupId) // Set the group ID to assign this channel to the group.
}

*NotificationManager.createNotificationChannelGroup() : 알림 채널 그룹 생성.

*NotificationChannel.setGroup() : 해당 알림 채널을 파라미터로 전달된 ID에 해당하는 채널 그룹에 등록한다.

 

 

알림 채널 : https://developer.android.com/develop/ui/views/notifications/channels?hl=ko&authuser=0

설정 UI : https://developer.android.com/develop/ui/views/components/settings?authuser=0&hl=ko

시스템 설정 화면 : https://developer.android.com/develop/ui/views/components/settings?authuser=0&hl=ko

728x90