ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [안드로이드] NotificationChannel
    카테고리 없음 2024. 4. 15. 09:40

    사용 이유

    API 26 이상부터 추가된 기능으로 알림을 보내려면 해당 기능을 적용해주어야 한다.


    사용법

    해당 메서드에서 원하는 기능을 추가 후 NotificationManager에 등록해주면 된다.

    같은 ID의 NotificationChannel은 한번만 등록되니 필자는 메인 액티비티에서 실행되도록 했다.

    fun initNotificationChannel() {
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val notificationChannel = NotificationChannel(
            "ChannelId",
            "ChannelName",
            NotificationManager.IMPORTANCE_DEFAULT
        ).apply {
            val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            val audioAttributes = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build()
            setSound(uri, audioAttributes)
        }
        notificationManager.createNotificationChannel(notificationChannel)
    }

    여기서 알림을 날릴 때 기존 방식에선 Context만 넣던 NotificationCompat.Builder의 인자에
    채널 ID를 추가로 넣어주면 된다.

    fun showNotification() {
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val notification = NotificationCompat.Builder(this, "ChannelId").apply {
            setSmallIcon(R.drawable.ic_launcher_foreground)
            setWhen(System.currentTimeMillis())
            setContentTitle(getString(R.string.notification_title))
            setContentText(getString(R.string.notification_description))
        }.build()
        notificationManager.notify(1, notification)
    }
Designed by Tistory.