※ 패키지 이름 android studio 에서 만든 프로젝트 이름과 동일해야함
1) 프로젝트 수준 build.gradle
id 'com.google.gms.google-services' version '4.3.8' apply false
2) 앱 수준 build.gradle
plugins {
id 'com.google.gms.google-services'
}
dependencies {
implementation platform('com.google.firebase:firebase-bom:32.4.0')
implementation 'com.google.firebase:firebase-messaging:23.2.1'
}
apply plugin: 'com.google.gms.google-services'
3) FirebaseMessagingService를 상속받은 MyFirebaseMessagingService.class 작성
package com.jjgate.fcmtest
import android.R
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.net.Uri
import android.util.Log
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import java.net.URLDecoder
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
Log.d("FCMLog", "Refreshed token: " + token);
// 보통은 기기에 저장...코드 작성
}
override fun onMessageReceived(message: RemoteMessage) {
// notification
if(message.notification != null) { //포그라운드
sendNotification(message.notification?.title!!, message.notification?.body!!);
}
// data
if (message.data.isNotEmpty()) { //백그라운드
message.data["title"]?.let { sendNotification(it, message.data["body"]!!) };
}
}
// FCM 푸시 메시지를 앱에서 알림
private fun sendNotification(title: String, body: String) {
Log.d("FCMLog", "호출")
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 chId = "myChId"
val chName = "myChName"
val soundUri: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notiBuilder: NotificationCompat.Builder = NotificationCompat.Builder(this, chId)
.setSmallIcon(R.mipmap.sym_def_app_icon)
.setContentTitle(title)
.setContentText(body)
.setContentTitle(URLDecoder.decode(title, "UTF-8"))
.setContentText(URLDecoder.decode(body, "UTF-8"))
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(chId, chName, NotificationManager.IMPORTANCE_HIGH)
manager.createNotificationChannel(channel)
manager.notify(0, notiBuilder.build())
}
}
4) AndroidManifest.xml
인터넷 퍼미션과 작성한 FirebaseMessagingService를 상속받은 MyFirebaseMessagingService.class를 등록한다
<uses-permission android:name="android.permission.INTERNET"/>
<service android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.RESPOND_VIA_MESSAGE"/>
</intent-filter>
</service>
package com.jjgate.fcmtest
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.Task
import com.google.firebase.FirebaseApp
import com.google.firebase.messaging.FirebaseMessaging
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// FCM SDK 초기화
FirebaseApp.initializeApp(this);
FirebaseMessaging.getInstance().token
.addOnCompleteListener { task: Task<String> ->
if (!task.isSuccessful) {
Log.w("FCMLog", "Fetching FCM registration token failed", task.exception)
return@addOnCompleteListener
}
val token = task.result
Log.d("FCMLog", "Current token: $token")
}
}
}
1) 프로젝트 개요 옆 톱니 > 프로젝트 설정 > 일반 탭 > 프로젝트ID 확인
-> 나중에 통신할 주소값에 넣어주어야함
2) Authorization에 사용 할 Access token 얻기
Google Developers에 OAuth 2.0 Playground에 접속
https://developers.google.com/oauthplayground
3) 포스트맨에서 테스트
※프로젝트 ID는 위 1번에서 확인 한 ID 넣어주면 됨
{
"message": {
"token": "FCM_TOKEN", // 안드로이드 스튜디오에서 얻은 FCM token 넣기
"notification": {
"body": "Body of Your Notification in data",
"title": "Title of Your Notification in data"
}
}
}