android fcm

나고수·2022년 8월 15일
0

Android

목록 보기
29/109
post-thumbnail
class MyFirebaseMessagingService : FirebaseMessagingService() {

    private val TAG = "LOGGING"

	//백그라운드에서 푸시 알림을 받을때 포그라운드와 동일한 처리를 해주고 싶으면 handleIntent를 override 해야함 
    override fun handleIntent(intent: Intent) {
        try {
            if (intent.extras != null) {
                val builder = RemoteMessage.Builder("MyFirebaseMessagingService")
                for (key in intent.extras!!.keySet()) {
                    builder.addData(key!!, intent.extras!![key].toString())
                }
                onMessageReceived(builder.build())
            } else {
                super.handleIntent(intent)
            }
        } catch (e: Exception) {
            super.handleIntent(intent)
        }
    }

    override fun onMessageReceived(message: RemoteMessage) {
        super.onMessageReceived(message)
        Log.d("fcmTest", "${message.notification?.title}")
        Log.d("fcmTest", "${message.notification?.body}")
        Log.d("fcmTest", "${message.data["purchaseContentId"]}")
        Log.d("fcmTest", "${message.data["contentId"]}")
        Log.d("fcmTest", "${message.data["flowly"]}")
        createNotificationChannel() //채널 만들기 
        message.notification?.let {
            with(NotificationManagerCompat.from(this)) {
                notify(
                    Random.nextInt(),
                    createNotificationNormal(it.title ?: "", it.body ?: "", message.data) 
                    //알림 만들기
                )
            }
        }
    }

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

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = getString(R.string.channel_name)
            val descriptionText = getString(R.string.channel_description)
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val id = getString(R.string.channel_id)
            val channel = NotificationChannel(id, name, importance).apply {
                description = descriptionText
            }
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun createNotificationNormal(
        title: String,
        content: String,
        data: Map<String, String>?
    ): Notification {

        val intent = Intent(this, MainActivity::class.java).apply {
            if (!data.isNullOrEmpty()) {
                val args = Bundle()
                args.putString("purchaseContentId", data["purchaseContentId"])
                args.putString("contentId", data["contentId"])
                args.putString("flowly", data["flowly"])
                putExtra("bundle", args)
            }
            flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
        }
        val pendingIntent =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                PendingIntent.getActivity(
                    this,
                    100,
                    intent,
                    PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
                )
            } else {
                PendingIntent.getActivity(
                    this,
                    100,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT
                )
            }

        return NotificationCompat.Builder(this, getString(R.string.channel_id))
            .setSmallIcon(R.mipmap.nofi_icon)
            .setContentTitle(title)
            .setContentText(content)
            .setAutoCancel(true)
            .setChannelId(getString(R.string.channel_id))
            .setContentIntent(pendingIntent)
            .build()
    }

}

포그라운드에서 알림 받을 때

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        intent?.let {
            val bundle = it.extras?.getBundle("bundle")
            bundle?.let {
                val purchaseContentId = bundle.getString("purchaseContentId")!!
                val contentId = bundle.getString("contentId")!!
                val flowly = bundle.getString("flowly")!!
                disposeAlarm(purchaseContentId, contentId, flowly)
            }
            it.removeExtra("bundle")
        }
    }

백그라운드에서 알림 받을 때

  • onNewIntent가 아니라 onCreate()에서 적절히 처리

build.gradle 설정

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'com.google.gms.google-services' 👈
}

dependencies {
    //firebase
    implementation platform('com.google.firebase:firebase-bom:30.2.0')
    implementation 'com.google.firebase:firebase-messaging-ktx:23.0.5'
}
profile
되고싶다

1개의 댓글

comment-user-thumbnail
2023년 2월 5일

intent생성할때 message.data를 기준으로 parent activity가 메인 액티비티인 regular pending Intent를 만들면 되지 않을까? - 그러면 해당 액티비티 - (back) - 메인 액티비티 가 되니까.. 괜찮지 않을까?

답글 달기

관련 채용 정보