提问者:小点点

Firebase Cloud Messaging:即使在应用程序终止时也能从消息中解析数据


我知道Firebase云消息传递方便发送推送通知和数据消息。我正在使用Flutter的firebase_messaging pub接收设备中的通知。onMessage、onLaunch和onResume回调只有在通知被取消或单击后才会被调用。

但是,我想访问收到的消息,无论通知是否被驳回。有没有办法做到这一点,不管app是在前台、后台还是被终止?


共1个答案

匿名用户

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

更新:

您应该创建broadcastreceiver:

class YourBroadcastReceiver : BroadcastReceiver() {

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

然后在清单中注册:

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

下一个也是最后一个步骤是在FireBaseMessagingService方法OnMessageReceived中,您可以获取ur数据并将其发送到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)
}