이 가이드에서는 메시지를 안정적으로 수신할 수 있도록 모바일 및 웹 클라이언트 앱에서 Firebase Cloud Messaging을 설정하는 방법을 설명합니다.
메시지를 수신하려면 FirebaseMessagingService
를 확장하는 서비스를 사용하면 됩니다.
서비스에서 onMessageReceived
및 onDeletedMessages
콜백을 재정의해야 합니다. 전체 예시는 Firebase 클라우드 메시징 빠른 시작 샘플을 참고하세요.
onMessageReceived
는 다음 경우를 제외하고 대부분의 메시지 유형에 제공됩니다.
앱이 백그라운드에서 실행되고 있을 때 전송된 알림 메시지: 이 경우 알림이 기기의 작업 표시줄로 전송됩니다. 사용자가 알림을 탭하면 기본적으로 앱 런처가 열립니다.
알림과 데이터 페이로드가 둘 다 포함된 메시지(백그라운드에서 수신된 경우): 이 경우 알림은 기기의 작업 표시줄로 전송되고 데이터 페이로드는 런처 활동의 인텐트 부가 정보로 전송됩니다.
요약하면 다음과 같습니다.
앱 상태 | 알림 | 데이터 | 모두 |
---|---|---|---|
포그라운드 | onMessageReceived |
onMessageReceived |
onMessageReceived |
배경 | 작업 표시줄 | onMessageReceived |
알림: 작업 표시줄 데이터: 인텐트 부가 정보 |
메시지 유형에 대한 자세한 내용은 알림 및 데이터 메시지를 참조하세요.
onMessageReceived
콜백은 실행 기간이 짧습니다. OS 지연, 앱 시작 시간, 다른 작업에 의해 차단되는 기본 스레드 또는 긴 시간이 소요되는 이전 onMessageReceived
호출 등 많은 요인이 이 기간에 영향을 미칠 수 있습니다.
따라서 onMessageReceived
에서는 장기 실행 작업(예: 알림에 표시할 이미지를 서버에서 가져오기)을 피하고 대신 WorkManager
를 사용하여 완료하는 데 몇 초 이상 걸릴 수 있는 작업을 처리하는 작업을 예약해야 합니다. 메시지 우선순위와 처리 방식에 미치는 영향에 관한 자세한 내용은 높은 우선순위 및 보통 우선순위 메시지의 메시지 처리를 참고하세요.
앱 매니페스트 수정
FirebaseMessagingService
를 사용하려면 앱 매니페스트에 다음을 추가해야 합니다.
<service
android:name=".java.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
알림의 모양을 맞춤설정하는 기본값을 설정하는 것이 좋습니다. 커스텀 기본 아이콘 및 색상을 지정하여 알림 페이로드에 해당 값이 설정되지 않았을 때 항상 지정된 값이 적용되게 할 수 있습니다.
application
태그 안에 다음 줄을 추가하여 커스텀 기본 아이콘 및 색상을 설정합니다.
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
Android는 다음 경우에 커스텀 기본 아이콘을 표시하고 사용합니다.
- 알림 작성기에서 보낸 모든 알림 메시지
- 알림 페이로드에 아이콘이 명시적으로 설정되지 않은 모든 알림 메시지
커스텀 기본 아이콘이 설정되지 않았고 알림 페이로드에도 아이콘이 설정되지 않았으면 Android에서 애플리케이션 아이콘을 흰색으로 렌더링해 표시합니다.
onMessageReceived
재정의
FirebaseMessagingService.onMessageReceived
메서드를 재정의하면 수신된 RemoteMessage 객체를 기준으로 작업을 수행하고 메시지 데이터를 가져올 수 있습니다.
Kotlin
override fun onMessageReceived(remoteMessage: RemoteMessage) { // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: ${remoteMessage.from}") // Check if message contains a data payload. if (remoteMessage.data.isNotEmpty()) { Log.d(TAG, "Message data payload: ${remoteMessage.data}") // Check if data needs to be processed by long running job if (needsToBeScheduled()) { // For long-running tasks (10 seconds or more) use WorkManager. scheduleJob() } else { // Handle message within 10 seconds handleNow() } } // Check if message contains a notification payload. remoteMessage.notification?.let { Log.d(TAG, "Message Notification Body: ${it.body}") } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. }
Java
@Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); if (/* Check if data needs to be processed by long running job */ true) { // For long-running tasks (10 seconds or more) use WorkManager. scheduleJob(); } else { // Handle message within 10 seconds handleNow(); } } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. }
onDeletedMessages
재정의
경우에 따라 FCM에서 메시지를 전송하지 못할 수 있습니다. 특정 기기가 연결될 때 앱에서 대기 중인 메시지가 너무 많거나(100개 초과) 기기가 한 달 넘게 FCM에 연결되지 않으면 이 문제가 발생합니다. 이러한 경우 FirebaseMessagingService.onDeletedMessages()
에 대한 콜백을 받을 수 있습니다. 이 콜백을 수신한 앱 인스턴스는 앱 서버에 전체적으로 동기화를 실시해야 합니다. 해당 기기의 앱으로 메시지를 보낸 지 4주 이상 경과한 경우 FCM은 onDeletedMessages()
를 호출하지 않습니다.
백그라운드 앱에서 알림 메시지 처리
앱이 백그라운드 상태이면 Android에서 알림 메시지를 작업 표시줄로 전송합니다. 사용자가 알림을 탭하면 기본적으로 앱 런처가 열립니다.
여기에는 알림과 데이터 페이로드가 둘 다 포함된 메시지 및 알림 콘솔에서 보낸 모든 메시지가 포함됩니다. 이러한 경우 알림은 기기의 작업 표시줄로 전송되고 데이터 페이로드는 런처 활동의 인텐트 부가 정보로 전송됩니다.
앱으로 전송된 메시지에 관한 자세한 내용은 Apple 및 Android 기기에서 열린 전송 메시지 수와 Android 앱의 '노출수'(사용자에게 표시된 알림) 데이터가 기록된 FCM 보고 대시보드를 확인합니다.