푸시 알림
Firebase Cloud Messaging으로 푸시 알림을 보냅니다. FCM을 설정하고 알림 채널을 만들며 작업이 포함된 알림을 구성하고 포그라운드와 백그라운드 전송을 처리합니다.
푸시 알림은(는) CoddyKit의 무료 Android Academy 강의입니다. 이것은 6개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Android Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Android Academy 강의에는 총 6개의 강의가 포함되어 있습니다.
푸시 알림이란 무엇입니까?
푸시 알림을 사용하면 앱이 포그라운드에 있지 않아도 서버에서 사용자에게 메시지를 보낼 수 있습니다. 일반적인 사용 사례는 다음과 같습니다.
- 새 메시지 알림
- 주문 상태 업데이트
- 긴급 뉴스
- 알림 및 프로모션
Android에서는 Firebase Cloud Messaging (FCM)이 표준 푸시 전송 서비스입니다.
FCM 개요
Firebase Cloud Messaging (FCM)의 흐름은 다음과 같습니다.
- 앱이 처음 실행될 때 FCM에 등록되고 기기 토큰을 받습니다.
- 앱이 토큰을 서버로 보냅니다.
- 푸시를 보내야 할 때 서버가 FCM으로 메시지를 보냅니다.
- FCM이 기기로 메시지를 전달합니다.
FCM은 무료이고 안정적이며 앱이 종료된 상태에서도 작동합니다.
프로젝트에 Firebase 추가하기
Firebase를 추가하는 단계는 다음과 같습니다.
- Firebase Console로 이동하여 프로젝트 추가 → Android 앱 추가를 선택합니다.
- 패키지 이름으로 앱을 등록합니다.
google-services.json을 다운로드하여app/에 배치합니다.- 플러그인과 의존성을 추가합니다.
// project/build.gradle:
buildscript {
dependencies { classpath 'com.google.gms:google-services:4.4.1' }
}
// app/build.gradle:
plugins { id 'com.google.gms.google-services' }
dependencies {
implementation platform('com.google.firebase:firebase-bom:32.7.4')
implementation 'com.google.firebase:firebase-messaging-ktx'
}FCM 권한(Android 13 이상)
Android 13(API 33)부터는 위험한 권한과 마찬가지로 런타임에 POST_NOTIFICATIONS 권한을 요청해야 합니다.
<!-- AndroidManifest.xml -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
// In Activity (Android 13+):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
}FirebaseMessagingService
수신되는 FCM 메시지와 토큰 갱신을 처리하는 서비스를 만듭니다.
class MyFirebaseService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
// Send token to your backend to enable push delivery
sendTokenToServer(token)
}
override fun onMessageReceived(message: RemoteMessage) {
val title = message.notification?.title ?: "New Message"
val body = message.notification?.body ?: ""
showNotification(title, body)
}
}Manifest에 서비스 등록하기
AndroidManifest.xml에 서비스를 선언합니다.
<service
android:name=".MyFirebaseService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>알림 채널(Android 8 이상)
Android 8(Oreo)부터 알림은 반드시 채널에 할당해야 합니다. 사용자는 채널별로 소리, 진동, 중요도를 제어할 수 있습니다.
fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"messages_channel", // channel ID
"Messages", // user-visible name
NotificationManager.IMPORTANCE_HIGH
).apply {
description = "Incoming message notifications"
enableVibration(true)
}
val manager = context.getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(channel)
}
}알림 만들고 표시하기
Android 버전 간 호환성을 위해 NotificationCompat.Builder를 사용합니다.
fun showNotification(context: Context, title: String, body: String) {
val intent = Intent(context, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notification = NotificationCompat.Builder(context, "messages_channel")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true) // dismiss on tap
.setContentIntent(pendingIntent) // open app on tap
.build()
NotificationManagerCompat.from(context)
.notify(System.currentTimeMillis().toInt(), notification)
}작업이 있는 알림
사용자가 앱을 열지 않고도 작업을 수행할 수 있도록 알림에 작업 버튼을 추가합니다.
val replyIntent = Intent(context, ReplyReceiver::class.java)
val replyPending = PendingIntent.getBroadcast(
context, 1, replyIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val notification = NotificationCompat.Builder(context, "messages_channel")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("New message from Alice")
.setContentText("Hey, are you coming?")
.addAction(R.drawable.ic_reply, "Reply", replyPending)
.addAction(R.drawable.ic_dismiss, "Dismiss", null)
.build()포그라운드와 백그라운드 처리 비교
FCM은 앱 상태에 따라 다르게 동작합니다.
- 앱이 포그라운드에 있는 경우 —
onMessageReceived()가 호출되며, 직접 알림을 만들고 표시합니다. - 앱이 백그라운드에 있거나 종료된 경우 — FCM이
notification페이로드에서 알림을 자동으로 표시하며,onMessageReceived는 호출되지 않습니다.
항상 onMessageReceived에서 추가 데이터를 받으려면 data 페이로드에 넣으십시오(notification에는 넣지 마십시오).
FCM 토큰 가져오기
서버로 보낼 현재 FCM 토큰을 가져옵니다.
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w("FCM", "Fetching token failed", task.exception)
return@addOnCompleteListener
}
val token = task.result
Log.d("FCM", "Token: $token")
// Send token to your server
sendTokenToServer(token)
}빠른 확인
앱이 백그라운드에 있을 때 FCM이 'notification' 페이로드가 포함된 메시지를 전달하면 어떻게 됩니까?
복습: 푸시 알림
Android에서 FCM으로 푸시 알림을 구현하는 방법은 다음과 같습니다.
- Firebase,
google-services.json,firebase-messaging-ktx추가 - Android 13 이상에서
POST_NOTIFICATIONS요청 FirebaseMessagingService생성 →onNewToken+onMessageReceived- Android 8 이상을 위한
NotificationChannel생성 NotificationCompat.Builder로 알림 생성onMessageReceived에서 항상 받으려면 data 페이로드 사용
다음 내용에서는 WorkManager로 백그라운드 작업을 예약합니다.
자주 묻는 질문
“푸시 알림” 강의는 무료인가요?
네 — “푸시 알림” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Android Academy 강의 전체를 잠금 해제할 수 있습니다. Android Academy 강의에는 총 6개의 강의가 포함되어 있습니다.
“푸시 알림”에서 뭘 배우나요?
Firebase Cloud Messaging으로 푸시 알림을 보냅니다. FCM을 설정하고 알림 채널을 만들며 작업이 포함된 알림을 구성하고 포그라운드와 백그라운드 전송을 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 Android Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Android Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Android Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 6개 중 4번째 강의입니다.
“푸시 알림” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Android Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Android Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.