뚜벅이!
Mobile :)
뚜벅이!
전체 방문자
오늘
어제
  • 분류 전체보기 (52)
    • 코딩테스트 (16)
      • programmers level1 (7)
      • codility (9)
    • 프로그래밍 공부 (31)
      • Spring Boot (6)
      • Nuxt.js (5)
      • Node.js (3)
      • Etc (11)
      • Android (6)
    • 잡다한 글 (3)
    • 토이프로젝트 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Notification
  • node
  • AndroidX
  • lesson4
  • 연습
  • Jetpack
  • lesson2
  • NavBar
  • 프로그래머스
  • Spring
  • Spring boot
  • JS
  • nuxt
  • docker
  • token
  • lesson3
  • javascript
  • codillity
  • 부트
  • Vue
  • programmers
  • node.js
  • Kotlin
  • level1
  • 초보자
  • ad
  • Vue.js
  • nuxt.js
  • firebase
  • 스킬체크테스트

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
뚜벅이!

Mobile :)

프로그래밍 공부/Android

[android-kotlin] firebase notification / message

2022. 7. 14. 16:54
728x90

 

2021.07.27 - [프로그래밍 공부/Spring Boot] - [Java] spring boot - firebase message server

 

[Java] spring boot - firebase message server

이제는 없으면 안되는 firebase. 웹에서 작성한 알림메세지를 서버로 전송하여 각각의 디바이스로 뿌려주는 간단한 코드를 작성하고자 한다. 대략 플로우는 이런식이다. Web ( notification UI/UX ) -> Spri

ttubeoki.tistory.com

 

이전 포스팅에서 백단에서의 메세지요청을 만들었으니,

앱에서의 메세지받는 코드를 작성해보자.

우선 디펜던시부터 받아오고~

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

 

 

 

manifest에 service를 등록해주자

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

 

여기서, Android8.0 이상을 대상으로 한다면 채널을 우선 만들어 준다.

관련 내용에 대해서는 여기에 설명되어있다. https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels

 

알림 개요  |  Android 개발자  |  Android Developers

알림 개요 알림은 사용자에게 미리 알림을 주고 다른 사람과의 소통을 가능하게 하며 앱에서 보내는 기타 정보를 적시에 제공하기 위해 Android가 앱의 UI 외부에 표시하는 메시지입니다. 사용자

developer.android.com

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="news" />

 

 

채널등록을 한 후에, firebase token을 발급받고, initalize 하는 부분을 생성해보자.

private fun initFirebase(){
    LogUtil.i(TAG, "initFirebase start")
    FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
        if (!task.isSuccessful) {
            LogUtil.w(TAG, "Fetching FCM registration token failed", task.exception)
            return@OnCompleteListener
        }

        // Get new FCM registration token
        val token = task.result.toString()
        LogUtil.d(TAG,"fcm token :: $token")
    })

    FirebaseMessaging.getInstance().subscribeToTopic(
        PrefUtil.getPrivateString(this,/*your topic*/)
    )
}

firebase token을 발급받고 확인하는 코드이며, topic 주제를 주고받기 위해서는 아래와 같이 subscribeToTopic을 해주어야 한다.

 

 

 

 

그다음 Service단 FirebaseMessagingService를 extend해준다.

class FirebaseService : com.google.firebase.messaging.FirebaseMessagingService() {

    companion object {
        private val TAG = FirebaseService::class.java.simpleName
    }
    
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
    }
}

토큰이 새로 발급된다면 onNewToken으로 들어오게 되는데

폐쇄망같은 경우 firestore에 접근을 못할 수도 있기때문에

sendRegistrationToServer() 라는이름으로 함수를 만들어 서버에 저장한다.

 

 

 

그런데 지금은 딱히 그정도까지는 필요 없기 때문에 onMessageResceived만 작성해도 된다.

        LogUtil.i(TAG, "From: ${remoteMessage.from}")

        if (remoteMessage.data.isNotEmpty()) {
            LogUtil.i(TAG, "Message data payload: ${remoteMessage.data}")

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use WorkManager.
                //scheduleJob()
            } else {
                // Handle message within 10 seconds
                //handleNow()
            }
        }
        remoteMessage.notification?.let {
            LogUtil.d(TAG, "Message Notification Body: ${it.body}")

            showNotification(
                    context = this,
                    title = it.title,
                    message = it.body
            )
        }

끄읕

728x90
저작자표시 (새창열림)

'프로그래밍 공부 > Android' 카테고리의 다른 글

[android] context 란  (0) 2022.12.21
[android] migration 진행중 ... kotlin v, IDE v, library v...etc...  (0) 2022.03.29
[kotlin] LiveData & DataBinding  (0) 2021.07.20
[kotlin] Android jetpack Navigation  (2) 2021.05.14
[Android&Kotlin] gps tracking  (3) 2021.02.04
    '프로그래밍 공부/Android' 카테고리의 다른 글
    • [android] context 란
    • [android] migration 진행중 ... kotlin v, IDE v, library v...etc...
    • [kotlin] LiveData & DataBinding
    • [kotlin] Android jetpack Navigation
    뚜벅이!
    뚜벅이!
    2022. 4년차 안드로이드 개발자 wndnjs19@gmail.com

    티스토리툴바