24.02.28 Firebase FCM 알림 받기

KSang·2024년 2월 28일
0

TIL

목록 보기
74/101

메세지 보냈는데, 알림이 떠야 상대방이 알것이다.

파이어베이스에선 FCM을 지원해 알림을 보낼수 있다.

파이어베이스에서 알림 보내는 방법을 알아보자

우선 gradle에서 FCM관련 의존성을 추가해줘야 한다.

gradle.kt

    //FCM 라이브러리
    implementation ("com.google.firebase:firebase-messaging:23.4.1")
    implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
    implementation ("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")

manifest에서도 권한을 허용해주자

AndroidManifest.xml

        <service
            android:name=".infrastructure.notify.FirebaseMessagingService"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

FirebaseMessagingService는 알림을 받아주는 클래스다.

FirebaseMessagingService() 안드로이드 스튜디오 에서 지원해주는대, FCM알림을 받고 그에 맞는 액션을 취해줄 수 있다.

의존성 추가하고, 권한을 허용했다면 이제 알림을 설정 해주자

class FirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)
    }
    
    override fun onNewToken(s: String ) {
    super.onNewToken(s)
    }

onMessageReceived는 기기에서 푸시 메시지를 수신 받았을시 작동한다.

onNewToken은 기기의 토큰이 바뀌었을 때 작동한다.

보통 onNewToken에서는 서버로 변경된 키값을 전달한다.

메세지를 받았을 때 알림이 뜨게 해보자

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // 서버에서 직접 보낼때
        if (remoteMessage.notification != null) {
            sendNotification(
                remoteMessage.notification?.title,
                remoteMessage.notification?.body!!
            )
        }
        
        ...
    private fun sendNotification(title: String?, body: String) {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) // 액티비티 중복 생성 방지
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
        ) // 일회성

        val channelId = "channel" // 채널 아이디
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) // 소리
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setContentTitle(title) // 제목
            .setContentText(body) // 내용
            .setAutoCancel(true)
            .setSmallIcon(ic_notify)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)

        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        val channel = NotificationChannel(
            channelId,
            "Channel human readable title",
            NotificationManager.IMPORTANCE_DEFAULT
        )
        notificationManager.createNotificationChannel(channel)

        notificationManager.notify(0, notificationBuilder.build()) // 알림 생성
    }

서버에서 메세지를 직접보낼때 notification.title과 body로 메세지의 제목 내용을 받을 수 있다.

이 데이터로 notify를 만들어주면 된다.

FirebaseMessagingService는 이제 어디서 선언함? MainActivity?
FirebaseMessagingService는 시스템이 자동으로 시작하며, FCM 메시지를 수신할 준비가 된다.
명시적으로 따로 선언해서 시작할 필욘 없다.

이제 콘솔에서 전체 유저한테 메세지를 보내보자

콘솔에서 클라우드 메세지를 누르면 알림을 작성 할 수 있다.

여기서 전체 유저한테 알림을 보내면 받아지는걸 볼 수 있다.

0개의 댓글