Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Forked from volodia-chornenkyy/OwnPushService.java
Last active February 18, 2021 11:25
Show Gist options
  • Save yongjhih/cbd646f6740e166db6d64930cbdc7a8f to your computer and use it in GitHub Desktop.
Save yongjhih/cbd646f6740e166db6d64930cbdc7a8f to your computer and use it in GitHub Desktop.
Handling of multiple FirebaseMessagingService
class FirebaseMessagingProxyService : FirebaseMessagingService() {
private val messagingServices: List<FirebaseMessagingService> by lazy {
listOf(FlutterFirebaseMessagingService())
.onEach { it.injectContext(this) }
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d(TAG, "onNewToken: token")
messagingServices.forEach { it.onNewToken(token) }
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
Log.d(TAG, "from: ${remoteMessage.from}")
Log.d(TAG, "data: ${remoteMessage.data}")
Log.d(TAG, "notification: ${remoteMessage.notification}")
messagingServices.forEach { it.onMessageReceived(remoteMessage) }
}
override fun onDeletedMessages() {
super.onDeletedMessages()
Log.d(TAG, "onDeletedMessages")
messagingServices.forEach { it.onDeletedMessages() }
}
override fun onMessageSent(message: String) {
super.onMessageSent(message)
Log.d(TAG, "onMessageSent: ${message}")
messagingServices.forEach { it.onMessageSent(message) }
}
override fun onSendError(message: String, e: Exception) {
super.onSendError(message, e)
Log.d(TAG, "onSendError: ${message}", e)
messagingServices.forEach { it.onSendError(message, e) }
}
}
fun <T : Service> T.injectContext(context: T, func: T.() -> Unit = {}) {
setField("mBase", context)
func()
}
fun Class<*>.findDeclaredField(name: String): Field? {
var clazz: Class<*>? = this
do {
try {
return clazz?.getDeclaredField(name)
} catch (e: Throwable) {}
clazz = clazz?.superclass
} while (clazz != null)
return null
}
fun Any.setField(name: String, value: Any): Boolean =
javaClass.findDeclaredField(name)?.let {
try {
it.isAccessible = true
it.set(this, value)
true
} catch (e: Throwable) { false }
} ?: false
val Any.TAG: String
get() {
val tag = javaClass.simpleName
val max = 23
return if (tag.length <= max) tag else tag.substring(0, max)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment