How to send message from Firebase to device when app is killed?

12,474

onMessageReceived() method will not be called if the app is in background or killed only when the message is sent through Firebase Console.

When app is not running you will anyway receive notification from firebase console. But if you want to intercept data via onMessageReceived() then you will have to create a custom app server which will send only data payload to fcm endpoint. In short you will have to create an app server if you want to actually utilize FCM more efficiently in this case .

You can have a look at these two questions which discuss more regarding same and in second question I also discuss briefly over using node.js and java servlet to do the same:

  1. Handle the data payload without user tapping on the notification?
  2. How to push notification to client when Firebase has a new entry?

Do let me know if this provides you with some info.

Share:
12,474
Andriy Antonov
Author by

Andriy Antonov

Updated on July 20, 2022

Comments

  • Andriy Antonov
    Andriy Antonov almost 2 years

    I am trying to get familiar with Firebase Notifications. It works fine, but I am stuck with receiving messages from the notification console when the app is not turned on.

    I know that documentation says that:

    if your app in foreground or background you can receive message in onMessageReceived method, otherwise user will receive notification in tray... click on it will open main activity with data inside intent

    But is there are any way to catch every message from the notification console even if the application is closed?

    ==== ANSWER ====

    Find answer here

    There is no way to send data message from the notification console.

    But there are other ways to send notification to devices and they will be caught inside onMessageReceived!

    You can use terminal (Mac or Linux) or some service like Postman to send Post request on this link: https://fcm.googleapis.com/fcm/send

    with the next body:

    {
        "to": "/topics/your_topic_here",
       "data": {
           "text":"text",
           "text1":"text1",
           ...
       }
    }
    

    also you need to add 2 headers:

    1. Authorization - key=your_server_key_here
    2. Content-Type - application/json

    To get your server key, you can find it in the firebase console: Your project -> settings -> Project settings -> Cloud messaging -> Server Key

    enter image description here

    enter image description here