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
Related
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.
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 tried GCM-Demo app on both Mobile/AVD and working fine, now as part of my PoC I will get notifications from SAP and using GCM I want to send notifications to Android devices.
I posted message to directly to https://android.googleapis.com/gcm/send using REST client successfully, please advice me what changes I have to change here to receive on this notification client device...
And I am confused what URL I need to give in CommonUtilities.JAVA , as I sent data directly using REST CLIENT.
static final String SERVER_URL = "http://host:8080/gcm-demo/";//is it necessary yo provide server URL ?
/**
* Google API project id registered to use GCM.
*/
static final String SENDER_ID = "1012728190866";
In simple words, I will send data using REST instead of SERVER(successfully I sent to GCM),and want to receive notification on device.
Thanks
Rajesh
I am using parse4j library for server side coding and on client side I have iOS device. Now I want to send the push notification from my web browser page I developed in JAVA in which I am using parse4j library to communicate with iOS device through Parse cloud. I am using gwt for coding the server side.
public void sendPushtoIOS() {
Parse.initialize("appId", "restApiId");
ParsePush parsePushObj = new ParsePush();
parsePushObj.sendInBackground("hello from server",null);
}
I am trying to send the notification with the above code, but nothing happens and iOS device doesn't receive any notification. Please could someone guide the code I written is correct or not, If not, how can I send the notification then?
try {
String rawJSON = "{\"aps\":{\"alert\":\""+"your message"+"\"},\"alerts\":{\"others\":\""+others+"\"}}";
PushNotificationPayload payload=PushNotificationPayload.fromJSON(rawJSON);
Push.payload(payload, "path of certificate.p12", password,false, appleDeviceToken);
}
catch (Exception e) {
}
As far as I understand correct, you are using the Parse4j library to send Push Notification. Did you control the current version of parse4j if it can send Push notification? Or it is pending enhancement? One suggestion; in order to send push notification write a cloud code and trigger this cloud code from parse4j. Then cloud code will send the Push notification.
Hope this helps,
Regards.
This library works fine. You can check pushes in parse dashboard, most likely you collected push requests. The only problem was that library works with channels. Maybe you do not set channels.
If you want to work with conditions, add this lines of code in library
JSONObject local = new JSONObject();
local.put("deviceType", "android");
data.put("where", local);
and remove
data.put("channel", "");
data.put("channels", new JSONArray(this.channelSet));
all of these changes must be done in method getJSONData() in class ParsePush
instead of android you can set your devices
I've been struggling from past 4 days to implement push notification in vert.x framework using java(at server side) and javascript(client side). I've been studying example from this link.
I am not able to understand what is the significance of "prefix" in below line of code.
How to put my custom message to json array, so that it will sent to client as notification.
sockJSServer.bridge(new JsonObject().putString("prefix", "/eventbus"), permitted, permitted);
And I am also unable to implement client side according to my need. My requirement is get data from database and than vert.x server publish that data to n number of clients. What will be the prerequisite for that whole scenario?
In above mentioned link, index.html is there. I debugged this on browser. It successfully connect the server.
One more point is, what is the significance of "/eventbus" in index.html(line no #108)
eb = new vertx.EventBus("http://localhost:8080/eventbus");
After successful connection with server.Should every client subscribe to server in order to get notification from server ? I want every client will get notification without any client intervention.
Now, the last point is in below code, what is address? Is it client ip address or server or any other thing.
function publish(address, message) {
if (eb) {
var json = {text: message};
eb.publish(address, json);
$('#sent').append($("<code>").text("Address:" + address + " Message:" + message));
$('#sent').append($("</code><br>"));
}
}
function subscribe(address) {
if (eb) {
eb.registerHandler(address, function(msg, replyTo) {
$('#received').append("Address:" + address + " Message:" + msg.text + "<br>");
});
$('#subscribed').append($("<code>").text("Address:" + address));
$('#subscribed').append($("</code><br>"));
}
}
Any help will be appreciable.
The callback function in registerHandler() receive message from server in Json form. You can get your custom message by message.notification where notification is your unique key that is to be set at server side.