I am using a phonegap-plugin-push for receiving notifications in Cordova Application. I am deploying on android Marsh-mellow for testing.
I want to see and store the contents of the Notifications received through Firebase Console when the app is in background.
Here is my Code -
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
var push = PushNotification.init({ "android": {"senderID": "91254247XXXX"}});
push.on('registration', function(data) {
console.log(data.registrationId);
//document.getElementById("gcm_id").innerHTML = data.registrationId;
});
push.on('notification', function(data) {
alert("On Notification function!!");
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
console.log("notification event");
console.log(JSON.stringify(data));
alert(JSON.stringify(data));
//Do something
});
push.on('error', function(e) {
alert(e);
});
}
When the app is in foreground (on screen) I receive the contents (title, message, data, etc.) properly and I am able to see them in alert box directly in the app.
But when app is in background (not on screen but running in backround), I get the notification in Notification Area. When I click on the notification received, it is redirecting me to the last opened page in the app.
The function push.on('notification', function(data) {} is not called. No alert messages are shown. Can someone help me how to access the notification message and data?
I found the answer after 2 days of research. We have to set "content-available" to 1 in the data field. Else it wont call on notification block if app is in background.
And this is not possible as of now through Google Firebase Console.
We have to send our custom payload messages (data or notification or both) seperately using any one of the firebase servers.
Detailed info can be found on the plugin's GitHub Page on background notifications.
I used NodeJs firebase-admin. I followed these setup guidelines and these steps for sending messages and it worked for me.
Here is my working code (NodeJS) -
var admin = require("firebase-admin");
var serviceAccount = require("pushnotificationapp-xxxxx.json"); //this is the service account details generated from server
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://pushnotificationappxxxxx.firebaseio.com/" //your database URL here.
});
var registrationToken = "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX....."; //registration token of the device
var payload ={
"data": {
"title": 'Test Push',
"message": 'Push number 1',
"info": 'super secret info',
"content-available": '1' //FOR CALLING ON NOTIFACATION FUNCTION EVEN IF THE APP IS IN BACKGROUND
}
};
//send the notification or message
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
UPDATE :
I implemented the same using php server too.
Here is my working php code for sending notifications using HTTP POST to FCM server-
<?php
$url = 'https://fcm.googleapis.com/fcm/send';
$data =
array(
"to" => "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX.....",
"data" => array(
"title"=> 'Test Push',
"message"=> 'Push number 1',
"info"=> 'super secret info',
"content-available"=> '1')
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => array("Content-Type:application/json",
"Authorization:key=AAAA1HfFM64:APA91XXXX...."), //this is the server authorization key from project settings tab in your Firebase Project
'method' => 'POST',
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo "Caught an error"; }
else{
echo $result;
}
?>
i was going through the same issue but i added "content-available": '1' also but my phone was not receiving any background push.
Finally i found that it was issue with my phone as mentioned here: https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#huawei-and-xiaomi-phones
Huawei and Xiaomi Phones
These phones have a particular quirk that when the app is force closed that you will no longer be able to receive notifications until the app is restarted. In order for you to receive background notifications:
On your Huawei device go to Settings > Protected apps > check "My App" where.
On your Xiaomi make sure your phone has the "Auto-start" property enabled for your app.
On your Asus make sure your phone has the "Auto-start" property enabled for your app.
Hope it will help someone.
Related
I am following the code mentioned in the docs to send a notification through Admin SDK.
exports.sendNotification = functions.https.onRequest((req, res) => {
const message = {
data: {
type: "warning",
content: "A new weather warning has been created!",
},
topic: "weather",
};
admin
.messaging()
.send(message)
.then((response) => {
console.log("Successfully sent message:", response);
})
.catch((error) => {
console.log("Error sending message:", error);
});
res.end();
});
After running the above code using Firebase emulator, the console prints
i functions: Beginning execution of "us-central1-sendNotification"
i functions: Finished "us-central1-sendNotification" in ~1s
> Successfully sent message: projects/foo/messages/2216986345254434321
However, I don't see any notification on the device.
NOTE: If I send the notification through Firebase Notification composer or Postman to the same topic weather, the device does show a notification. I don't know what's wrong in the code above.
You're sending a data message which requires you to handle the display yourself.
Checkout Message Types for the different types of FCM messages.
In order to see your notifications, you can do either of the following:
Send a notification message instead of a data message, this means you'll use the notification key in place of the data key in your message payload object like below:
const message = {
notification: {
title: "warning",
body: "A new weather warning has been created!",
},
topic: "weather",
};
Display the data message using the flutter_local_notification plugin as outlined in firebase_messaging's documentation
I am using react-native and amplify to send push notifications to devices via AWS Pinpoint. I can get the generated token for the devices. But I just need to send push notifications using user Id. I try to update the endpoint, but it's not working. Can anyone suggest me the proper way to handle this?
PushNotification.onRegister((token) => {
console.log('in app registration', token);
Analytics.updateEndpoint({
address: token,
channelType: "GCM",
OptOut: 'NONE',
userId: "12345"
}).then(data => {
console.log(data)
}).catch(error => {
console.log(error)
});
});
It depends how you would like to send the push notification. We have created UI that allows sending a push, which triggers a lambda.
Firstly, you need the app to update the endpoint with the token / address as you have done.
Then you can send the push from the lambda, as shown in this code.
const sendPushNotification = async () => {
const params = {
ApplicationId: "PINPOINT_ANALYTICS_ID",
SendUsersMessageRequest: {
Users: {
"12345": {} // replace numbers with userid here connected with pinpoint endpoint
},
MessageConfiguration: {
APNSMessage: {
Action: 'OPEN_APP',
Title: 'Title of push notification',
SilentPush: false,
Sound: 'default',
Body: 'Message you would like to send'
},
GCMMessage: {
Action: 'OPEN_APP',
Title: 'Title of push notification',
SilentPush: false,
Sound: 'default',
Body: 'Message you would like to send'
},
},
},
};
return pinpoint.sendUsersMessages(params).promise();
};
await sendPushNotification();
I was able to do that using #aws-amplify/analytics library. Following is the method that I used.
Analytics.configure(aws_exports);
PushNotification.onRegister((token) => {
//alert(token)
console.log('in app registration', token);
Analytics.updateEndpoint({
address: token, // The unique identifier for the recipient. For example, an address could be a device token, email address, or mobile phone number.
attributes: {
// Custom attributes that your app reports to Amazon Pinpoint. You can use these attributes as selection criteria when you create a segment.
hobbies: ['piano', 'hiking'],
interests: ['basketball']
},
channelType: 'GCM', // The channel type. Valid values: APNS, GCM
userId: '221XWsdfER234',
// User attributes
optOut: 'ALL',
userAttributes: {
interests: ['football', 'basketball', 'AWS']
// ...
}
}).then((data) => {
console.log(data)
}).catch(error => {
console.log(error)
})
});
With Amazon Pinpoint, you can’t send transactional message as Push notification. Meaning, you can’t send direct Push notification to a specific recipient.
Amazon Pinpoint - Push notification supports sending notifications to a targeted audience by creating a campaign and segment.
If it’s for testing only, from Pinpoint dashboard, you can send Test message to a specific user by using User ID or by using device token.
Read more here =>
Sending Transactional Messages from Your Apps - Amazon Pinpoint
I am using firebase function and sending the notification like below
let pushPayload = {
notification: {
title: 'Doodles Notification',
body: "push testing",
sound: 'default',
badge: '1'
}
};
//push tokens need to be of customer as well as all the admins in the system. fetch admin push tokens
admin.messaging().sendToDevice(pushToken, pushPayload).then(
(resp) => {
console.log("push notification sent using test method")
return
}
).catch(
(err) => {
console.log("Error sending push notification:" + JSON.stringify(err))
return
}
)
The client side ionic app has method like below:
this.fcm.onNotification().subscribe(data => {
console.log("push message is:" + JSON.stringify(data))
alert(data.aps.alert.body)
});
on ios this all works great. however on android, the console.log prints
{"wasTapped":false}
I am ok with the above expected property but where is the data? The firebase documentation is confusing around it and I am sort of lost what is the correct payload I need to use that works with both ios and android.
Your pushPayload also needs to have a data array to pass data. I believe you also need speech marks around your keys:
"notification":{
"title":"Doodles Notification",
"body":"push testing",
"sound":"default",
"badge":"1"
},
"data":{
"Key1":"Test",
"Key2":"More data"
}
Documentation
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
}
});