FirebaseMessagingService를 상속받은 MyFirebaseMessagingService 클래스 생성
import android.app.NotificationChannel
import android.app.NotificationManager
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService() : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
// Create the NotificationChannel.
val name = "채팅 알림"
val descriptionText = "채팅 알림입니다."
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(getString(R.string.default_notification_channel_id), name, importance)
mChannel.description = descriptionText
// Register the channel with the system. You can't change the importance
// or other notification behaviors after this.
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
val body = message.notification?.body ?: ""
val notificationBuilder = NotificationCompat.Builder(applicationContext, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.baseline_chat_24)
.setContentTitle(getString(R.string.app_name))
.setContentText(body)
notificationManager.notify(0, notificationBuilder.build())
}
override fun onNewToken(token: String) {
super.onNewToken(token)
}
}
FirebaseMessagingService를 확장하는 서비스를 추가
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
onCreate 함수에서 askNotificationPermission() 호출
private fun askNotificationPermission() {
// This is only necessary for API level >= 33 (TIRAMISU)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
) {
// FCM SDK (and your app) can post notifications.
} else if (shouldShowRequestPermissionRationale(POST_NOTIFICATIONS)) {
showPermissionRationalDialog()
} else {
// Directly ask for the permission
requestPermissionLauncher.launch(POST_NOTIFICATIONS)
}
}
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun showPermissionRationalDialog() {
AlertDialog.Builder(this)
.setMessage("알림 권한이 없으면 알림을 받을 수 없습니다.")
.setPositiveButton("권한 허용하기") { _, _ ->
requestPermissionLauncher.launch(POST_NOTIFICATIONS)
}.setNeutralButton("취소") { dialogInterface, _ ->
dialogInterface.cancel()
}.show()
}
Firebase.messaging.token.addOnCompleteListener {
val token = it.result
}
1) 콘솔 > 프로젝트 선택 > 왼쪽 바에서 "실행" > Messaging > 첫번째 캠페인 > Friebase 메시지 온보딩 > Firebase 알림 메시지
2) 테스트 메시지 전송
3) FCM 토큰 입력 후 테스트 버튼 클릭
4) 기기 상에서 알림 확인
Firebase Cloud Messaging API(V1) (관련 문서 링크)
1) 서버 엔드포인트 업데이트 (POST 방식)
https://fcm.googleapis.com/v1/projects/Firebase프로젝트ID/messages:send
Firebase 프로젝트 ID는 Firebase 콘솔의 일반 프로젝트 설정 탭에서 이 ID를 확인할 수 있다.
2) Authorization
Authorize 버튼을 클릭 - 구글 계정으로 로그인 -
"Firebase 애플리케이션 메시지 보내기 및 메시지 구독 관리" 허용 하여 토큰을 얻어온다.
3) Body > raw 창에 FCM TOKEN 정보 및 테스트 메시지를 입력 후 Send 버튼을 누른다.
{
"message":{
"token":"${FCM_TOKEN}",
"notification":{
"body":"안녕",
"title":"테스트"
}
}
}
4) 기기 상에서 알림 확인