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.
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:
So if you want to send messages from an Android app, you will have to:
- create server-side code that the Android app talks to
- have that server-side code call Firebase Cloud Messaging to send messages
- 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:
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:
- the sample replaces the Node.js script with a Cloud Function.
- the sample sends to device tokens instead of topics.
- the sample uses the new Firebase Admin SDK to send messages, instead of calling the FCM HTTP end-point
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
- Url:https://gcm-http.googleapis.com/gcm/send
- Headers:
Content-Type: application/json
Authorization: key=[YOUR_APP_API_KEY]
- Body:
{
"to": "/topics/news",
"notification": {
"body": "Hello dude!",
}
}
or use android app to send message
sample from github