코틀린(Kotlin)/TIL

[코틀린(Kotlin)] 알림

초보왕보초 2024. 1. 7. 18:01
728x90

알림

  • 앱의 UI와 별도로 사용자에게 앱과 관련한 정보를 보여주는 기능
  • 알림을 터치하여 해당 앱을 열 수 있다
    - Android 7.0부터는 문자답하기 같은 간단한 작업을 할 수 있다
  • 보통 단말기 상단 부분에 표시되고, Android 8.0부터는 앱 아이콘의 배지로도 표시된다

알림_예시

 

 

1. 알림 채널 (Android 8.0 이상)

  • Android 8.0 이상의 경우에는 알림을 만들기 전에 알림 채널을 먼저 만들어야 한다
  • 알림 채널은 알림을 그룹 하여 알림 활성화나 방식을 변경할 수 있다
  • 현재 앱이 실행 중인 안드로이드 버전을 확인하여 8.0 이상인 경우에만 채널 생성한다
private val myNotificationID = 1
private val channelID = "default"

private fun createNotificationChannel() {
	// 안드로이드 버전이 8.0 이상인지 체크
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.0){
    	// 채널ID와 채널 이름, 중요도가 있는 Notification이라는 채널을 만들어준다
    	val channel = NotificationChannel(channelID, "default channel", 
        	NotificationManager.IMPORTANCE_DEFAULT)
        // 채널에 대한 설명
        channel.description = "description text of this channel."
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

 

 

2. 알림 생성

  1. .NotificationCompat.Builder 객체에서 알림에 대한 UI정보와 작업을 지정
    - setSmanllIcon() : 작은 아이콘
    - setContentTitle() : 제목
    - setContentText() : 세부 텍스트
  2. .NotificationCompat.Builder.build() 호출
    - Notification 객체를 반환
  3. NotificationManagerCompat.notify()를 호출해서 시스템에 Notification 객체를 전달
private val myNotificationID = 1

private fun showNotification() {
	val builder = NotificationCompat.Builder(this, channelID)
    	// 알림 아이콘 설정
    	.setSmallIcon(R.mipmap.ic_launcher)
        // 알림 제목 설정
        .setContentTitle("Title")
        // 알림 세부 텍스트 설정
        .setContentText("Notification Text")
        // 알림 중요도 설정
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    NotificationManagerCompat.from(this).notify(myNotificationID, builder.build())
}

 

 

3. 알림 중요도

  • 채널 중요도 (Android 8.0 이상)
    NotificationChannel
    - channelID, "defaultchannel", NotificationManager.IMPORTANCE_DEFAULT
  • 알림 우선순위 (Android 7.1 이하)
    NotificationCompat.Builder(this, channelID).setPriority(NotificationCompat.PRIORITY_DEFAULT)
  • 중요도 순위

중요도 순위

 

 

4-1. 알림 확장뷰 - 긴 텍스트

사전 작업

- 뷰 바인딩 추가

- activity_main.xml에 클릭 시 스테이터스 바에 알림이 뜨게 하도록 하는 버튼(btn_notification)을 생성해 준다

- 알림에서 클릭해서 호출할 SecondActivity를 생성해 준다

 

MainActivity.kt

더보기
package com.android.ex_view3_notification

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.AudioAttributes
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.NotificationCompat
import com.android.ex_view3_notification.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btnNotification.setOnClickListener {
            notification()
        }
    }

    fun notification() {
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        val builder: NotificationCompat.Builder
        // 안드로이드 버전이 8.0 이상인지 체크
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 26 버전 이상(Android 8.0 이상)일 때
            // 채널 ID
            val channelID = "one-channel"
            // 채널 이름
            val channelName = "My Channel One"
            // 채널 생성 (ID, 이름, 중요도)
            val channel = NotificationChannel(
                channelID,
                channelName,
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                // 채널에 다양한 정보 설정
                // 채널 설명
                description = "My Channel One Description"
                // 배지
                setShowBadge(true)
                // 알람이 울리는 링톤 (알림 오디오)
                val uri: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val audioAttributes = AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build()
                setSound(uri, audioAttributes)
                // 알림 진동
                enableVibration(true)
            }
            // 채널을 NotificationManager에 등록
            manager.createNotificationChannel(channel)

            // 채널을 이용하여 builder 생성
            builder = NotificationCompat.Builder(this, channelID)
        } else {
            // 26 버전 이하 (Android 버전이 8.0 이하일 때)
            builder = NotificationCompat.Builder(this)
        }

        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.notify)
        // 알림이 눌렸을 때 SecondActivity 호출
        val intent = Intent(this, SecondActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        // 알림의 기본 정보
        builder.run {
            // 알림 아이콘
            setSmallIcon(R.mipmap.ic_launcher)
            // 알림 발생시간
            setWhen(System.currentTimeMillis())
            // 알림 제목
            setContentTitle("새로운 알림입니다.")
            // 알림 세부 텍스트
            setContentText("알림이 보이시나요?")
            setStyle(
                NotificationCompat.BigTextStyle()
                    // 긴 텍스트 뷰
                    .bigText("긴 텍스트를 보기 위해 사용하는 스타일입니다. 긴 텍스트를 보기 위해 사용하는 스타일입니다.긴 텍스트를 보기 위해 사용하는 스타일입니다.긴 텍스트를 보기 위해 사용하는 스타일입니다.긴 텍스트를 보기 위해 사용하는 스타일입니다.긴 텍스트를 보기 위해 사용하는 스타일입니다.긴 텍스트를 보기 위해 사용하는 스타일입니다.긴 텍스트를 보기 위해 사용하는 스타일입니다.긴 텍스트를 보기 위해 사용하는 스타일입니다.긴 텍스트를 보기 위해 사용하는 스타일입니다. ")
            )

            // 큰 아이콘에 notify 이미지
            setLargeIcon(bitmap)
            // Action = 눌렀을 때 pendingIntent
            addAction(R.mipmap.ic_launcher, "Action", pendingIntent)
        }

        // 알림 실행
        manager.notify(11, builder.build())
    }
}

 

 

4-2. 알림 확장뷰 - 이미지 (setStyle만 바꾸면 된다)

더보기
    // 큰 이미지 뷰
    setStyle(
    	NotificationCompat.BigPictureStyle()
			.bigPicture(bitmap)
			.bigLargeIcon(null)
    )
728x90