How to push notification with Cloud Messaging Firebase from the server - java

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.

Related

Azure notification hub: Send notification - Getting the impacted users

I'm using azure-notificationhubs-java-backend to send notifications to Azure hub. I have Azure tags created per application user. Business require me to send notification to multiple users (this part is achieved), and report back the execution status, i.e. whom Azure was able to deliver the notification, and who all were missed (so that other communication can be made with those users). We've this scenario that not all users are yet registered with Azure. Below is the call I am making:
SyncCallback<NotificationOutcome> callback = new SyncCallback<>();
notificationHub.sendNotificationAsync(templateNotification, recipientTags, callback);
NotificationOutcome outcome = callback.getResult();
// outcome has just the notificationId, and trackingId
Any suggestion how can I get success and failed tags. Or there's some other call I can make using the notificationId or trackingId to meet the desired. Thanks!
You can get this data from per message telemetry. Please see below blog for more information.
https://azure.microsoft.com/en-us/blog/retrieve-platform-notification-system-error-details-with-azure-notification-hubs/

When do you need an app server for Firebase 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

How to send direct message via Firebase from user to user?

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.

GCM push notifications with out server

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

Amazon SimpleEmail: how to check if an Email has been delivered?

I tried to send emails with Amazon SES, with the Java AWS SDK, and it worked. I would like to be able to check (at a later time) whether the delivery was successful. I will define it successful if the final mailserver accepted the mail for delivery.
I saw that when you send an email you can get a messageId that uniquely identifies your email:
SendEmailRequest request = new SendEmailRequest(from, destination, message);
SendEmailResult result = service.sendEmail(request);
String messageId = result.getMessageId();
However I saw that you can get only aggregated statistics, for example with SendDataPoint (Represents sending statistics data. Each SendDataPoint contains statistics for a 15-minute period of sending activity).
I'm not using SES to send bulk emails, but personalized notifications on a very low volume and I'd be interested to check every single message.
Did I overlook something? Is it possible to do this type of check with SES?
Amazon does provide a mechanism for you to capture bounces, which provides you with contrapositive verification.
You can create a mailbox to receive bounce notifications, then tell SES to forward bounce notifications there. e.g.:
request.setReturnPath("bounces#example.com");
You can then write code to periodically check that mailbox, and parse the messages for the destination email address.
Amazon provides a brief explanation of how they handle bounces & complaints here:
http://aws.amazon.com/ses/faqs/#37
However, if you want to check if the message avoided the spam filter or was read by the end user, that is beyond the scope of SES (although they work hard to ensure deliverability).
We use Bouncely.com. You simply set the ReturnPath to bounces#bouncely.com and it tracks all the bounces and spam reports. It also has an API that allows us to unsubscribe users automatically.
Use Amazon Simple Notification Service and define an HTTP endpoint to receive notification in case of email bounces. Works perfectly.

Categories