I'm trying to send out a push notification from a teacher to a student, for example. I'm using firebase and I've already got that token from each device and saved it on firebase to the wanted user, and setup my FirebaseMessagingService.
Now I want to be able to send a notification, programmatically, whenever a teacher clicks on a student in a list, for example.
How do I do that? I've been looking for a solution for a couple of days and couldn't find an answer.
Thanks :)
This is what I did. And it works. I know, because I was up all night trying to get this thing to work.
admin.messaging().sendToDevice(token, msg)
.then(resMsg => {
console.log("Successfully sent message", resMsg);
}).catch(err => {
console.log("Error sending message", err);
})
Where token is the FCM token from the client device.
And the msg is a JSON payload of the following structure:
const msg ={
notification: {
title: 'It\'s the last day of the week!',
body: `It's Sunday! Don't forget to refresh Dashboard with your latest activity data!`,
},
};
Source Build a transactional push notifications system using only Firebase
For sending push notifications with firebase you need to use the FCM API which can be found here: https://firebase.google.com/docs/cloud-messaging/server.
Assuming you use Java for your software you could take a look at this quickstart example provided by google: https://github.com/firebase/quickstart-java/blob/master/messaging/src/main/java/com/google/firebase/quickstart/Messaging.java or look for a complete library.
You just need to add some logic to your application that triggers the FCM API with the correct token and payload.
Related
I want to be able to send a notification to a user IF something changes.
For example, my application is crime-related. So users can submit reports of crimes that have happened in their neighborhoods.
When a new crime is reported, I want to be able to send ALL users in that specific neighbourhood a notification, even if they are not actively using the app.
How can this be done? I'm quite new at this but to my understanding services like Firebase Messaging require you to type out a message manually and select users to send the message to manually. I'm wondering if there's a way this can be done without someone having to manually do work?
Similar to how snapchat/instagram and stuff will send you notifications that someone has sent you a message even when you are not using your phone.
In my case, I just want the same standard notification "New crime in your area" to be displayed...
How can I do this? (Currently for notifications I'm just using Notification Channels), thank you so much!
You can easily do this using Parse Server through FCM integration.
First, you need to setup your Android app to be able to receive push notifications
Just follow this Quickstart: https://docs.parseplatform.org/parse-server/guide/#push-notifications-quick-start
Second, you need to create a cloud code function
I suggest you to create a cloud code function that will receive the neighborhood as parameter, will query for the user installations in that neighborhood and send the push notification to all of them.
It would be something like this:
Parse.Cloud.define('notifyCrime', async req => {
const query = new Parse.Query(Parse.Installation);
query.equalTo('neighborhood', req.params.neighborhood); // I'm supposing you have a field called neighborhood in your installation class - if not, you can save this field there when the user sign up
await Parse.Push.send({
where: query,
data: {
alert: 'There is a crime in your neighborhood'
},
useMasterKey: true
});
});
Reference: https://docs.parseplatform.org/js/guide/#sending-pushes-to-queries
Third, you need to call the cloud function from your Android app
Once some user has reported a crime, you can call the cloud code function that you created in step 2 to notify all other users in the same neighborhood.
It would be something like this:
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("neighborhood", "The neighborhood goes here");
ParseCloud.callFunctionInBackground("notifyCrime", params, new FunctionCallback<Object>() {
void done(Object response, ParseException e) {
if (e == null) {
// The users were successfully notified
}
}
});
Reference: https://docs.parseplatform.org/cloudcode/guide/#cloud-functions
"my understanding services like Firebase Messaging require you to type out a message manually and select users to send the message to manually".
This is not completely true. There is a method name Firebase Topic Messaging, that lets you send notifications to specific user segments only. You have to register from the app for that topic and then, you can send customized message to your user groups based on topics they subscribed to.
What I really need to accomplish is an instant messaging feature using Firebase.
I've been reading the Firebase Cloud Messaging docs, but I get very confused about the pourposes of the example codes on the server side.
I thought about this solution:
Send a message on the client app to Firebase via RemoteMessage.send()
On Firebase, I catch that message and "redirect" it to the message reciever, who is another client of the app.
In my client app I have this code that I took from the documentation (Firebase was previously initialized):
instance.send(new RemoteMessage.Builder(senderID + "#fcm.googleapis.com")
.setMessageId(Integer.toString(messageID))
.addData("message", message)
.addData("action", "SAY_HELLO")
.build());
That would be the first part of the solution, but now I'm stuck on the part of the code where Firebase should "catch" the message and sends it to another user.
I was trying to write a node.js function to accomplish this, but the problem is that I don't know what is triggered when Firebase gets a RemoteMessage.
Would you mind explaining me how can I do this?
Any code example will be welcome. Thanks :)
I already have an app and I want to start sending notification to the users. I already set up everything in the app(using react native) and I checked manually that I can send notification to the devices and it works.
Now I want to run a job in the server who will push the message (with the device token) to the cloud messaging in firebase.
I can't find a lot of details about how to do it. I would like if someone can give me any guide I can use with. my server is in Kotlin(java can be good too) and I m working with gradle.
Thank you so much for the help
From a Java server you can use the Firebase Admin SDK to send messages. From that documentation comes this minimal example:
// This registration token comes from the client FCM SDKs.
String registrationToken = "YOUR_REGISTRATION_TOKEN";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setToken(registrationToken)
.build();
// Send a message to the device corresponding to the provided
// registration token.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
Note that this sends a data message, so that will always be delivered to your code, where you can decide to display a notification or not. To send a notification message, which is what the Firebase console does, you'd use:
Message message = Message.builder()
.setNotification(new Notification("This is the title", "This is the body"))
.setToken(registrationToken)
.build();
Both of these send the message to a specific registration token, so only to a single device/app instance. This means you will need to maintain a list of these tokens, in a way that allows you to send the messages to fit your needs. E.g. a common way is to store the tokens per user. For an example of that, see the functions-samples repo. While this example is in Node.js, the same logic could be applied to a Java server.
Finally: you can also send message to topics. For an example of that (again: using a Node.js server), have a look at this blog post Sending notifications between Android devices with Firebase Database and Cloud Messaging.
I am new to using FCM notifications for Android Application at https://firebase.google.com/docs/cloud-messaging/server. I was reading up on it and found that in the About FCM Server page requirements, it says the following:
An app server that you must implement in your environment. This app
server sends data to a client app via the chosen FCM connection
server, using appropriate XMPP or HTTP protocol
However, I am sorely confused about this. As I read more into the article, I see that there is an API that looks like this:
POST http://fcm.googleapis.com/fcm/send
If I invoke this API using something like OkHttpClient and build my request like so, (provided that I have authentication headers and a POST body included)
private void sendRegistrationToServer(String token) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder().add(“Body", "").build();
//Assuming I have authentication and body put in
Request request = new Request.Builder().url("http://fcm.googleapis.com/fcm/send”).post(body).build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
Would I in theory, be able to send a notification with whatever information I want to that device? I can receive the message through the following class:
public class NotificationService extends FirebaseMessagingService {
...
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
I’m sure my understanding is incorrect somewhere as the documentation does say we need an application server, but if someone could please point out where I am misunderstanding how to implement FCM notifications, that would be great. If someone could give an example of where or when we would need an app server, or how it should ACTUALLY be implemented, that would also be much appreciated. Thanks!
When the documentation says that you need an app server is mainly because you need an application that store the tokens of the devices to which you would like to send the notifications and this application should update the tokens if any of your client devices change its token. However, you could use the OkHttpClient to send request to the FCM service and therefore send notification to other devices if you have, off course, the token ID of those devices. It depends on what you want to do and it depends on how you want to manage the notifications.
If you want an example on how to implement the server app in java here is a good example example 1 that was posted or here is another post with an implementation on PHP. If you want an example on how to implement the client application and how to test it from the firebase console here is another good example.
If you use the XMPP protocol. You should implement a connection server that manages the connection to FCM to handle upstream and downstream messages.
This is a sample java project to showcase the Firebase Cloud Messaging (FCM) XMPP Connection Server. This project is a very simple standalone server that I developed as a base of a larger project. It is an application server that we must implement in our environment. This server sends data to a client app via the FCM CCS Server using the XMPP protocol.
https://github.com/carlosCharz/fcmxmppserver
And also I've created a video in youtube where I explain what it does.
https://www.youtube.com/watch?v=PA91bVq5sHw
Hope you find it useful.
No need to do any extra work just follow below link:
https://github.com/firebase/quickstart-android/tree/master/messaging
I am really rookie and need an advice.
I have read documentation, and as far as i understood if you need send direct message, follow next steps:
Make authentification, eventually you get Firebase TokenId and
userId
Send them to your server side and store it in DB
When you are going to send a message you need create json and put
inside topic text and resipent userId so on...
Send this json via HTTP to your server side
When server retrive this json, it should use Firebase API to
create new message bloc child with random name in firebase
Eventually server have to find recipent user in DB by userId that we get from message.
After server will find current recipent user by userId , next we should take firebase tokenId In order to sent notification .
And send recipent user notification with such data - name of new
message bloc child
Recipent will connect to this current bloc and retrive data
It is as i understood this consept, fix me please if smth wrong?
Your suggested approach sounds good. The most important thing to realize is that you require an app server to send a downstream message to a device. Using the database as the communication mechanism between the app and the app server is a popular approach.
You could also use Cloud Messaging's upstream capabilities. But I've never tried that approach, because the database works fine for me and I had little interest in learning yet another protocol (XMPP).
You can read how I implemented it in this Firebase blog post Sending notifications between Android devices with Firebase Database and Cloud Messaging.