반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Archives
Today
Total
관리 메뉴

코딩하기 좋은날

Android Notification (kotlin) 본문

Android

Android Notification (kotlin)

huiung 2020. 7. 12. 21:56
반응형

 

Notification 이란?

 

Android의 알림에 대해서 알아 보겠습니다. 휴대폰에서 최상단에서 밑으로 드래그를 하면 아래와 같은 알림이 뜬 상태바가 나오게 됩니다. 알림은 일반적으로 아래와 같이 구성 되어 있습니다.

 

출처 : 구글 공식 문서

 

알림 개요  |  Android 개발자  |  Android Developers

알림은 사용자에게 알림, 다른 사람과의 의사소통 또는 앱에서 보내는 시기적절한 기타 정보를 제공하기 위해 Android가 앱의 UI 외부에 표시하는 메시지입니다. 사용자는 알림을 탭하여 열거나 ��

developer.android.com

 

알림은 기본적으로 로컬알림과 원격알림이 존재하며 로컬 알림은 장치에서 앱을 통해 발생 하게 되고 원격 알림은 원격서버에서 장치로 전송하는 알림입니다.

 

우선은 로컬 알림을 한번 만들어 보겠습니다.

 

우선 안드로이드 8.0(오레오) 이상부터는 알림을 제공하기 위해서는 NotificationChannel 인스턴스를 createNotificationChannel에 전달을 해야 합니다. 따라서 해당 역할을 해주는 createNotificationChannel() 함수를 만들고 채널을 Create 해주어야 합니다.

 

 

기본적으로 알림은 NotificationCompat.Builder 를 통해 만들어 집니다. context 와 channelID를 생성자에 전달하고 .set... 메서드를 통해 아이콘, 제목, 내용, Intent 등등을 설정 할 수 있습니다. 

 

Intent를 설정 해주는 것은 해당 알림을 선택 했을 때 어떤 activity로 이동할지를 지정 해줍니다. 이때는

해당 Intent를 담은 PendingIntent 객체를 이용하여 설정 해주어야 합니다.

 


Local Notification

 

아래의 예제 프로그램에서는 알림을 클릭시 ResultActivity로 이동하게 되고, 버튼을 클릭시 총 3개의 알림이 발생하며 이들을 그룹화 하여 묶어서 보여주는 예제 입니다. 

 

그룹화는 setGroup 함수에 GroupKey를 전달하여 그룹으로 묶고 setGroupSummary() 메서드를 사용하여 해당 그룹의 요약된 알림을 제공하면 됩니다.

 

MainActivity.kt

package com.example.notificationexample

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val channelId = "my_channel"

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = getString(R.string.Channel_name)
            val descriptionText = getString(R.string.Channel_description)
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(channelId, name, importance).apply {
                description = descriptionText
            }

            val notificationManager: NotificationManager =
                    getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    fun sendNotification(view: View) {

        val GROUP_KEY_NOTIFY = "group_key_notify"

        val intent = Intent(this, ResultActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }

        val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

        val builder1 = NotificationCompat.Builder(this, channelId)
                .setSmallIcon(android.R.drawable.ic_dialog_info) //smallIcon
                .setContentTitle("Notification") //Title
                .setContentText("Notification example1!") //내용
                .setAutoCancel(true) //알림 클릭시 알림 제거 여부
                .setContentIntent(pendingIntent) //클릭시 pendingIntent의 Activity로 이동
                .setGroup(GROUP_KEY_NOTIFY)
                .addAction(android.R.drawable.sym_action_chat,
                        "OPEN", pendingIntent) //액션

        val builder2 = NotificationCompat.Builder(this, channelId)
                .setSmallIcon(android.R.drawable.ic_dialog_info) //smallIcon
                .setContentTitle("Notification") //Title
                .setContentText("Notification example2!") //내용
                .setAutoCancel(true) //알림 클릭시 알림 제거 여부
                .setContentIntent(pendingIntent) //클릭시 pendingIntent의 Activity로 이동
                .setGroup(GROUP_KEY_NOTIFY)

        val builder3 = NotificationCompat.Builder(this, channelId)
                .setSmallIcon(android.R.drawable.ic_dialog_info) //smallIcon
                .setContentTitle("Notification") //Title
                .setContentText("Notification example3!") //내용
                .setAutoCancel(true) //알림 클릭시 알림 제거 여부
                .setContentIntent(pendingIntent) //클릭시 pendingIntent의 Activity로 이동
                .setGroup(GROUP_KEY_NOTIFY)


        val buildersummary = NotificationCompat.Builder(this, channelId)
                .setSmallIcon(android.R.drawable.ic_dialog_info) //smallIcon
                .setContentTitle("Notification") //Title
                .setContentText("Notification summary!") //내용
                .setAutoCancel(true) //알림 클릭시 알림 제거 여부
                .setContentIntent(pendingIntent) //클릭시 pendingIntent의 Activity로 이동
                .setGroup(GROUP_KEY_NOTIFY)
                .setGroupSummary(true)

        val notificationId1 = 100
        val notificationId2 = 101
        val notificationId3 = 102
        val notificationId4 = 103
        NotificationManagerCompat.from(this).apply {
            notify(notificationId1, builder1.build())
            notify(notificationId2, builder2.build())
            notify(notificationId3, builder3.build())
            notify(notificationId4, buildersummary.build())
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        Log.d("Log", Build.VERSION_CODES.O.toString())
        createNotificationChannel()
    }
}

 버튼을 클릭할 경우 아래와 같이 알림이 묶여서 나오고 이를 밑으로 드래그 하면 각각의 알림이 나타나게 됩니다. 

참고로 Android 7.0 이상부터는 앱이 4개 이상의 알림을 보내면서 그룹을 지정하지 않으면 시스템에서 이러한 알림을 자동으로 그룹화한다고 합니다.


로컬 알림은 위와 같이 구현을 해주면 됩니다.

그러나 실제로 앱을 만들어서 서비스를 한다고 하면 클라이언트가 직접 알림을 띄우는 경우도 있겠지만 서버에서 원격으로 어떤 것을 알려주기 위해 알림을 보내는 경우가 더 많을 것입니다.

 

이러한 경우에는 firebase 의 FCM 기능을 이용하면 구현 할 수 있습니다. 

 

 

반응형