본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 알림(Notification) 기능 만들기

by teamnova 2021. 4. 17.

Notification(알림)이란?

 

사용자에게 미리 알림을 주고 다른 사람과의 소통을 가능하게 하며 앱에서 보내는 기타 정보를 적시에 제공하기 위해 Android가 앱의 UI 외부에 표시하는 메시지입니다.

 

[참고]

developer.android.com/guide/topics/ui/notifiers/notifications?hl=ko


알림 기능을 만들어 보겠습니다.

 

먼저 예제에 사용할 화면을 만들어 보겠습니다.

 

<activity_main.xml>

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="94dp"
        android:layout_height="38dp"
        android:text="메인 화면"
        android:textAlignment="center"
        android:textSize="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.34" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알림 기능 실행"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.568" />

</androidx.constraintlayout.widget.ConstraintLayout>

다음 코드를 작성해 보겠습니다.

 

스틱코드를 활용한다면, 클래스에서 'b' 까지만 작성했을 때 '버튼 이벤트 생성' 이벤트가 나타납니다.

 

 

'버튼 이벤트 생성' 이벤트를 누를 경우 코드가 자동으로 완성이 됩니다.

 

 

여기서는 버튼의 아이디 값만 입력을 해주시면 됩니다.

 

다음 알림을 보내기 위해 알림을 생성하는 코드를 작성해보겠습니다.

 

 

'알림 정보 생성' 이벤트를 누를 경우 코드가 자동으로 완성이 됩니다.

 

this , 뒤에는 받을 채널 아이디로 사용할 String값, icon에는 사용할 이미지 정보, title에는 사용할 제목, text에는 보낼 내용을 입력해주시면 됩니다.

 

다음 알림을 받기 위해 채널을 등록하는 코드를 작성해보겠습니다.

 

'알림 채널 등록' 이벤트를 누를 경우 코드가 자동으로 완성이 됩니다.

 

채널 id, 채널 이름, 등 필요한 값을 넣으면, 알림을 받기위한 코드가 완성이 됩니다.

 

<최종코드>

import android.os.Build
import android.app.NotificationManager
import android.app.NotificationChannel
import android.content.Context
import androidx.core.app.NotificationCompat
import android.widget.Button
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {

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

        var button = findViewById(R.id.button) as Button
        button.setOnClickListener {
            var builder = NotificationCompat.Builder(this, "MY_channel")
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentTitle("알림 제목")
                    .setContentText("알림 내용")

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 오레오 버전 이후에는 알림을 받을 때 채널이 필요
                val channel_id = "MY_channel" // 알림을 받을 채널 id 설정
                val channel_name = "채널이름" // 채널 이름 설정
                val descriptionText = "설명글" // 채널 설명글 설정
                val importance = NotificationManager.IMPORTANCE_DEFAULT // 알림 우선순위 설정
                val channel = NotificationChannel(channel_id, channel_name, importance).apply {
                    description = descriptionText
                }

                // 만든 채널 정보를 시스템에 등록
                val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                notificationManager.createNotificationChannel(channel)

                // 알림 표시: 알림의 고유 ID(ex: 1002), 알림 결과
                notificationManager.notify(1002, builder.build())
            }
        }
    }
}

프로젝트를 실행하면 버튼을 누를 경우 알림이 오는 것을 확인할 수 있습니다.

 

 

사용한 스틱코드

[Kotlin][Android] 알림 기능 만들기)  stickode.com/detail.html?no=2048