질문 정리

Firebase Cloud Messageing 수신 기능 구현(Compose)

five2week 2024. 8. 28. 15:45

문제 상황

사용자가 프로모션 알림을 앱을 사용하지 않을 때도 이러한 알림을 받을 수 있어야 합니다.

 

구현 순서

  1. firebase 프로젝트 생성 및 google-service.json 파일 다운로드
  2. 필요한 종속성을 build.gradle에 선언
  3. AndroidManifest에 service 추가
  4. FirebaseMessagingService을 상속 받아서 구현

 

구현 방법

Firebase Cloud Messaging을 활용하여 앱에서 프로모션 알림을 수신하고 처리하는 구현 방법을 다음 단계별로 설명합니다

 

 

1. 프로젝트 설정

  • google-services.json 파일을 프로젝트에 추가합니다.

  • 필요한 종속성을 build.gradle에 선언합니다.
// app
plugins {
    id("com.google.gms.google-services")
}

dependencies {
    implementation("com.google.firebase:firebase-messaging-ktx")		
}

// project
plugins {
    id("com.google.gms.google-services") version "4.4.0" apply false
}
  • AndroidManifest.xml에 service를 추가합니다.
<service
    android:name=".data.remote.FcmService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

 

 

 

2. FirebaseMessaging Service

  • FirebaseMessagingService를 상속 받아서 사용합니다.

 💡 onNewToken 메서드가 불리는 경우

  1. 앱 설치 시: 사용자가 앱을 처음 설치하고 실행할 때, 새로운 FCM 등록 토큰이 생성되며, 이 때 onNewToken이 호출됩니다.
  2. 앱 데이터 삭제 후 재설치 시: 사용자가 앱 데이터를 삭제하거나 앱을 제거했다가 다시 설치하는 경우, 기존의 토큰이 삭제되고 새 토큰이 발급될 때 이 메서드가 실행됩니다.
  3. 토큰이 갱신되는 경우: FCM 토큰은 주기적으로 갱신될 수 있습니다. 이는 보안을 유지하기 위해 필요한 절차로, 갱신 주기는 Firebase 서비스에 의해 관리됩니다.
  4. 앱의 보안 관련 설정 변경 시: 예를 들어, 사용자가 앱의 인스턴스 ID를 초기화하거나 FCM 관련 정보를 재설정하는 경우, 새로운 토큰이 필요하게 됩니다.
  5. 기기 설정 변경 시: 사용자가 Google 계정을 추가하거나 변경하는 등의 기기 설정을 수정할 때, FCM 시스템이 토큰을 새로 발급할 수 있습니다. 
@AndroidEntryPoint
class FcmService : FirebaseMessagingService() {
    @Inject
    lateinit var appPreferences: AppPreferences

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        LogUtils.d("new token : $token")
        appPreferences.saveFcmToken(token)
    }
}

 

 

 

3. 알림 메시지 처리

  • onMessageReceived 메서드를 오버라이드하여 수신된 메시지를 처리합니다.
  • 메세지의 종류는 알림 메세지와 데이터 메세지로 총 두 가지입니다.
  • 알림 메시지가 도착하면 시스템이 자동으로 알림을 생성하여 사용자에게 보여줍니다.
  • 데이터 메시지의 경우, 메시지에 포함된 데이터를 앱에서 직접 처리하고 필요한 작업을 수행합니다.
@AndroidEntryPoint
class FcmService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        LogUtils.d("From: ${remoteMessage.from}")

        // 알림 메시지인 경우
        if (remoteMessage.notification != null) {
            LogUtils.d("Message Notification Body: ${remoteMessage.notification?.body}")
            showNotification(remoteMessage.notification?.title, remoteMessage.notification?.body)
        }
    }

    private fun showNotification(title: String?, body: String?) {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val channel = NotificationChannel(
            FCM_NOTIFICATION_NAME,
            "Notification",
            NotificationManager.IMPORTANCE_HIGH
        )
        notificationManager.createNotificationChannel(channel)

        val notificationBuilder = NotificationCompat.Builder(this, FCM_NOTIFICATION_NAME)
            .setContentTitle(title ?: "Promotion Title")
            .setContentText(body ?: "Promotion Message")
            .setSmallIcon(android.R.drawable.ic_dialog_email)
            .setAutoCancel(true)

        notificationManager.notify(FCM_NOTIFICATION_ID, notificationBuilder.build())
    }
}

 

이러한 단계를 통해, 사용자가 앱을 사용하고 있지 않을 때도 프로모션 알림을 효과적으로 수신하고, 적절히 반응할 수 있도록 하는 시스템을 구축할 수 있습니다.

 

참고 링크

https://firebase.blog/posts/2023/08/adding-fcm-to-jetpack-compose-app/

 

The Firebase Blog

News, tutorials, and updates from the Firebase team.

firebase.blog

https://firebase.google.com/docs/cloud-messaging/android/client?hl=ko

 

Android에서 Firebase 클라우드 메시징 클라이언트 앱 설정

Google I/O 2023에서 Firebase의 주요 소식을 확인하세요. 자세히 알아보기 의견 보내기 Android에서 Firebase 클라우드 메시징 클라이언트 앱 설정 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐

firebase.google.com