관리 메뉴

나만을 위한 블로그

[Android] 코틀린으로 FCM 푸시 알림 보내는 법 본문

Android

[Android] 코틀린으로 FCM 푸시 알림 보내는 법

참깨빵위에참깨빵 2021. 5. 23. 18:03
728x90
반응형

자바로 FCM을 구현하는 방법은 아래의 포스팅 참고

https://onlyfor-me-blog.tistory.com/183

 

[Android] FCM 푸시 알림 보내는 법(+PHP에서 cURL 라이브러리 써서 FCM 푸시 알림 보내는 법)

FCM : 파이버베이스 클라우드 메시징의 이니셜이다. 이전에 GCM(구글 클라우드 메시징)이란 이름이었고 현재는 안드로이드, 아이폰, 웹 앱의 메시지와 메시지 알림을 위한 크로스 플랫폼 클라우드

onlyfor-me-blog.tistory.com

 

코틀린을 공부하던 도중 FCM을 구현하는 방법을 알게 되어 기록하려고 한다.

SHA-1 키를 구하는 방법까지는 위의 포스팅을 참고해도 문제없다. 그러나 앱을 실행하기 위해 앱을 키고 화면을 이리저리 이동해야 하는 절차는 없어졌다! 코틀린만 그런 건지 모르겠지만 이 절차가 없어지니 너무 편하다.

아래 글을 따라하기 전 패키지명 중간에 example이 없는지 꼭 확인한다. 있다면 다른 글자로 바꿔준다. FCM이 동작하지 않을 수 있다.

 

이제 의존성을 추가해야 한다. 코틀린이니까 자바와는 다른 의존성 문구를 추가해줘야 한다.

먼저 프로젝트 수준 gradle 파일을 아래와 같이 변경한다. 아래의 의존성 문구는 오늘 날짜 기준으로 파이어베이스 공식 문서를 참고해 작성했으니 최신 버전의 의존성 문구를 원한다면 공식 홈페이지를 참고하기 바란다.

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.4.21"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.8' // <- 추가

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://devrepo.kakao.com/nexus/content/groups/public/' }
    }
}

다음은 앱 수준 gradle 파일에 아래의 의존성을 추가해준다.

implementation platform('com.google.firebase:firebase-bom:28.0.1')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-messaging-ktx'

// 아래는 추가하지 않아도 상관없다. 내가 나중에 써야할 수도 있으니 미리 추가해둔 것이다
implementation 'com.google.firebase:firebase-core:17.2.2'
implementation 'com.google.firebase:firebase-auth:19.1.0'
implementation 'com.firebaseui:firebase-ui-auth:4.2.1'

다 붙여넣었다면 sync now를 눌러 변경점을 동기화해준다.

그리고 자바와 똑같이 MyFirebaseMessagingService라는 파일을 만들어줘야 한다.

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.media.RingtoneManager
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyFirebaseMessagingService: FirebaseMessagingService()
{
    private val TAG: String = this.javaClass.simpleName

    override fun onMessageReceived(remoteMessage: RemoteMessage)
    {
        super.onMessageReceived(remoteMessage)
        if (remoteMessage.notification != null)
        {
            sendNotification(remoteMessage.notification?.title, remoteMessage.notification!!.body!!)
        }
    }

    override fun onNewToken(token: String)
    {
        Log.d(TAG, "Refreshed token : $token")
        super.onNewToken(token)
    }

    // 받은 알림을 기기에 표시하는 메서드
    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 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT)

        val channelId = "my_channel"
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setContentTitle(title)
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // 오레오 버전 예외처리
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
    }

}

 

 

그리고 매니페스트에 위 파일을 등록한다. 서비스 태그로 등록해야 한다.

<service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

여기까지 했다면 끝이다. 시험삼아 파이어베이스 홈페이지에서 테스트 푸시 알림을 보내면 정상적으로 수신되고, 누르면 앱이 켜지는 걸 확인할 수 있다. 내 경우 약 20초 정도가 걸려서야 푸시 알림이 도착했다.

반응형
Comments