Can anyone please help me with the sample code for google push notifications. I am getting an error in json message.
Here is the code:
local googleApiKey = "**********************"
local googleRegistrationId = nil
-- Called when a sent notification has succeeded or failed.
local function onSendNotification(event)
local errorMessage = nil
-- Determine if we have successfully sent the notification to Google's server.
if event.isError then
-- Failed to connect to the server.
-- This typically happens due to lack of Internet access.
errorMessage = "Failed to connect to the server."
elseif event.status == 200 then
-- A status code of 200 means that the notification was sent succcessfully.
print("Notification was sent successfully.")
elseif event.status == 400 then
-- There was an error in the sent notification's JSON data.
errorMessage = event.response
elseif event.status == 401 then
-- There was a user authentication error.
errorMessage = "Failed to authenticate the sender's Google Play account."
elseif (event.status >= 500) and (event.status <= 599) then
-- The Google Cloud Messaging server failed to process the given notification.
-- This indicates an internal error on the server side or the server is temporarily unavailable.
-- In this case, we are supposed to silently fail and try again later.
errorMessage = "Server failed to process the request. Please try again later."
end
-- Display an error message if there was a failure.
if errorMessage then
native.showAlert("Notification Error", errorMessage, { "OK" })
end
end
-- Sends the given JSON message to the Google Cloud Messaging server to be pushed to Android devices.
local function sendNotification(jsonMessage)
-- Do not continue if a Google API Key was not provided.
if not googleApiKey then
return
end
-- Print the JSON message to the log.
print("--- Sending Notification ----")
print(jsonMessage)
-- Send the push notification to this app.
local url = "**************************"
local parameters =
{
headers =
{
["Authorization"] = "key=" .. googleApiKey,
["Content-Type"] = "application/json",
},
body = jsonMessage,
}
network.request(url, "POST", onSendNotification, parameters)
end
-- Sends a push notification when the screen has been tapped.
local function onTap(event)
-- Do not continue if this app has not been registered for push notifications yet.
if not googleRegistrationId then
return
end
-- Set up a JSON message to send a push notification to this app.
-- The "registration_ids" tells Google to whom this push notification should be delivered to.
-- The "alert" field sets the message to be displayed when the notification has been received.
-- The "sound" field is optional and will play a sound file in the app's ResourceDirectory.
-- The "custom" field is optional and will be delivered by the notification event's "event.custom" property.
local jsonMessage =
[[
{
"registration_ids": ["]] .. tostring(googleRegistrationId) .. [["],
"data":
{
"alert": "Hello World!",
"sound": "notification.wav",
"custom":
{
"boolean": true,
"number": 123.456,
"string": "Custom data test.",
"array": [ true, false, 0, 1, "", "This is a test." ],
"table": { "x": 1, "y": 2 }
}
}
}
]]
sendNotification(jsonMessage)
end
Runtime:addEventListener("tap", onTap)
-- Prints all contents of a Lua table to the log.
local function printTable(table, stringPrefix)
if not stringPrefix then
stringPrefix = "### "
end
if type(table) == "table" then
for key, value in pairs(table) do
if type(value) == "table" then
print(stringPrefix .. tostring(key))
print(stringPrefix .. "{")
printTable(value, stringPrefix .. " ")
print(stringPrefix .. "}")
else
print(stringPrefix .. tostring(key) .. ": " .. tostring(value))
end
end
end
end
-- Called when a notification event has been received.
local function onNotification(event)
if event.type == "remoteRegistration" then
-- This device has just been registered for Google Cloud Messaging (GCM) push notifications.
-- Store the Registration ID that was assigned to this application by Google.
googleRegistrationId = event.token
-- Display a message indicating that registration was successful.
local message = "This app has successfully registered for Google push notifications."
native.showAlert("Information", message, { "OK" })
-- Print the registration event to the log.
print("### --- Registration Event ---")
printTable(event)
else
-- A push notification has just been received. Print it to the log.
print("### --- Notification Event ---")
printTable(event)
end
end
-- Set up a notification listener.
Runtime:addEventListener("notification", onNotification)
-- Print this app's launch arguments to the log.
-- This allows you to view what these arguments provide when this app is started by tapping a notification.
local launchArgs = ...
print("### --- Launch Arguments ---")
printTable(launchArgs)
Whenever this code is called and Error 400 notification appears. Is there a way to send custom push notifications to android device using corona?
Json is completely fine. There might be the problem of url you set up and for triangle notification problem you can go through the following link:
http://jsonlint.com/#
Related
I use Firebase Cloud Messaging (FCM) HTTP Legacy API protocol to send push notifications in JSON to android mobile devices. For the client side I use react-native-fcm library.
The aim is to send the notification to the particular devices when the application is in 3 states:
1) running
2) background running
3) killed
According to the documentation for FCM there are 3 different types of messages which can be sent via FCM service:
1) notification (has predefined fields)
2) data (set whatever fields you want)
3) mixed (notification + data).
The logic of listening the event for incoming message on the client side using react-native-fcm is the next:
this.notificationEmitterSubscription = FCM.on(FCMEvent.Notification, notif => {
if(notif && notif.fcm){
//received from Firebase
if(!notif.local_notification && notif.title){
let badge = parseInt(notif.badge);
FCM.setBadgeNumber(badge);
this.showNotification(notif.title, notif.body, badge);
}
//notification is clicked
if(notif.opened_from_tray){
FCM.setBadgeNumber(0);
this.executeNavigateAction(notif.fcm.action); //this method just navigates user to a particular screen in the application
}
}
});
Show notification method is implemented in this way:
showNotification(title, body, badge) {
FCM.presentLocalNotification({
body: body,
priority: "high",
title: title,
sound: "default",
large_icon: "ic_launcher",// Android only
icon: "ic_launcher",
show_in_foreground :true, /* notification when app is in foreground (local & remote)*/
vibrate: 300, /* Android only default: 300, no vibration if you pass null*/
lights: true, // Android only, LED blinking (default false)
badge: badge,
local: true,
click_action: NAV_SCREEN_NAME
});
}
notif.title, notif.body and notif.badge are the fields which are set in data section of the message when sending it via FCM API. In other word the message is sent in the (3) mixed form:
{
"registration_ids" : ["FCM_device_token_1", "FCM_device_token_2"],
"notification" :
{
"title" : "fcm notification message title",
"body" : "fcm notification message body",
"badge" : 111
},
"data" :
{
"title" : "fcm data message title",
"body" : "fcm data message body",
"badge" : 222
}
}
If the message is sent as (1) notification (without "data" section in the message, in this case some changes in the reading the fields are necessary, to change notif.title -> notif.fcm.title, but this is not the main point in the question) or mixed (3) then the listener for the notification is NOT triggered when application is (2) background running and (3) killed. As a result, the badge number is not set. BUT despite the fact that the method showNotification(title, body, badge) is not called (because the event listener is not triggered) the message IS shown. It seems that react-native-fcm has internal implementation for this situation to show (1) notification and (3) mixed messages automatically when application is not running. In other words, the listener IS called for (1) notification and (3) mixed messages only when the application is (1) running and IS NOT called when the application is in the (2) background or (3) killed and does NOT show the badge number. However, the message itself IS shown for all situations.
Another approach is to send a (2) data message. This type of FCM message triggers the listener (notificationEmitterSubscription) for all states of the application: (1) running and (2) background running and (3) killed. As a result, badge number is set in all these states. However, despite the fact that method showNotification(title, body, badge) is called whenever a data FCM message is received, method FCM.presentLocalNotification does NOT display the message if the application is killed.
Thus, in few words, I have a question.
How to:
EITHER display a badge number when (1) notification or (3) mixed message is received and the application is in (2) background running or (3) killed
OR display a (2) data message when the application is (3) killed?
Thank you!
The solution has been found. The statement is that: there is no code running if the application is killed, so the messages is handled and displayed out of your code. The message has to be set in the next format to be shown for the killed status:
{
"registration_ids" : ["FCM_token_1", "FCM_token_2"],
"data" :
{
"custom_notification" :
{
"title" : "FCM test title",
"body" : "FCM test body"
},
badge : 1
}
}
In your react-native application in the notification handler the notification is received as a json value of notif.custom_notification property. So, the code looks like this:
this.notificationEmitterSubscription = FCM.on(FCMEvent.Notification, notif => {
if(notif && notif.fcm){
//received from Firebase
if(!notif.local_notification && notif.custom_notification){
let message = JSON.parse(notif.custom_notification);
let body = message.body;
let title = message.title;
let badge = parseInt(notif.badge);
FCM.setBadgeNumber(badge);
this.showNotification(title, body, badge);
}
//notification is clicked
if(notif.opened_from_tray){
FCM.setBadgeNumber(0);
this.executeNavigateAction(notif.fcm.action);
}
}
});
The issue can be solved as a resolved one.
I am using the Gmail API for Android for an application to send emails.
I want to send the mails such that they are received in the Social group of messages.
So is it possible in any way that I can set the labels for an email while sending it using the Gmail API ?
It is possible for us to set labels while sending mails through mail.google.com so how can the same be achieved with the Gmail API ?
You cannot specify the labels message should have when sending it. Under what tab certain messages should end up under is up to the user.
But if you are sending a message to the user himself howewer, it's not that hard to modify the message once it has been sent. When you send a message, you get all the label that were applied to the message in the response. Just send a message, and then modify the labels, and you are done.
Here's an example (with regular http-requests, but you could do the same with one of the client libraries):
// Base64-encoding the message and making it url-safe by replacing
// all '+' with '-', and all '/' with '_'.
btoa("To: example#gmail.com\n" +
"From: example#gmail.com\n" +
"Subject: Cool man\n\n" +
"Here is the message").replace(/\+/g, '-').replace(/\//g, '_');
// => "VG86IGV4YW1wbGVAZ21haWwuY29tCkZyb206IGV4YW1wbGVAZ21haWwuY29tClN1YmplY3Q6IFRoaXMgaXMgdGhlIHN1YmplY3QKCkhlcmUgaXMgd2VyZSB0aGUgbWVzc2FnZSBnb2Vz"
Sending the message:
POST https://www.googleapis.com/gmail/v1/users/me/messages/send
{
"raw": "VG86IGV4YW1wbGVAZ21haWwuY29tCkZyb206IGV4YW1wbGVAZ21haWwuY29tClN1YmplY3Q6IFRoaXMgaXMgdGhlIHN1YmplY3QKCkhlcmUgaXMgd2VyZSB0aGUgbWVzc2FnZSBnb2Vz"
}
Response
{
"id": "150866b2f6956617",
"threadId": "150866b2f6956617",
"labelIds": [
"SENT",
"INBOX",
"UNREAD"
]
}
Then, I just the add the CATEGORY_SOCIAL-label to get it to show under the social-tab (removing the INBOX-label will not show it at all).
Request
POST https://www.googleapis.com/gmail/v1/users/me/messages/150866b2f6956617/modify
{
"addLabelIds": [
"CATEGORY_SOCIAL"
]
}
Worked great!
I'm developing in Titanium a cross platform app that runs on IOS and Android. To send my push notification I'm considering using Pushwoosh but I'm open for suggestion.
On the app certain parameters are saved locally that will effect the content of the push notification. Is it now possible to get these locally saved parameters to Pushwoosh so I can send custom notification and how would I do that?
Yes, it's called a payload.
Not sure how PushWoosh works with payloads... but you can use Parse.
When you receive the Push you get out of that the custom payload data (max size is 256 bytes and in iOS8+ it's 2 Kb of data) and save it into your App:
Ti.Network.registerForPushNotifications({
types: [ Ti.Network.NOTIFICATION_TYPE_BADGE, Ti.Network.NOTIFICATION_TYPE_ALERT, Ti.Network.NOTIFICATION_TYPE_SOUND ],
success: function(e) { Ti.App.Properties.setString('token', e.deviceToken); subscribePush();},
error: function (e) { alert("error: " + JSON.stringify(e)); },
callback: function (e) {
alert('the push ' + JSON.stringify(e) ); // Works Only on RUN Device
// Store your Data in the app
Ti.App.Properties.setObject('myPushedData', e.data)
}
});
It's definitely possible with Pushwoosh - you can pass any custom JSON data in a "key":"value" format along with your push notifications from both PW Control Panel and through API ("data" parameter). In the resulting push payload this data is passed as a value of the "u" parameter.
Please refer to the code sample from Pushwoosh Titanium guide on how to access this additional custom data from the payload:
// Process incoming push notifications
function receivePush(e) {
alert('Received push: ' + JSON.stringify(e));
Ti.API.warn("push message received: " + JSON.stringify(e));
//send stats to Pushwoosh about push opened
PushWoosh.sendPushStat(e.data.p);
var pushwoohURL = e['data']['l'];
var a = Ti.UI.createAlertDialog({
title : 'New Message',
message : e.data.alert,
buttonNames : ['Open', 'Close']
//message : JSON.stringify(e.data) //if you want to access additional custom data in the payload
});
a.show();
a.addEventListener('click', function(e) {
if (e.index == 0) {
Titanium.Platform.openURL(pushwoohURL);
}
});
}
xamarian Android project not always receives the push message triggered from push.gcm.send(). Broadcast receiver calls only onregister() first time, but not calls onmessage(). my php server script works well with https://android.googleapis.com, and it calls onmessage() of broadcast reciver. Also Native android project with azure mobile service use push sharp client behaves same, it doesn't call onmessage() when push.gcm.send() executed in azure server. let me know what iam doing wrong, i use the perfect Applicationkey,server key,project number,........Below is the log details.I am getting status code 201.
Log entry details:
INFORMATION
Test Push notification sent: APA91bELUme4gM35eHBH4dmxo7AVBkmVu6Gsown_8zrROb5SsKzHn7MgpypBirmmDDuyPlr8hRjBDRX2lBc_j9voAPYv2RotXiVTHMaXFRRADu0xNfrPk-g-bCkfsCO7Uv-OnPMW8bgmTHIX8u8exKpGxfSrFZvN8dEDAoC5iw { isSuccessful: true,
statusCode: 201,
body: '',
headers:
{ 'transfer-encoding': 'chunked',
'content-type': 'application/xml; charset=utf-8',
server: 'Microsoft-HTTPAPI/2.0',
date: 'Tue, 27 May 2014 19:40:00 GMT' },
md5: undefined }
Input Script:
function insert(item, user, request) {
request.execute({
success: function() {
// Write to the response and then send the notification in the background
request.respond();
push.gcm.send(item.channel, item.text, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
});
}
Please double-check your test is correct by ensuring your client code matches the completed example with appropriate fields replaced from here: http://go.microsoft.com/fwlink/p/?linkid=331303&clcid=0x409
The full instructions are found at: http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-mobile-services-android-get-started-push/
If you still encounter issues after double-checking these, send me email at toddreif#microsoft.com with your Mobile Service account name.
Refer to Migrate a Mobile Service to use Notification Hubs.
Microsoft had been upgraded the Mobile Service, to push notifications powered by Notification Hubs. You will not be affected if you created the mobile service before the upgrade.
Base on the response { isSuccessful: true, statusCode: 201, body ... }, it indicate that your Mobile Service is the new version.
If you prefer to send push without Notification Hubs, don't use push.gcm.send, use the following code snippet instead.
var legacyGcm = require('dpush');
legacyGcm.send(your_GCM_APIKEY, regId, item, function (error, response) {
if (!error) {
// success code
} else {
// error handling
}
});
I am creating a messaging application, and like any mobile messaging service Push Notifications are needed for when the app isn't connected to the backend.
Let me use an example to out line the scenario I'm experiencing.
There is a conversation between User A & User B
// User B's application is idle (not receiving messages from our backend)
// User A sends User B a message
A --> B
Because User B isn't connected, he/she is sent a push notification beckoning him/her to open the app and sync the message.
User B's phone now has one notification on his/her lock screen, like so
Message from User A
then ...
// User A sends User B another message
A --> B
User B's phone now has two separate notifications on his/her lock screen from User A.
These messages read like this:
Message from User A
Message from User A
BUT, I would like the lockscreen to read something like this
Message from User A (2)
I am unsure how to get the notifications to aggregate once they reach the phone, assuming they have metadata attached to them that articulates who the "sender" of the message is.
Currently, this is the payload I am sending up to Urban Airship
function sendPushNotification (event, user) {
if (event.type == 21 || event.type == 22 || event.type == 24) {
var sender = event.sender.username;
var alert = "from #" + sender;
var reciever = user.username;
var payload = {
"audience": {
"alias" : reciever
},
"device_types": [ "ios", "android" ],
"notification": {
"ios": {
"alert": alert,
"badge": "+1",
"sound": "default",
"extra": { "username": sender }
},
"android": {
"alert": alert,
"collapse_key": "inboxappco",
"extra": { "username": sender }
}
}
};
console.log("Hello 2");
pushNotification(payload);
} else {
// modularize for general purpose notifications
}
}; // end sendPushNotification function
Any advice on how I can leverage the the sender metadata, to aggregate consecutive push notifications from the same person into one line item on the lock screen?
Thanks in advance SOF.
It appears that your app will need to create your own custom push notification object and somehow get access to the NotificationManager
PushManager.shared().setNotificationBuilder(new YourCustomNotificationObject());
I'm not sure how Urban Airship exposes the NotificationManager, but you need to use the setGroup("arbitrarygroupname") accessor in your NotificationBuilder
Unless you are targeting minimum API level 20, then this is accessor is not available, so you have to use the v4+ NotificationCompat.Builder object, and make sure your support libraries are version 20 or higher.
EDIT, as of UrbanAirship 4.0.3 for Android this is not possible, server side you can keep track of a series of push notifications and use the collapse_key parameters with each push, collapse_key will replace push notifications of the same type, so your SERVER will have to send push notifications with different names, with the name being Message from User A (2) instead of letting the Android system handle that client side