Android Kotlin 如何在 FirebaseMessagingService onMessageReceived 上更新当前 activity 中的内容?

Android Kotlin How to update content in current activity on FirebaseMessagingService onMessageReceived?

场景是当用户打开聊天 activity 并且之后收到 firebase 聊天数据通知。下面的代码,

class myFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // how do i update chat content here?
        // startActivity with FLAG_ACTIVITY_NEW_TASK will restart the activity
        // startActivity with FLAG_ACTIVITY_REORDER_TO_FRONT will crash the app
        // or is there a way to call a method in chat activity to update it's content?
    }
}

如何在当前打开的聊天中更新聊天内容activity/screen?

您可以在聊天中添加一个侦听器activity,当收到通知时通知

创建新文件:

class NotificationReceivedListener {

    var listener: OnNotificationReceivedListener? = null

    interface OnNotificationReceivedListener{
        fun onNotificationReceived(bundle: Bundle?)
    }

    fun setOnNotificationReceivedListener(param: OnNotificationReceivedListener) {
        listener = param
    }

    fun notificationReceived(bundle: Bundle?){

        listener?.let {
            it.onNotificationReceived(bundle)
        }
    }

}

在 FirebaseMessagingService 伴随对象中:

var notificationReceivedListener = NotificationReceivedListener()

在 onMessageReceived 中:

notificationReceivedListener.notificationReceived(payloadBundle)

在activity中:

MyFirebaseMessagingService.notificationReceivedListener.setOnNotificationReceivedListener(object :
NotificationReceivedListener.OnNotificationReceivedListener {
                    override fun onNotificationReceived(args: Bundle?) {
                          activity!!.runOnUiThread( {...})
            }