简体   繁体   中英

Firebase push notification not received when app remove from background in android

I am facing this issue for last 2 days I am not able to receive firebase push notification when app remove from background.Firebase push notification working fine when app is in foreground or background but when remove from background then not able to receive push notification. I have read so many block on stack overflow but nothing helped me.Kindly help me to get rid of this situation.I am using only data payload not notification payload

Below is the code:

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
    }
}

Thanks in Advance.

First, you are calling it Push Notification but you are not using that, you are using FCM data messages.

If they were authentic push notifications and your app was not in the foreground, they would be received directly in the taskbar without being called onMessageReceived ().

With data messages if your app is not running then it will not receive the messages, they will be received later if the app is started again.

If you want more possibilities of receiving the messages, you should start a service from your app, but also if the device enters sleep mode it will also stop receiving them, or will receive them quite late.

Perhaps you are assuming that FCM messages should always be received immediately, but this is not true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM