This is the code i found on SNS's official site to publish to a topic
String msg = "My text published to SNS topic with email endpoint";
PublishRequest publishRequest = new PublishRequest(topicArn, msg);
PublishResult publishResult = snsClient.publish(publishRequest);
System.out.println("MessageId - " + publishResult.getMessageId());
I am developing a chat app on for android using sns(it will also push notifications to the existing ios counterpart of the app)
if i want to publish to a single device directly can i give device's "ApplicationEndPointArn" instead of topicArn
SNS is intended to decouple notification service from application layer.
We could create a topic and add mobile endpoints as subscribers.
When a message is published to the topic all subscribers will get notified.
Apart from this if you would really need single endpoint messaging you could try,
PublishRequest publishRequest = new PublishRequest();
publishRequest.setTargetArn(endpointArn);
publishRequest.setMessage("SOME MESSAGE");
snsClient.publish(publishRequest)
where endpointArn is a device endpoint.
But make sure that you persist this device endpoint when device is registered in SNS and use the same returned EndpointArn for further communication.
Related
I implemented my backend service (using java and FCM) to send push-notifications to mobile apps.
I implemented my service using Java Firebase Admin-SDK (https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/messaging/package-summary and https://firebase.google.com/docs/cloud-messaging/send-message#java) about this and I'm able to send (and receive) push notifications on iOS and Android mobile apps.
Now I received a request from mobile-developers that they needs to customize (client-side) the received push notifications (also when the app is in background mode).
Probably here is reported a same question: What is the difference between Firebase push-notifications and FCM messages?
Reading the documentation (https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages) I understood that It's necessary to use a Data-message instead of a Notification message.
It's not clear for me what's necessary to change to support this delivery type.
Do I change the Android-config of the FCM-message or Do I remove some unnecessary data (just set all info into the custom data without others info for example Android configuration etc..)
It's possible to have a small example?
If your json will have notification key, developers will not able to handle notifications in background. They will receive this notification only when app is in foreground. In case when developers should receive “silent pushes” or they need control all notifications, you should remove notification key, and use only data key.
This can be achieved by changing the key 'notification' to 'data' as follows:
{
"notification": { //replace this line by "data"
"title": "Hey Gajanan",
"body": "Thanks for visiting omnidecoder.com"
},
"to" : "YOUR-GENERATED-TOKEN"
}
I am thinking about keeping all registration ids(push token) in DB and sending notifications to user from iPhone. I tried something like this but did not get any notification.
func sendPNMessage() {
FIRMessaging.messaging().sendMessage(
["body": "hey"],
to: TOKEN_ID,
withMessageID: "1",
timeToLive: 108)
}
What I am doing wrong or maybe it is impossible at all?
Currently it's not possible to send messages from the application itself.
You can send messages from the Firebase Web Console, or from a custom server using the server-side APIs.
What you might want to do is to contact a server (like via http call) and that server will send the message to the user.
This way ensure that the API-KEY of the server is protected.
PS: the sendMessage(..) api is called upstream feature, and can be used to send messages from your app to your server, if you server has an XMPP connection with the FCM server.
Yes you can send push notification through Firebase.Please make sure do NOT include the server-key into your client. There are ways "for not so great people" to find it and do stuff... The Proper way to achieve that is for your client to instruct your app-server to send the notification.
You have to send a HTTP-Post to the Google-API-Endpoint.
You need the following headers:
Content-Type: application/json
Authorization: key={your_server_key}
You can obtain your server key within in the Firebase-Project.
HTTP-Post-Content: Sample
{
"notification": {
"title": "Notification Title",
"text": "The Text of the notification."
},
"project_id": "<your firebase-project-id",
"to":"the specific client-device-id"
}
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the Google Cloud Functions documentation:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
Diego's answer is very accurate but there's also cloud functions from firebase it's very convenient to send notifications in every change in the db. For example let's say you're building chat application and sending notification in every new follower change.
This function sample is very good example.
For more information about cloud functions you can check official docs.
I have an app that has a "send feedback to developer" section. I also have a User collection in my firestore database. When a user logs into the app, I have that Users data update their FCM token with the following code in my SceneDelegate.swift:
import Firebase
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil {
DispatchQueue.main.async {
let docRef = Firestore.firestore().collection("User").document((user?.email)!)
docRef.getDocument { (snapshot, error) in
guard let snapshot = snapshot else {return}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
docRef.updateData(["FCMtoken":token])
print("FCM registration token: \(token)")
}
}
}
}
}
})
guard let _ = (scene as? UIWindowScene) else { return }
}
then in my feedback view controller i have this code to send my specific device (but you can look up/fetch which specific device you want in your database where the FCMtoken is stored where i have INSERT-DEVICE-TOKEN-HERE). The url to send to is "https://fcm.googleapis.com/fcm/send" and you can find YOUR-APP-FCM-KEY by going to your project settings in firebase, going to cloud messaging tab and its the server key.
func sendMePushNotification() {
let token = "INSERT-DEVICE-TOKEN-HERE"
if let url = URL(string: "https://fcm.googleapis.com/fcm/send") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = ["Content-Type":"application/json", "Authorization":"key=YOUR-APP-FCM-KEY"]
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"title\":\"Feedback Sent!\",\"body\":\"\(self.feedbackBox.text!)\",\"sound\":\"default\",\"badge\":\"1\"},\"data\": {\"customDataKey\": \"customDataValue\"}}".data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, urlresponse, error) in
if error != nil {
print("error")
} else {
print("Successfully sent!.....")
}
}.resume()
}
}
Use onesignal,you can send device to notifications or device to segments ,it can work with firebase in this way
Use onesignal functions to create a specific id,save it in a firebase database ,then when the id can be put in another function that is used to send a notification
Notes: 1-i am using it in my apps with firebase works perfectly
2-i can submit that code,just someone comments so i can find this answer
I am very new to java server side development, i have followed this link [http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/][1] and successfully implemented GCM with my android device, the problem is dont know how to trigger the GCM server while the content is updated in my db,i need to notify each and every update of my db to the user, am i need to watch the db using timer task something like that or is there any default solution to keep track of db ?
My Server side code :
regId = "my registration id";
String userMessage = request.getParameter("message");
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(30)
.delayWhileIdle(true).addData(MESSAGE_KEY, userMessage).build();
result = sender.send(message, regId, 1);
have tried with many solution but till now not getting exact solution, Suggestion, ideas or related links are most welcome
Thanks in advance
Without knowing the specific functionality of your server and app, I can only offer a general solution.
Each process in your server that performs DB updates that have to be pushed to some Android devices via GCM can write the messages and the registration IDs to some kind of queue.
Then you can have another process (or processes) that would consume the queue of GCM messages, and send them to Google. These processes can handle failures (retry sending the messages in case of temporary failures), and update your database of registration IDs if they receive responses with canonical registration IDs or errors such as InvalidRegistration or NotRegistered.
I am using Logica OpenSMPP (http://opensmpp.org/) to manage messages via SMPP protocol. I have a server, which can answer on my SMS and USSD messages, and I am developing a client. I have already managed to send DeliverSM message and get SubmitSM response from server via SMS: first I start SMSC, and then do something like that:
DeliverSM request = new DeliverSM();
request.setSourceAddr(from);
request.setDestAddr(to);
try {
request.setShortMessage(message);
} catch (WrongLengthOfStringException e) {
log.error("Error during setShortMessage", e);
}
request.setRegisteredDelivery((byte) 0);
new Transmitter(this.connection).send(request);
But I encounter some problems while doing the same for USSD. I know, that I must somehow use the following (cut from SMPP V3.4 Specification):
The ussd_service_op parameter is required to define the USSD service
operation when SMPP is being used as an interface to a (GSM) USSD
system.
What are the steps that I need to do to learn my client send both SMS and USSD messages to server?
This project hosts code for sending USSD. You may consider browsing the code to see how it's done, and then implement similar features in Logica OpenSMPP.
I'm using SMSLib in my java application to send messages, I make that using a usb modem as a gateway and send the messages to any phone throw it, the point here that when i receive the message it displays the sender as the sim number(the sim that exists in the usb modem).
The thing i want to do is to assign a name instead of the sim number so the recipient will see that name not the usb modem sim number
In most cases sender name is overridden by the Service Provider to their identification 'SIM number'.
By the Library it provides two locations to set sender information.
On gateway level
SerialModemGateway gateway = new SerialModemGateway("modem.com4",
"COM4", 57600, "Huawei", "E160");
gateway.setFrom("chandpriyankara");
On Message level
SMS
OutboundMessage msg = new OutboundMessage("+94123456789",
"SMS test: sample message from StackOverflow");
msg.setFrom("chandpriyankara");
I couldn't set a customer sender for SMS from either of my tested SMS providers[GSM Providers]. But this should work for buld SMS gateways. You have to discuss this with your service provider.
WAP
OutboundWapSIMessage wapMsg = new OutboundWapSIMessage("+94123456789",
new URL("http://stackoverflow.com/"),
"WAP test: sample message from StackOverflow!");
wapMsg.setFrom("chandpriyankara");
For WAP messages, some of GSM providers set my custom sender details, but not all.
You can put sender information to your message instance before sending.
message.setFrom("your sender information");
Additionally it may depend on your GSM provider.