0Pricing
Android Academy · 강의

Cloud Messaging으로 푸시 알림 보내기

FCM 알림을 보내고 받습니다.

Cloud Messaging으로 푸시 알림 보내기은(는) CoddyKit의 무료 Android Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Android Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Android Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

Cloud Messaging이란 무엇인가요?

Firebase Cloud Messaging (FCM)은 앱이 닫혀 있을 때도 앱에 푸시 알림과 데이터 메시지를 전달합니다.

작동 방식은 간단합니다.

  • 앱이 설치될 때마다 고유한 등록 토큰이 발급됩니다.
  • 서버(또는 Firebase 콘솔)가 해당 토큰이나 주제로 메시지를 보냅니다.
  • FCM이 메시지를 기기로 전달하면 기기가 메시지를 표시하거나 처리합니다.

Messaging 의존성 추가하기

FCM은 앞에서 설정한 BoM이 버전을 관리하는 firebase-messaging 라이브러리에 포함되어 있습니다.

BoM이 있으면 버전 번호를 지정할 필요가 없습니다.

// app/build.gradle.kts
dependencies {
    implementation(platform("com.google.firebase:firebase-bom:33.1.0"))
    implementation("com.google.firebase:firebase-messaging")
}

알림 권한

Android 13 (API 33) 이상에서는 알림을 게시하려면 런타임 권한인 POST_NOTIFICATIONS가 필요합니다.

매니페스트에 권한을 선언한 다음 런타임에 요청합니다. 권한을 허용받지 못하면 알림이 조용히 삭제됩니다.

<!-- AndroidManifest.xml -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

권한 요청하기

Activity Result API를 사용해 런타임에 POST_NOTIFICATIONS를 요청합니다. API 33 이상에서만 요청하고, 이전 버전에서는 권한이 암시적으로 부여됩니다.

import android.Manifest
import android.os.Build
import androidx.activity.result.contract.ActivityResultContracts

val requestPermission = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { granted ->
    println(if (granted) "Notifications allowed" else "Notifications denied")
}

fun askNotificationPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        requestPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
    }
}

등록 토큰

각 설치에는 대상을 식별하는 고유한 FCM 토큰이 있습니다. Firebase.messaging.token으로 가져옵니다.

특정 기기로 푸시할 수 있도록 이 토큰을 백엔드로 보냅니다. 토큰은 변경될 수 있으므로 항상 가장 최신 토큰을 기준값으로 사용해야 합니다.

import com.google.firebase.Firebase
import com.google.firebase.messaging.messaging
import kotlinx.coroutines.tasks.await

suspend fun currentToken(): String {
    return Firebase.messaging.token.await()
}

Messaging 서비스

메시지를 받으려면 FirebaseMessagingService를 상속합니다. 들어오는 페이로드를 처리하려면 onMessageReceived를 재정의하고, 토큰이 갱신될 때 반응하려면 onNewToken을 재정의합니다.

FCM 인텐트 필터와 함께 매니페스트에 서비스를 등록합니다.

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

class MyFcmService : FirebaseMessagingService() {

    override fun onNewToken(token: String) {
        // Upload the fresh token to your backend
        sendTokenToServer(token)
    }

    override fun onMessageReceived(message: RemoteMessage) {
        val title = message.notification?.title ?: "New message"
        val body = message.notification?.body ?: ""
        showNotification(title, body)
    }

    private fun sendTokenToServer(token: String) { /* ... */ }
    private fun showNotification(title: String, body: String) { /* ... */ }
}

서비스 등록하기

Android가 서비스로 메시지를 전달할 수 있도록 매니페스트에 서비스를 선언합니다. MESSAGING_EVENT 인텐트 필터가 필요합니다.

<!-- AndroidManifest.xml inside <application> -->
<service
    android:name=".MyFcmService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

알림 메시지와 데이터 메시지

FCM 메시지는 두 가지 유형으로 나뉩니다.

  • 알림 메시지 — 앱이 백그라운드에 있으면 FCM이 알림 창에 자동으로 표시합니다. onMessageReceived는 앱이 포그라운드에 있을 때만 실행됩니다.
  • 데이터 메시지 — 항상 키/값 맵으로 onMessageReceived에 전달되므로 처리 방식을 직접 제어할 수 있습니다.

message.data에서 사용자 지정 필드를 읽습니다.

import com.google.firebase.messaging.RemoteMessage

fun handle(message: RemoteMessage) {
    val type = message.data["type"]      // your custom field
    val itemId = message.data["itemId"]
    when (type) {
        "chat" -> openChat(itemId)
        "promo" -> openPromo(itemId)
    }
}
fun openChat(id: String?) {}
fun openPromo(id: String?) {}

알림 채널 만들기

Android 8부터는 모든 알림에 채널이 필요합니다. 앱 시작 시 한 번 생성하면 시스템이 채널을 사용해 소리, 중요도, 채널별 사용자 설정을 제어합니다.

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context

fun createChannel(context: Context) {
    val channel = NotificationChannel(
        "messages",
        "Messages",
        NotificationManager.IMPORTANCE_HIGH
    )
    val manager = context.getSystemService(NotificationManager::class.java)
    manager.createNotificationChannel(channel)
}

알림 표시하기

채널 ID에 연결된 알림을 NotificationCompat.Builder로 만든 다음 NotificationManagerCompat으로 게시합니다.

API 33 이상에서는 사용자가 POST_NOTIFICATIONS를 허용한 경우에만 알림이 표시된다는 점을 기억하세요.

import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat

fun showNotification(context: Context, title: String, body: String) {
    val notification = NotificationCompat.Builder(context, "messages")
        .setSmallIcon(android.R.drawable.ic_dialog_info)
        .setContentTitle(title)
        .setContentText(body)
        .setAutoCancel(true)
        .build()

    NotificationManagerCompat.from(context).notify(1, notification)
}

주제 구독

개별 토큰을 관리하는 대신 주제로 여러 사용자에게 메시지를 전송할 수 있습니다. 클라이언트가 주제 이름을 구독하면 서버가 구독한 모든 사용자에게 한 번에 메시지를 보냅니다.

news, sports, all-users와 같은 공지에 유용합니다.

import com.google.firebase.Firebase
import com.google.firebase.messaging.messaging
import kotlinx.coroutines.tasks.await

suspend fun subscribeToNews() {
    Firebase.messaging.subscribeToTopic("news").await()
}

suspend fun unsubscribeFromNews() {
    Firebase.messaging.unsubscribeFromTopic("news").await()
}

빠른 확인

앱이 백그라운드에 있고 FCM에서 순수한 알림 메시지를 받았습니다. 어떤 일이 일어날까요?

복습: Cloud Messaging

이제 푸시 알림으로 사용자에게 도달할 수 있습니다.

  • firebase-messaging을 추가하고 API 33 이상에서 POST_NOTIFICATIONS를 요청합니다.
  • 설치마다 FCM 토큰이 발급되며, 이를 서버에 업로드합니다.
  • FirebaseMessagingService를 상속하고 onMessageReceived / onNewToken을 재정의합니다.
  • 알림 메시지와 데이터 메시지의 차이를 이해합니다.
  • 알림 채널을 만들고 NotificationCompat으로 알림을 구성하거나 주제를 통해 메시지를 전송합니다.

이제 Firebase의 세 가지 핵심 기능인 Auth, Firestore, Messaging을 모두 살펴보았습니다. Android 앱을 위한 완전한 백엔드가 갖춰진 것입니다.

자주 묻는 질문

“Cloud Messaging으로 푸시 알림 보내기” 강의는 무료인가요?

네 — “Cloud Messaging으로 푸시 알림 보내기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Android Academy 강의 전체를 잠금 해제할 수 있습니다. Android Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“Cloud Messaging으로 푸시 알림 보내기”에서 뭘 배우나요?

FCM 알림을 보내고 받습니다. 브라우저에서 직접 실행하는 실습 코드로 Android Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Android Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Android Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“Cloud Messaging으로 푸시 알림 보내기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Android Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Android Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Firebase 설정
  2. Firebase 인증
  3. Cloud Firestore 기초
  4. Cloud Messaging으로 푸시 알림 보내기
← Android Academy(으)로 돌아가기