如何在应用程序被关闭时接收 Firebase 消息?

huangapple go评论65阅读模式
英文:

How to receive firebase messages even if app is killed?

问题

你想要在应用程序被关闭的情况下也能接收通知。

通常,您会使用以下代码段从FCM读取数据:

class MyFcmListenerService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.d("TAG", "onMessageReceived: called")
    }
}

在某些具有原生Android的设备上,当应用程序在前台/后台运行时,您将在logcat中看到打印出 "onMessageReceived: called"。但在具有MIUI、ColorOS、OneUI等操作系统的设备上,在后台中由于进程已被终止,您将看不到 "onMessageReceived"。

英文:

You want to receive notifications even when app in killed state.

You will generally use this snippet to read data from fcm :

class MyFcmListenerService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.d("TAG","onMessageReceived: called")
    }
} 

You will see onMessageReceived: called is printed in logcat when app is in foreground/background in some devices which have stock android. But in case of devices which have MIUI, ColorOS, OneUI etc. You will not see onMessageReceived in background because process is killed.

答案1

得分: 0

以下代码片段可用于在应用程序处于后台/被杀死状态时接收 FCM 消息。

class BackgroundFcmReceiver : WakefulBroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val extras = intent.extras?.keySet()
        if (extras != null) {
            for (key in extras) {
                Log.d("TAG", "$key")
            }
        }
    }
}

根据开发者文档,WakefulBroadcastReceiver 用于实现一个 BroadcastReceiver 的旧模式,它接收设备唤醒事件,然后将工作传递给 android.app.Service,并确保在过渡期间设备不会回到睡眠状态。
这个类会为您创建和管理部分唤醒锁定;

注意:您必须请求 android.Manifest.permission.WAKE_LOCK 权限才能使用它。

英文:

Following code snippet can be used to receive FCM messages when app is in background/killed state

class BackgroundFcmReceiver : WakefulBroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
    val extras = intent.extras?.keySet()
    if (extras != null) {
        for (key in extras) {
            Log.d("TAG", "$key")
        }
    }

}

As of developer documentation WakefulBroadcastReceiver is for an old pattern of implementing a BroadcastReceiver that receives a device wakeup event and then passes the work off to a android.app.Service, while ensuring that the device does not go back to sleep during the transition.
This class takes care of creating and managing a partial wake lock for you;

Note : you must request the android.Manifest.permission.WAKE_LOCK permission to use it.

huangapple
  • 本文由 发表于 2023年6月12日 17:41:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定