OOD Waterball
OOD Waterball

Reputation: 801

How to send message to the topic in Android

How to send a topic message via Firebase ?

I only found the way to send by using Firebase Console , as well as some ways about Post HTTP requests , but I don't understand how to do it in Android.

How can I write some codes in Android to specify a topic which to target then send a message to the topic?

Thanks.

Upvotes: 2

Views: 6485

Answers (2)

Lapenkov Vladimir
Lapenkov Vladimir

Reputation: 3218

If your app is registered in Firebase console, you may send message not only via Firebase console but via either http client. Here is code in Fiddler sending notification to "news" topic

  1. Url:https://gcm-http.googleapis.com/gcm/send
  2. Headers: Content-Type: application/json Authorization: key=[YOUR_APP_API_KEY]
  3. Body:

{ "to": "/topics/news", "notification": { "body": "Hello dude!", } }

or use android app to send message sample from github

Upvotes: 2

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

Sending a message to devices (so-called downstream messages) requires a HTTP call that specifies the server key. As its name implies, this key should only be used in environments you can trust. You cannot directly send a message from a device to other devices, including topics. This diagram from the Firebase Cloud Messaging documentation shows the flow:

diagram showing the flow of FCM messages

So if you want to send messages from an Android app, you will have to:

  1. create server-side code that the Android app talks to
  2. have that server-side code call Firebase Cloud Messaging to send messages
  3. have the Android app call your server-side code

One way to accomplish such a flow is described in our blog post Sending notifications between Android devices with Firebase Database and Cloud Messaging. It uses the Firebase Database to communicate with a server-side script that then calls FCM to send the messages to topics. The server-side code in this post is a Node.js script, since it was the simplest approach available when I wrote it.

But last week Firebase released Cloud Functions for Firebase. This allows you to run server-side code without managing your own infrastructure, which makes it a perfect fit for your use-case. In fact it is such a good fit that it's first in the documentation on use-cases for Cloud Functions for Firebase:

Send FCM message through Cloud Functions for Firebase

You will see that the approach in this sample is very similar to the one in the blog post: both listen for database writes to trigger sending FCM messages. Some of the changes in the sample compared to the blog post:

Upvotes: 10

Related Questions