Android - 알림(Notification)

2024. 7. 17. 16:22[개발]/Kotlin 활용 앱 개발

# 개념

- 앱의 UI와 별도로 사용자에게 앱과 관련된 정보를 보여주는 기능

 

# 알림 채널

- Android 8.0 이상부터는 알림을 만들기 전에 알림 채널부터 만들어야 함

- 알림 채널은 알림을 그룹화해 알림 활성화 / 알림 방식 변경 등을 할 수 있음

private val myNotificationID = 1
private val channelID = "default"

// 알림 채널 생성 메서드 구현
private fun createNotificationChannel() {
	// Android 8.0 이상일 때
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Android 8.0
        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)
    }
}

 

# 알림 생성

- NotificationCompat.Builder 객체에서 알림에 대한 UI 정보와 작업을 지정

- NotificationCompat.Builder.build()를 통해 Notification 객체를 반환

- 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())
}

 

# 알림 중요도

= 채널 중요도(Android 8.0 이상) / 알림 우선순위(Android 7.1 이하) 

 

# 알림 확장뷰 - 긴 텍스트

builder.setStyle(NotificationCompat.BigTextStyle().bigText(resources.getString(R.string.long_notification_body)))

 

# 알림 확장뷰 - 이미지

val bitmap = BitmapFactory.decodeResource(resources, R.drawable.android_hsu)
val builder = NotificationCompat.Builder(this, channelID)
	.setSmallIcon(R.mipmap.ic_launcher)
    .setLargeIcon(bitmap)
    .setContentTitle("Notification Title")
    .setContextText("Notification Body")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setStyle(NotificationCompat.BigPictureStyle()
    	.bigPicture(bitmap)
        .bigLargeIcon(null) // hide largeIcon while expanding

 

# 알림 확장뷰 - 버튼 추가

// Action 버튼을 누르면 intent로 TextActivity가 시작되는 코드
val intent = Intent(this, TestActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val builder = NotificationCompat.Builder(this, channelID)
	.setSmallIcon(R.mipmap.ic_launcher)
    .setContentTitle("Notification Title")
    .setContentText("Notification Text")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .addAction(R.drawable.android_hsu, "Action", pendingIntent)
NotificationManagerCompat.from(this).notify(myNotificationID, builder.build())

 

# 알림 확장뷰 - 프로그레스 바 

val builder = NotificationCompat.Builder(this, channelID)
	.setSmallIcon(R.mipmap.ic_launcher)
    .setContentTitle("Title")
    .setContentText("Text")
    // setProgress의 파라미터
    // 1. max: Int = 프로그래스 바의 최대값 / 작업이 완료되면 뜨는 숫자
    // 2. progress:Int = 현재 진행 상태
    // 3. indeterminate: Boolean = true는 현재 진행 상태가 안보임, false는 보임
    .setProgress(100, 0, false)
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
NotificationManagerCompat.from(this).notify(myNotificationID, builder.build())

Thread {
	for (i in 1..100).step(10) {
    	Thread.sleep(10000
        builder.setProgress(100, i, false)
        NotificationManagerCompat.from(this)
        	.notify(myNotificationID, builder.build())
    }
    builder.setContentText("Completed")
    	.setProgress(0, 0, false)
    NotificationManagerCompat.from(this)
    	.notify(myNotificationID, builder.build())
}.start()

 

# 알림에 액티비티를 연결

?