【问题标题】:Firebase push notification not received when app remove from background in android当应用程序从 android 的后台删除时未收到 Firebase 推送通知
【发布时间】:2020-06-06 07:44:39
【问题描述】:

我在过去 2 天都面临这个问题,当应用程序从后台删除时,我无法收到 Firebase 推送通知。当应用程序处于前台或后台时,Firebase 推送通知工作正常,但从后台删除时无法接收推送通知。我已经阅读了很多关于堆栈溢出的块,但没有任何帮助。请帮助我摆脱这种情况。我只使用数据有效负载而不是通知有效负载

下面是代码:

class MyFirebaseMessagingService : FirebaseMessagingService() {
    private var notificationUtils: NotificationUtils? = null


    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.i("firebaseToken", token)
        Log.i("deviceId", AppUtils.getDeviceId())
        SharedPrefs.write("firebaseToken", token)

    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.from)
        if (remoteMessage == null) return
        // Check if message contains a notification payload.
        if (remoteMessage.notification != null) {
            Log.e(
                TAG,
                "Notification Body: " + remoteMessage.notification!!.body
            )
//            handleNotification(remoteMessage.notification!!.body)
        }
        // Check if message contains a data payload.
        if (remoteMessage.data.size > 0) {
            Log.e(
                TAG,
                "Data Payload: " + remoteMessage.data.toString()
            )
            try {

                val params =
                    remoteMessage.data.toMap()
                val json = JSONObject(params)
                Log.e(TAG, "JSON_OBJECT " + json.toString())
                handleDataMessage(json)
//                val json = JSONObject(remoteMessage.data.toString())
//                handleDataMessage(json)
//                Log.e(
//                    TAG,
//                    "json from Data Payload: " + json
//                )
            } catch (e: Exception) {
                Log.e(TAG, "Exception: " + e.message)
            }
        }
    }

    private fun handleNotification(message: String?) {
        if (!NotificationUtils.isAppIsInBackground(applicationContext)) { // app is in foreground, broadcast the push message
            val pushNotification = Intent(AppConstants.PUSH_NOTIFICATION)
            pushNotification.putExtra("message", message)
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification)
            // play notification sound
            val notificationUtils = NotificationUtils(applicationContext)
            notificationUtils.playNotificationSound()
        } else { // If the app is in background, firebase itself handles the notification
        }
    }

    private fun handleDataMessage(json: JSONObject) {
        Log.e(TAG, "push json: $json")
        try {

            val title: String = json.optString("title")
            val description: String = json.optString("description")
            val user: String = json.optString("user")
            val applyDate: String = json.optString("apply_date")
            if (!NotificationUtils.isAppIsInBackground(applicationContext)) {
                val myKM =
                    getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
                if (myKM.inKeyguardRestrictedInputMode()) {
                    //it is locked
                    val resultIntent =
                        Intent(applicationContext, HomePageActivity::class.java)
                    resultIntent.putExtra(AppConstants.DESCRIPTION, description)
                    resultIntent.putExtra(AppConstants.TITLE, title)
                    resultIntent.putExtra(AppConstants.APPLIED_DATE, applyDate)
                    resultIntent.putExtra(AppConstants.USER, user)
                    val timestamp = System.currentTimeMillis()
                    showNotificationMessage(
                        applicationContext,
                        title,
                        "User " + user + " apply date " + applyDate + " description " + description,
                        "" + timestamp,
                        resultIntent
                    )
                } else {
                    //it is not locked
                    // app is in foreground, broadcast the push message
                    val pushNotification = Intent(AppConstants.PUSH_NOTIFICATION)
                    pushNotification.putExtra(AppConstants.DESCRIPTION, description)
                    pushNotification.putExtra(AppConstants.TITLE, title)
                    pushNotification.putExtra(AppConstants.APPLIED_DATE, applyDate)
                    pushNotification.putExtra(AppConstants.USER, user)
                    LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification)
                    // play notification sound
                    val notificationUtils =
                        NotificationUtils(applicationContext)
                    notificationUtils.playNotificationSound()
                }
            } else {
                // app is in background, show the notification in notification tray
                val resultIntent =
                    Intent(applicationContext, HomePageActivity::class.java)
                resultIntent.putExtra(AppConstants.DESCRIPTION, description)
                resultIntent.putExtra(AppConstants.TITLE, title)
                val timestamp = System.currentTimeMillis()
                showNotificationMessage(
                    applicationContext,
                    title,
                    description,
                    "" + timestamp,
                    resultIntent
                )
            }
        } catch (e: JSONException) {
            Log.e(TAG, "Json Exception: " + e.message)
        } catch (e: Exception) {
            Log.e(TAG, "Exception: " + e.message)
        }
    }

    /**
     * Showing notification with text only
     */
    private fun showNotificationMessage(
        context: Context,
        title: String,
        message: String,
        timeStamp: String,
        intent: Intent
    ) {
        notificationUtils = NotificationUtils(context)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        notificationUtils?.showNotificationMessage(title, message, timeStamp, intent)
    }

    /**
     * Showing notification with text and image
     */
    private fun showNotificationMessageWithBigImage(
        context: Context,
        title: String,
        message: String,
        timeStamp: String,
        intent: Intent,
        imageUrl: String
    ) {
        notificationUtils = NotificationUtils(context)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        notificationUtils?.showNotificationMessage(title, message, timeStamp, intent, imageUrl)
    }

    companion object {
        private val TAG = MyFirebaseMessagingService::class.java.simpleName
    }
}

提前致谢。

【问题讨论】:

标签: android firebase


【解决方案1】:

首先,您将其称为推送通知,但您没有使用它,您使用的是 FCM 数据消息。

如果它们是真实的推送通知,并且您的应用不在前台,则它们将直接在任务栏中接收,而无需调用 onMessageReceived()。

如果您的应用程序没有运行,则带有数据消息,那么它将不会收到消息,如果应用程序再次启动,它们将在稍后收到。

如果您想获得更多接收消息的可能性,您应该从您的应用中启动一个服务,但如果设备进入睡眠模式,它也会停止接收它们,或者会很晚才接收它们。

也许您假设 FCM 消息应始终立即收到,但事实并非如此。

【讨论】:

    猜你喜欢
    • 2020-08-02
    • 2017-12-04
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多