I have been trying to send push notifications to a Phonegap app deployed on iOS and Android. iOS works fine, but Android doesn't work when I send push notifications from any of the dev consoles from PubNub, Parse and Amazon SNS.
I did verify that I can send notifications if I use the GCM API, so I am using the correct Sender ID, API key and the device token.
I don't see any errors on PubNub console. On Parse dashboard I see that the push notifications have been sent. No error on Amazon SNS. Yet, no push notifications on the device.
I am out of ideas. Thanks in advance for any helpful advice.
With help from PubNub, figured out what the issue was. The sample on PubNub has the following format
{"pn_gcm": {
"data" : {
"GCMSays" : "hi" }
}
}
But the required format was
{"pn_gcm": {
"data" : {
"message" : "hi" }
}
}
After confirming using PubNub console, I updated my JSON object in the code and it all worked like a charm.
With Parse console, I tried to create a JSON object with similar format, but it didn't work. Haven't tried Amazon SNS.
This tutorial illustrates how to configure Android GCM with PubNub: http://www.pubnub.com/docs/java/android/tutorial/google-push-notification.html
[Parse developer] Parse doesn't provide 1st party support for PhoneGap; their product just works with the JS SDK, which doesn't have native Push support. I describe what is necessary to get Parse to recognize your device for push in an arbitrary language in a previous question. You may however be receiving the push but not creating a notification.
In Android (unlike iOS, WinRT, or WinPhone), push doesn't necessarily imply "notification." The native android SDK from Parse creates this automatically for you. You'll need to create your own BroadcastReceiver and wire it to handle the intents that the Play Store app is sending for pushes. You can find these in our Android Push Tutorial. In your BroadcastReceiver, you'll want to create and register your own Notification object when receiving a push.
For Firebase Cloud Messaging, I had to use this structure to receive a tray notification:
"pn_gcm": {
"notification": {
"title": push_title,
"text": push_message
}
},
Related
I am trying to send push notifications using python to all users. However, I am aware that there is no way to do this using apps and you have to use topics (as far as I am aware).
Is there a way that I can create a topic out of the app?
Thanks
Edit: I am completely new to firebase (so sorry if I am difficult)
First of all you need to understand a topic does not need to create (it will be create automatically), you only need to define the topic name for example if you are creating app to receive push notification when the weather change, so the topic name could be "weather".
Now you need have 2 components: mobile & backend
1. Mobile: in your mobile app you only need integrate the Firebase SDK and subscribe to the topic "weather" how do you do that?
Firebase.messaging.subscribeToTopic("weather")
Don't forget checking documentation.
2. Backend: in your server you will need to implement the sender script based on FCM SDK.
If you are a beginner I'd recommend you use Postman to send push notifications and then integrate FCM in your backend app.
You can send this payload trough Postman (don't forget set your API KEY in headers)
https://fcm.googleapis.com/fcm/send
{
"to": "/topics/weather",
"notification": {
"title": "The weather changed",
"body": "27 °C"
}
}
If that works, you can add FCM SDK to your backend:
$ sudo pip install firebase-admin
default_app = firebase_admin.initialize_app()
Finally you can send notifications as documentation says:
from firebase_admin import messaging
topic = 'weather'
message = messaging.Message(
notification={
'title': 'The weather changed',
'body': '27 °C',
},
topic=topic,
)
response = messaging.send(message)
More details here: https://github.com/firebase/firebase-admin-python/blob/eefc31b67bc8ad50a734a7bb0a52f56716e0e4d7/snippets/messaging/cloud_messaging.py#L24-L40
You need to be patient with the documentation, I hope I've helped.
The above solutions are depreciated and outdated.
Let me include the latest implementation of firebase-admin SDK for python.
import firebase_admin
from firebase_admin import credentials, messaging
cred = credentials.Certificate(
"<path-to-your-credential-json>")
firebase_admin.initialize_app(cred)
topic = 'notification'
message = messaging.Message(
notification=messaging.Notification(
title='The weather changed', body='27 °C'),
topic=topic,
)
response = messaging.send(message)
print(response)
*Note of few configurations:
Obtain your credential.json in your firebase console under: "Project settings" -> "Service accounts" -> "Generate new private key"
Make sure you subscribe to the correct topic name for both of your server and client application. Every client applications that subscribed to the same topic regardless of which devices will received the corresponding notifications.
Have a good day~
To subscribe an Android client to a topic, do as shown in the documentation on subscribing to a topic:
FirebaseMessaging.getInstance().subscribeToTopic("weather")
Then you can send a message to that topic from a trusted environment, such as your development machine, a server you control, or Cloud Functions. For an example of this, see How do you send a Firebase Notification to all devices via CURL?
I am migrating from custom Push Notification to AWS SNS. I did the following.
configured AWS SNS Topic
Created Platform Application
created Endpoints
Suscribed endpoints to Platform Application
I am trying the last step for Pushing the Notification using 'publish' API for Ruby. I receive the message_id as response. It also logs as success / delivered in CloudWatch. But the Push is not received in the device.
The device is valid
The device has a valid push token
the device has the application installed.
The message format I tried areas follows
{"GCM"=>{"data"=>"{\"message\":\"message\",\"url\":\"url\"}"}, :default=>"default"}
SNS publish API syntax
client.publish({target_arn: endpoint_arn, message: message.to_json, subject: "SNS test", message_structure: :json})
FYI, Before marking this as duplicate of any other question, please note that i have referred all previous answers and nothing helped me. hence I am raising a new one.
The GCM payload format is updated.
This works for me.
{
"GCM": "{ \"notification\": { \"body\": \"hello....\", \"title\": \"title123\" } }"
}
There is a problem with my message formation. I figured it out by debugging with android . The Push reached the device but it was not in the expected format. So the push was not shown in the device. I was sending
{"GCM"=>{"data"=>"{\"message\":\"message\",\"url\":\"url\"}"}, :default=>"default"}
But the Android system was expecting 'badge' and some other keys in my message. I tried with
{:default=>"default", :GCM=>"{\"data\":{\"message\":\"test\",\"url\":\"https://s3.amazonaws.com/mcds_fulltext/aapg/gsaapgbull/issues/74/android_hdpi/cover_74.gif\",\"registration_ids\":\"arn:aws:sns:us-****-1:*********7:endpoint/GCM/gs*****_gcm/*********************\",\"badge\":\"10\",\"vol\":\"128\",\"issue\":\"10\",\"journal_name\":\"gsaapg\",\"abbr\":\"aapg\"},\"collapse_key\":\"New Article badge\"}"}
Now it works as expected.
This particular JSON might not be appropriate for everyone. But the cause of this issue is the message JSON is not in the expected format for the mobile app. This might be helpful for someone who face the similar issue.
I am using AWS resources for my android project, I am planning to add push notification service for my project with AWS SNS.there are few questions bothering me much. I did not find any questions regarding these, except one or two but with unclear explanations.
1.Does AWS support FCM? SNS work with GCM. But Google recommends to use FCM instead of GCM. I did not find AWS supporting FCM.
2.Do AWS store messages (or data) into their databases even after sending push notifications?
3.I tried putting FCM api key in SNS application platform, it is showing invalid parameters why?
FCM is backwards compatible with GCM. The steps for setting up FCM on AWS are identical to the GCM set up procedure and (at least for the moment) FCM works transparently with GCM and SNS with respect to server-side configuration.
However, if you are sending data payloads to the Android device they will not be processed unless you implement a client side service that extends FirebaseMessagingService. The default JSON message generator in the AWS console sends data messages, which will be ignored by your app unless the aforementioned service is implemented. To get around this for initial testing you can provide a custom notification payload which will be received by your device (as long as your app is not in the foreground)
There are GCM-FCM migration instructions provided by Google however the changes you need to make are predominantly on the App side.
The steps you need to follow to test GCM/FCM on your app with SNS are:
Create a Platform Application in SNS, selecting Google Cloud Messaging (GCM) as the Push Notification Platform, and providing your Server API key in the API key field.
Select the Platform Application and click the Create platform endpoint button.
Provide the InstanceID (Device Token) generated by your app. You must extend the FirebaseInstanceIDService and override the onTokenRefresh method to see this within your Android App. Once you have done this, uninstall and reinstall your app and your token should be printed to the Debug console in Android Studio on first boot.
Click the Add endpoint button.
Click on the ARN link for your platform application.
Select the newly created Endpoint for your device and click the Publish to endpoint button.
Select the JSON Message Format, and click the JSON message generator button.
Enter a test message and click the Generate JSON button
Now comes the "gotcha part".
The message that is generated by SNS will be of the form:
{
"GCM": "{ \"data\": { \"message\": \"test message\" } }"
}
As we mentioned earlier, data payloads will be ignored if no service to receive them has been implemented. We would like to test without writing too much code, so instead we should send a notification payload. To do this, simply change the JSON message to read:
{
"GCM": "{ \"notification\": { \"title\": \"test title\", \"body\": \"test body\" } }"
}
(For more information about the JSON format of an FCM message, see the FCM documentation.)
Once you have done this, make sure your app is not running on the device, and hit the Publish Message button. You should now see a notification pop up on your device.
You can of course do all this programmatically through the Amazon SNS API, however all the examples seem to use the data payload so you need to keep that in mind and generate a payload appropriate to your use case.
Now you can go to your firebase console (https://console.firebase.google.com/) select your project, click the gear icon and choose project settings, then click on the cloud messaging tab...
You'll see the legacy Server Key which is the GCM API Key and you'll have the option to generate new Server Keys which are the FCM versions
SNS will accept both versions but their menu option is still categorizing it under GCM
Here is picture for your reference:
Note that you can "accidentally" remove your Server Keys but the Legacy server key is not deletable. Also, if you click the add server key button, you'll get a new server key BELOW the first one, WITH NO WARNING! ...Nice job Google ;)
One more additional note to Nathan Dunn's great answer.
How to send data with the notification from SNS to Firebase.
We need to add data to the Json (inside the notification):
{
"default": “any value",
"GCM": "{ \"notification\": { \"body\": \”message body\”, \”title\”: \”message title \”, \"sound\":\"default\" } , \"data\" : {\”key\" : \”value\", \”key2\" : \”value\” } }”
}
In your FirebaseMessagingService implementation (Xamarin example)
public override void OnMessageReceived(RemoteMessage message)
{
try
{
var body = message?.GetNotification()?.Body;
var title = message?.GetNotification()?.Title;
var tag = message?.GetNotification()?.Tag;
var sound = message?.GetNotification()?.Sound;
var data = message?.Data
foreach (string key in data.Keys)
{
// get your data values here
}
}
catch (Exception e)
{
}
}
I tried to use solution with notification payload instead of data, but I did not receive push notifications on the mobile device. I found this tutorial https://youtu.be/iBTFLu30dSg with English subtitles of how to use FCM with AWS SNS step by step and example of how to send push notifications from AWS console and implement it on php with aws php sdk. It helped me a lot.
Just an additional note to Nathan Dunn's Answer: to add sound use the following JSON message
{
"GCM": "{ \"notification\": { \"text\": \"test message\",\"sound\":\"default\" } }"
}
It took me a while to figure out how to send the notification with the right payload (publish to topic). So I will put it here.
private void PublishToTopic(string topicArn)
{
AmazonSimpleNotificationServiceClient snsClient =
new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest1);
PublishRequest publishRequest = new PublishRequest();
publishRequest.TopicArn = topicArn;
publishRequest.MessageStructure = "json";
string payload = "\\\"data\\\":{\\\"text\\\":\\\"Test \\\"}";
publishRequest.Message = "{\"default\": \"default\",\"GCM\":\"{" + payload + "}\"}";
PublishResponse publishResult = snsClient.Publish(publishRequest);
}
Amazon does support FCM as all previous code has been migrated from GCM to FCM. Below article explains in detail.
Article Published by Amazon
To answer the questions:
AWS SNS does support FCM.
No AWS does not store messages after sending push notifications.
For a detailed tutorial on setting up FCM with SNS please read this article.
Parse is shutting down and they've made their server opensource. However they do not have the extended functionality with push notifications as what used to be the case with parse.com
Can anyone help me set up push notifications on the open source version of Parse on android?
I've been through their wiki and I'm a tad bit confused about it.
If I'm not wrong, should I just add the GCM credentials to where the Parse Server is being initialized and then deploy it manually (possibly to heroku) myself and then use cURL to send notifications as per the wiki?
Or did I misunderstand the whole process and need to do something else?
Thanks in advance!
You can host your own Parser Server in a self-hosting solution or use a Parse Hosting provider like https://www.back4app.com
See all options below:
https://github.com/ParsePlatform/parse-server#parse-server-sample-application
Then you can send the push notifications using dashboard console, API or cloud code. Note that push notifications cannot be sent anymore from client. Because of security issues, Parse Server has discontinued sending push notifications direct from client. The best practice now is to create a cloud function to send the push notifications and then call it from client code. See more details below:
https://github.com/ParsePlatform/parse-server/wiki/Push#4-send-push-notifications
And here there is an example of a cloud function that can be used to send push notifications:
Parse.Cloud.define('push', function (request, response) {
// THIS METHOD NO LONGER WORKS
// Parse.Cloud.useMasterKey();
Parse.Push.send({
channels: request.params.channels,
data: request.params.data
}, {
// ADD THE `useMasterKey` TO THE OPTIONS OBJECT
useMasterKey: true,
success: function () {
response.success('Success!');
},
error: function (error) {
response.error('Error! ' + error.message);
}
});
});
You can also send the push notification throw Parse Dashboard. Parse has just announced this feature is now available:
http://blog.parse.com/announcements/push-and-config-come-to-the-parse-dashboard/
just fill the GCM field and the second field when you initialize Parse server (in the index.js or the ecosystem.json)... this will allow the server to send the Push for Android, for sending push U can use cloud code, curl or whatever. You need to use MasterKey though
I want to send push notification to individual using android GCM. have created the app in SNS. I am using aws-sdk v1.4 for Ruby.
When I send through Amazon web interface I receive the messages, but When I publish it through using the code below, I get blank messages. what is the right message format to send?
sns = AWS::SNS::Client.new
endpoint = sns.create_platform_endpoint(platform_application_arn:my_token)
sns.publish(target_arn:endpoint:endpoint_arn, message: "GCM:{data:{message:"GCM:{data:{message:'hello'}")
Please help.
TIA
{"GCM": "{ \"data\": { \"message\": \"hello\" } }"}
Do not call to_json method also set the subject parameter in publish.
The message should be a valid JSON string if you want to publish a message to GCM. You can use to_json to serialize a hash object to JSON. Here is a article about using AWS SDK for Ruby http://blog.tryneighborly.com/amazon-sns-for-apns-on-rails/.
For more information about Amazon SNS:
Send Custom Platform-Specific Payloads in Messages to Mobile Devices
Getting Started with Google Cloud Messaging for Android
Ruby doc for Aws::SNS::Client