Firebase Cloud Messaging:即使应用程序终止,也可以从消息中解析数据

时间:2019-02-06 16:43:24

标签: android firebase dart flutter firebase-cloud-messaging

我了解Firebase Cloud Messaging有助于发送推送通知和数据消息。我正在使用Flutter的firebase_messaging pub来接收设备中的通知。仅在通知被取消或单击后,才会调用onMessage,onLaunch和onResume回调。

但是,无论通知是否被取消,我都希望访问收到的消息。有没有办法做到这一点,而不管应用程序是处于前台,后台还是已终止?

1 个答案:

答案 0 :(得分:1)

您可以立即将消息发送到广播接收器并在此处解析

已更新

您应该创建BroadcastReceiver

class YourBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        //some code..
    }
}

然后将其注册到Manifest中:

<receiver
    android:name="com.yourApp.YourBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="YourBroadcastReceiver " />
    </intent-filter>
</receiver>

下一步,也是最后一步,是在方法FirebaseMessagingService中的onMessageReceived中,您可以获取您的数据并将其发送到YourBroadcastReceiver

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)
    val messageText = remoteMessage.data[yourData]
    val intent = Intent(this, YourBroadcastReceiver ::class.java)
    intent.putExtra(messageText, messageText)
    sendBroadcast(intent)
}