will come true

[Android/Kotlin] 상태바 알림(Notification), 채널(Channel) 본문

Android

[Android/Kotlin] 상태바 알림(Notification), 채널(Channel)

haehyun 2022. 1. 5. 17:22

상태 바

상태 바는 화면 상단에 현재 시간, 네트워크, 배터리 정보 등을 표시하는 공간으로써 원래 시스템이 관리하는 곳이기 때문에 앱이 직접 제어할 수 없는 영역이다. 그러나 우리는 알림을 위해 제공하는 API를 이용해 각종 앱에서 푸시 알림을 수신할 수 있다.

 

알림 채널(Channel)

API 레벨 26버전(Oreo) 부터 추가된 개념, 앱의 알림을 카테고리(채널)별로 구분할 수 있도록 한다.
이전까지는 하나의 앱에 대해서 1. 알림 받기 / 2. 알림 받지 않기 두 가지 밖에 설정할 수 없었지만, 채널 개념이 생기고부터는 하나의 앱이 발생시키는 알림들 중 특정 알림만 선택적으로 받는 것이 가능해졌다.

[설정] → [애플리케이션] → [애플리케이션 정보] → [알림] 으로 들어가면 채팅 알림, 키워드 알림, 서비스 알림 등 알림이 세분화되어 있으며 각각의 항목에 대해 개별적으로 알림받기를 설정할 수 있다.

 

알림 생성 과정

1. 기기 버전 체크 

Channel 자체가 SDK 26 부터 생긴 개념이기 때문에 이전 버전에서는 Channel로 알림을 표시하지 않는다. 앱 호한성을 고려해 버전 체크후 두가지 방식으로 알림 표시 작업 수행

  • SDK 26 이상 → 채널 사용 O
  • SDK 26 미만 → 채널 사용 X

2. NotificationChannel

  • NotificationChannel 채널 생성
  • NotificationChannel setter 함수로 채널 정보 설정 (채널 설명문, 배지 알림음, 불빛, 진동 등)
  • NotificationManager에 채널 등록

3. NotificationCompat.Builder

  • NotificationChannel의 channelId로 NotificationCompat.Builder 생성
  • NotificationCompat.Builder setter 함수로 알림 정보 설정 (스몰 아이콘, 알림 시각, 제목, 내용)

4. Notification 

  • NotificationComapt.Builder로 Notification 객체 생성

5. NotificationManager

  • Notification객체를 매개변수로 NotificationManager.notify() 함수 실행

 

소스 코드

[MainActivity.kt] - 앱 실행 시 푸시알림 표시

package com.example.androidlab

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.graphics.Color
import android.media.AudioAttributes
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 알림
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val builder: NotificationCompat.Builder

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 채널 생성
            val channelId = "one-channel"
            val channelName = "My Channel One"
            val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)

            // 채널 정보 설정
            channel.description = "My Channel One Description"      // 채널 설명
            channel.setShowBadge(true)                              // 배지 표시
            val uri: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            val audioAttributes = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build()
            channel.setSound(uri, audioAttributes)                      // 알림음 재생
            channel.enableLights(true)                              // 불빛 표시
            channel.lightColor = Color.RED                              // 불빛 색상
            channel.enableVibration(true)                       // 진동 울림
            channel.vibrationPattern = longArrayOf(100, 200, 100, 200)  // 진동 패턴

            // 채널을 NotificationManager에 등록
            manager.createNotificationChannel(channel)

            // 채널 Id로 NotificationCompat.builder 생성
            builder = NotificationCompat.Builder(this, channelId)
        } else {
            builder = NotificationCompat.Builder(this)
        }

        // 알림 정보 설정
        builder.setSmallIcon(android.R.drawable.ic_notification_overlay)    // 스몰 아이콘
        builder.setWhen(System.currentTimeMillis())     // 알림 시각
        builder.setContentTitle("Content Title")        // 타이틀
        builder.setContentText("Content Massage")       // 내용

        val notification: Notification = builder.build()
        manager.notify(11, notification)
    }
}

Comments