Skip to content

Instantly share code, notes, and snippets.

@samuelchou
Created December 3, 2021 16:48
Show Gist options
  • Save samuelchou/75a17c77076555f174996d00c75e7888 to your computer and use it in GitHub Desktop.
Save samuelchou/75a17c77076555f174996d00c75e7888 to your computer and use it in GitHub Desktop.
Android - Firebase Cloud Messaging, More Customization for background messages.
package studio.ultoolapp.firebaselab
import android.util.Log
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import java.util.*
class CustomMessagingService : FirebaseMessagingService() {
companion object {
private const val TAG = "CustomMessagingService"
const val INTENT_FCM = "com.google.android.c2dm.intent.RECEIVE"
const val INTENT_FCM_DIRECT_BOOT = "com.google.android.c2dm.intent.RECEIVE_DIRECT_BOOT"
}
/**
* called ONLY when app is running in foreground.
*/
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
val nContent: String = p0.notification?.run {
"title: $title / body: $body / image: $imageUrl / link: $link"
} ?: "[No Notification Content]"
Log.d(TAG, "onMessageReceived: received ${p0.messageType}\nN: $nContent\nD: ${p0.data}")
// show a dialog, or something that can be done inside app.
}
/**
* called EVERYTIME when a FCM is sent, no matter app is in foreground or background.
*/
override fun handleIntent(p0: Intent?) {
p0?.run {
Log.v(TAG, "handleIntent: detect intent: $action / $extras")
} ?: run {
Log.v(TAG, "handleIntent: called with null intent.")
}
p0?.let { intent ->
if (INTENT_FCM == intent.action || INTENT_FCM_DIRECT_BOOT != intent.action) {
// it's a standard FCM. data is just inside extras.
// do whatever you'd like...
// for example
intent.extras.run {
val title: String? = getString("gcm.notification.title")
val content: String? = getString("gcm.notification.body")
val optionalImageUrl: String? = getString("gcm.notification.image")
val sentTime: Long = getLong("google.sent_time", Date().time)
val customDataSetFromFCMConsole: String? = getString("custom_field")
}
}
}
// NOTE: onMessageReceived will STILL be called if app is in foreground.
super.handleIntent(p0)
}
}
@samuelchou
Copy link
Author

samuelchou commented Apr 7, 2022

Oh damn, I wrote it wrong. line:40 should be INTENT_FCM == intent.action || INTENT_FCM_DIRECT_BOOT == intent.action
2 equality!

ref: https://www.jianshu.com/p/79b07772aedd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment