가만 보면, 클라우드 메시징과 인앱 메시지 이렇게 두 개가 있다.
과거의 나는 그냥 지나쳤다. 뭐 둘다 메시지 이겠거니
하지만 둘은 다르다.
FCM이라고 불리는 Cloud Message는 주 기능은 '푸시 알림'이다.
사용자가 앱을 사용 중이든 아니든 알림을 보낸다.
- 플랫폼에 상관 없이 API에 맞춰 메시지를 보낼 수 있다.
인앱 메시지(In-App Messaging)는 사용자가 앱을 사용 중인 경우에만 표출이 가능하다.
그리고 사용자가 특정 동작이나 상태를 충족할 때 메시지를 표시할 수 있다.
- 주 목적은 사용자 경험을 개선하거나 특정 기능을 소개하는 용도로 사용된다.
그래서 FCM과는 다르게 전체적인 메시지가 아닌 특정 사용자에게 메시지를 보낸다.
우선 앱을 보낼 때 토큰을 등록을 해주어야 하는데
이녀석 파이어베이스 설명에 있는 깃헙 들어가보면 단순하게 Log만 찍히는 거다...
도대체 서버에 토큰 등록은 어떻게 하는 것일까

무튼.. 뭔가 등록하는 함수가 있나보다.. 이거 찾다가 진도가 나가질 않는구나
MyFirebaseMessagingService에 'onMessageReceived' 오버라이드 함수를 작성해주고 로그를 찍어본다

그리고 파이어베이스 메시지에서 메시지 전송 테스트를 해보자.
[캠페인 만들기]
[알림] (인앱X)
그리고 알림 제목, 메시지만 작성하고

다음 다음하여 '검토'를 누르고 로그캣 창을 잠시 바라본다.
그러면 메시지가 온다...!!
[보낸 시각] : 오전 9시 56분 57초

[도착 시각] : 09시 58분 24초
2023-11-24 09:58:24.546 13824-13954 cavedwellers kr....ers.firebasecloudmessagingapp V [MyFirebaseMessagingService.kt:24] onMessageReceived.. message:com.google.firebase.messaging.RemoteMessage@aea9a
2023-11-24 09:58:24.547 13824-13954 cavedwellers kr....ers.firebasecloudmessagingapp V [MyFirebaseMessagingService.kt:25] onMessageReceived.. message:{}
약 2분 정도 걸린다.
메시지 내용은 보이지가 않는다.. 파싱을 해야 하는 걸까?
파이어 베이스 메시지 수신 쪽 문서를 살펴보자
링크 : https://firebase.google.com/docs/cloud-messaging/android/receive?hl=ko&authuser=0
Android 앱에서 메시지 수신 | Firebase 클라우드 메시징
Google I/O 2023에서 Firebase의 주요 소식을 확인하세요. 자세히 알아보기 의견 보내기 Android 앱에서 메시지 수신 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. F
firebase.google.com
문득, 의문점이 든다. MyFirebaseMessagingService를 따론 startService함수를 타지 않았는데
어떻게 실행될까..
최초 Firebase관련 실행 함수는 토큰을 등록해주는 동작(FirebaseMessaging)밖에 없다.
해당 동작을 한 이후 MyFirebaseMessagingService는 onCreate되지 않지만,
Firebase에서 테스트 메시지를 전송하면 해당 시점에서 onCreate되고 onMessageReceived가 된다.

토큰이 Firebase Server에 등록되었고, 마치 하드웨어 MAC을 타겟하는 방식 같다.
해당 토큰에 데이터를 전송하고, Manifest에 intent-filter를 패키지 매니저가 실행시킨 것 같다.
한 번 홈화면에서 테스트해보자.
[새로운 메시지]

흠.. 전송은 되었다고 하는데.. 로그에서 표시 되질 않는다.
무튼 가이드를 따라가보자
엇 ... 10시 37분 23초에 도착했다...

이제 포그라운드, 백그라운드 상황에서 표시할 알람(NotifiactionBuilder)를 만들면 될 것 같다.
-- 테스트 해본 결과 파이어베이스에서 친절하게 Service자체가 실행되면,
따로 BroadCast Receiver라든가.. 타지 않고, 동작되도록 해놓았다.
FCM에서 발송하면 속도는 느리지만, 직접 URL을 쏘면 굉장히 빠르다.
우선, 알림(Notification)을 만드는 코드
private fun sendNotification(titleMsg: String, contentMsg: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val requestCode = 0
val pendingIntent = PendingIntent.getActivity(
this,
requestCode,
intent,
PendingIntent.FLAG_IMMUTABLE
)
val channelId = "fcm_default_channel"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(titleMsg)
.setContentText(contentMsg)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// since android Oreo API 26
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
val notificationId = 0
notificationManager.notify(notificationId, notificationBuilder.build())
}
onMessageReceived함수에서 알람을 실행해주면 된다.
FCM 캠페인으로 전송하는 것이 아닌 직접 전송하는 방법
[Post]
: https://fcm.googleapis.com/fcm/send
[Authorization]
: No Auth
[Headers]
: FCM API KEY는 프로젝트 설정 - 클라우드 메시징에 API Key가 있다
Key="Authorization" / Value="key=[FCM API KEY]"
Key="Content-Type" / Value="application/json"
[Body]
{
"registration_ids":["tokenId"],
"notification": {
"title": "titleText",
"body": "bodyText"
},
"data": {
"key1": "value1",
"key2": "value2"
}
}
AndroidManifest에 Service를 등록하면 푸시 알림 수신시 자동으로 서비스가 실행되며 동작한다...
왜 내 기억 속엔 Manifest에는 컴포넌트를 등록해주고 실행을 원한 경우에 startService 또는 bindService를 기억하고 있었다... 흠흠... 무튼 그러하다.
그리고 푸시 알림을 보내면 아주 잘 받는다. 포그라운드, 백그라운드 모두^^
근데 백그라운드인 경우 onCreate만 호출되고 무슨 값을 받았는지는 로그가 찍히지 않았다.
푸시 알림을 보낼 때 마다 onCreate가 호출 되었다.
'dev > aos' 카테고리의 다른 글
[AOS] 라이브러리 Github, JitPack연결 (0) | 2023.11.28 |
---|---|
[AOS] 뒤로가기시 안내 팝업창(Dialog) 띄우기 (0) | 2023.11.28 |
[AOS] FCM(Firebase Cloud Messaging) 구축 (0) | 2023.11.23 |
[AOS] 초록줄, 노란줄 제거 방법 (0) | 2023.11.22 |
[AOS] 빌더 패턴 Builder Pattern 작성 (0) | 2023.11.17 |