[kotlin] 코틀린을 사용한 실시간 알림 기능 구현

본 문서에서는 코틀린을 사용하여 실시간 알림이 포함된 애플리케이션을 개발하는 방법을 다룹니다.

목표

이 문서의 목표는 다음과 같습니다:

  1. 코틀린 언어로 안드로이드 애플리케이션을 개발하는 방법을 이해한다.
  2. Firebase Cloud Messaging (FCM) 을 사용하여 실시간 알림을 구현하는 방법을 학습한다.
  3. 사용자에게 알림을 전달하는 푸시 알림을 구현한다.

사전 요구사항

이 문서를 이해하기 위해서는 다음이 요구됩니다:

구현 단계

1. Firebase 프로젝트 설정

먼저, Firebase Console 에서 새 프로젝트를 만들고 안드로이드 애플리케이션을 설정합니다. 그리고 FCM을 활성화하여 Server keySender ID를 획득합니다.

2. 안드로이드 프로젝트 설정

Android Studio를 열고 새로운 빈 안드로이드 프로젝트를 만듭니다. 그런 다음, Firebase SDK를 추가하고 FCM 설정 파일을 포함시킵니다.

3. FCM 메시지 수신용 서비스 구현

코틀린으로 FCM 메시지를 수신하기 위한 서비스를 구현합니다. 이를 통해 백그라운드에서 앱으로 푸시 알림을 수신할 수 있습니다.

import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // 수신한 알림에 대한 처리 로직을 작성합니다.
    }
}

4. 푸시 알림 표시

FCM 메시지를 수신하고 사용자에게 푸시 알림을 표시하는 방법을 구현합니다.

import android.app.NotificationManager
import android.app.NotificationChannel
import android.os.Build
import android.content.Context
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.RemoteMessage
import androidx.core.content.ContextCompat.getSystemService

class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // 알림 생성
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel("default", "Default", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        val notification = NotificationCompat.Builder(this, "default")
            .setContentTitle(remoteMessage.notification?.title)
            .setContentText(remoteMessage.notification?.body)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .build()

        // 알림 표시
        notificationManager.notify(0, notification)
    }
}

5. 기기 등록 토큰 처리

사용자 기기의 FCM 토큰을 검색하고 서버에 등록하여 푸시 알림을 보낼 수 있도록 준비합니다.

결론

이제 알림 기능을 구현하기 위한 기본적인 단계를 마쳤습니다. 위의 단계에 따라 코틀린을 사용하여 안드로이드 애플리케이션에 실시간 알림 기능을 추가할 수 있습니다.

참고 자료

Happy coding!