Dor Dahan
Dor Dahan

Reputation: 391

How to send notifications using Firebase in Android Studio when the app is closed?

I'm using Android Studio and Firebase. I want to send to a specific user a notification when other users sends him messages, and I want his phone to be able to get these notifications, even when his app is not running at all.

I've tried to use some guilds by firebase themselves, youtube tutorials and google. But I failed. Can someone please help me with this?

Upvotes: 0

Views: 637

Answers (1)

 Ekalips
Ekalips

Reputation: 1491

FCM have two kinds of messages: downstream and notification. Each of this types behave differently depending on the app state.

1. Notification

Notification will be received by device only if app is in background. It'll be displayed or in notifications tray, or as Heads Up notification. You can't receive Notification kind of message when your app is in foreground.

2. Downstream

Downstream message will be received by your app in any state. You'll receive it in your FirebaseMessagingService implementation (onMessageReceived).

3. Both worlds

If you combine both, 1 and 2, you'll get downstream-notification message. So it'll take behavior from both "worlds". You'll receive Notification message if your app is in background and Downstream if your app is in foreground. Also if you'll click on notification where click_action is specified and you have Intent Filter for this action - it'll lead you to that Activity and call onNewIntent or onCreate depending on backstack.

So, answering your question - if you want to always receive new message notification - send only Downstream message. Even if app is killed it'll receive it or when app will become alive (if messaging service was enable to restart), or right away. But there is one drawback in this way: you'll need to show notification (HeadsUp or regular) to user by yourself.

Update

Here is common Firebase message body:

 {
    "to" : "FIREBASE_TOKEN",
    "notification" : {  // Responsible for Notification kind of messages
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : { // Responsible for Downstream kind of messages
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
  }

So what do you need - it's in some way (as json, or so) send this data to specified firebase url with some headers. Here is link with details how to send messages. Note that there is info how to send message top multiple devices/groups and you need to specify only your partner FirebaseToken in to: field.

Upvotes: 2

Related Questions