Google Cloud Messaging Push Notification: PushNotification - android

I am developing an ionic application with Google Cloud Messaging Push Notification with Visual Studio. First I add phonegap-plugin-push from https://github.com/phonegap/phonegap-plugin-push and insert my senderID which is Project number from Google Cloud Messaging API. Next, I add following code.
var push = PushNotification.init({
"android" : {
"senderID" : "9XX5XXX346XX"// This is your project number which you've created on Google Developers Console
},
"ios" : {},
"windows" : {}
});
push.on('registration', function(data) {
//data.registrationId
//send this token on server
});
push.on('notification', function(data) {
if (data.sound) {// play specific sound on notification received(When app running)
var snd = new Media('file:///android_asset/www/sound/' + data.sound);
snd.play();
}
if (!data.additionalData.foreground) {
// app is NOT RUNNING and new notification is RECEIVED
} else {
// app is RUNNING and new notification is RECEIVED
}
});
push.on('error', function(e) {
//alert(JSON.stringify(data))
// e.message
});
When I run my application in emulator and android device. It comes with eror PushNotification.init. May I know why?

Related

How to resolve Nifty cloud send push notification error from monaca (android)?

I have implemented nifty cloud for push notification service in monaca platform(android).
I can receive push notification send from nifty cloud mobile backend.
document.addEventListener("deviceready", function () {
console.log("app is ready");
window.NCMB.monaca.setDeviceToken(
"a111111111111111111111111111111111111111111111111111111111111111",//Application Key
"b111111111111111111111111111111111111111111111111111111111111111", //Client Key
"22222222222" //fcm sender id
);
}, false);
But i also need to send push notification from android. For this this i am following this
// "Application key" and "Client Key"
var ncmb = new
NCMB("a111111111111111111111111111111111111111111111111111111111111111", "b111111111111111111111111111111111111111111111111111111111111111"); //
var push = new ncmb.Push();
$scope.pushSend = function () {
push.set({
"immediateDeliveryFlag": true,
"target": ["android"],
"message": "Please input your test messge",
"deliveryExpirationTime": "3 day"
});
push.send()
.then(function (message) {
console.log(message);
})
.catch(function (err) {
console.log(err);
});
};
Now, I'm getting this error
this is my request header
I can see that in my request header X-NCMB-Apps-Session-Token is missing.
So why X-NCMB-Apps-Session-Token is not present in my request header and how to solve 404 (Not Found) problem.

How to send Push Notification Firebase

I am new to Firebase and the main reason I adapted to it from my old MySql DB is the ability to send push notification and dynamic links. I have been trying for the past two days to send notification to a group of people who have subscribed to a topic from my node.js script. The script always returns InternalServerError. I am able to send notification from the Firebase console but that is not good enough for my app as I need to implement dynamic notification (i.e. triggered by one users action).
So far I did not understand what was in the official docs and tried following a tutorial I found and I am currently here
app.get('/push',function(req,res){
/*var title = req.params.title;
var body = req.params.body;*/
// var confName = req.params.name;
var message = { //this may vary according to the message type (single recipient, multicast, topic, et cetera)
to: '/topics/ilisten',
// collapse_key: 'your_collapse_key',
notification: {
title: 'This is Title',
body: 'This is body'
},
data: { //you can send only notification or only data(or include both)
my_key: 'Conf Name here'
}
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!"+err);
} else {
console.log("Successfully sent with response: ", response);
}
});
})
My first question is what should I do in the to field so that all the users in my app reciece the notification.
I would also like to take a look at correct and complete implementation of this concept with android code. If anyone has such code please share it here as it would help the future Firebase users who cannot understand the official docs like me.
Following is one approach using node-gcm (https://github.com/ToothlessGear/node-gcm)
var gcm = require('node-gcm');
var sender = new gcm.Sender(<sender_key>);
var message = new gcm.Message();
message.addNotification('title', title);
message.addNotification('body', body);
sender.send(message, { topic: "/topics/" + topic }, function (err, response) {
if (err) console.error(err);
else console.log(response);
});

Get notification when a user wants to add data to the database

I'm about to begin working on a recipe Android app for my college final project, and I want users to be able to add recipes to the database. However, I don't want the data to be added right away, but I'd like to receive a notification whenever someone wants to add a recipe, so I can confirm it myself. I'm using back{4}app by the way.
How can I do such a thing in a not-so-complicated way? I was thinking to create an admin account for myself in the app itself, but is there any way to send the notifications to said account? I also want to be able to confirm recipe addition with a simple "Confirm" button from within the app, so will this require me to create an additional class for pending recipes? Will I need an admin account in any case?
all this can be achieve by using cloud code.
Parse.cloud.define("addRecipe", function(request, response) {
const query = new Parse.Query("recipe");
query.set("name", "name");
query.save({
success function(result) {
response(result);
//call push notification function from client or from cloud code when the error is nil
},
error: function(result, error) {
response(error);
}
});
});
this is an example of push notifications using cloud code.
push notification are not allow anymore from the client due to secure reason.
you should be subscribe to this channel
Parse.Cloud.define("pushsample", function (request, response) {
Parse.Push.send({
channels: ["channelName"],
data: {
title: "Hello!",
message: "Hello from the Cloud Code",
}
}, {
success: function () {
// Push was successful
response.sucess("push sent");
},
error: function (error) {
// Push was unsucessful
response.sucess("error with push: " + error);
},
useMasterKey: true
});
});
you should also implement some logic to your app in order to display recipes confirm by admin.
var recipe = Parse.Object.extend("recipe");
var query = new Parse.Query(recipe);
query.equalTo("confirm", true);
query.find({
success: function(results) {
//it will display recipes confirmed
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
});
you should also setup a admin system in your app or a website

Integrating a messenging function into Phonegap-App

i want to integrate a small chat / instant messaging function in my app and need a little start-up aid.
I've registered a Google Cloud Messaging Account and received a configuration file ("google-services.json", containing the project id) and a server API key.
The first question is: Do i have to make further settings in my google account so that the app gets all information needed for the messenging function?
The next question is, how to integrate the messenging function in my project.
What i've done (and what seems NOT to work):
In my index.html file, i have integrated the following code (XXXXXXXXX has been replaced with my sender ID):
<script type="text/javascript" src="PushNotification.js"></script>
<script>
var pushNotification;
function onDeviceReady() {
alert('Device is ready');
try {
pushNotification = window.plugins.pushNotification;
alert('Registering ' + device.platform);
if(device.platform == 'android' || device.platform == 'Android' ||device.platform == 'amazon-fireos' ) {
pushNotification.register(
successHandler,
errorHandler,
{
"senderID":"XXXXXXXXXXX",
"ecb":"onNotification"
});
alert('Registered the Android device');
alert('regID = ' + e.regid);
} else {
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"});
alert('Registered the iOS device');
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
//alert(txt);
alert('Error: ' + err.message);
}
}
// handle APNS notifications for iOS
function onNotificationAPN(e) {
if(e.alert) {
// showing an alert also requires the org.apache.cordova.dialogs plugin
navigator.notification.alert(e.alert);
}
if(e.sound) {
// playing a sound also requires the org.apache.cordova.media plugin
var snd = new Media(e.sound);
snd.play();
}
if(e.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);
}
}
// handle GCM notifications for Android
function onNotification(e) {
alert('EVENT -> RECEIVED:' + e.event);
switch( e.event )
{
case 'registered':
if( e.regid.length > 0 )
{
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
console.log("regID = " + e.regid);
alert(' REGID = ' + e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if(e.foreground) {
alert('--INLINE NOTIFICATION--');
// on Android soundname is outside the payload.
// On Amazon FireOS all custom attributes are contained within payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
// playing a sound also requires the org.apache.cordova.media plugin
var my_media = new Media("/android_asset/www/"+ soundfile);
my_media.play();
} else {
// otherwise we were launched because the user touched a notification in the notification tray.
if(e.coldstart)
//$("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
alert('--COLDSTART NOTIFICATION--')
else
alert('--BACKGROUND NOTIFICATION--')
}
alert('MESSAGE -> MSG: ' + e.payload.message);
//android only
alert('MESSAGE -> MSGCNT: ' + e.payload.msgcnt);
//amazon-fireos only
alert('MESSAGE -> TIMESTAMP: ' + e.payload.timeStamp);
break;
case 'error':
//$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
alert('ERROR -> MSG' + e.msg);
break;
default:
//$("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
alert('EVENT -> Unknown, an event was received and we do not know what it is');
break;
}
}
function tokenHandler (result) {
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
alert('iOS Result = ' + result);
}
function successHandler (result) {
alert('Android Result = ' + result);
alert('RegID = ' + e.regid);
}
function errorHandler (error) {
alert('Error = ' + error);
}
document.addEventListener('deviceready', onDeviceReady, true);
alert('regID = ' + e.regid);
alert('Reg code completed');
</script>
As i use Phonegab Build, i have added the following line to my config.xml file
<gap:plugin name="com.phonegap.plugins.pushplugin" version="2.4.0" />
The following plugins (which are also used) have been already part of the config file:
<gap:plugin name="org.apache.cordova.dialogs" />
<gap:plugin name="org.apache.cordova.media" />
My main questions are:
Where do i have to place the Server API Key?
Where do i have to place the google-services.json file (in which directory) and how is this file linked to he index.html
Further questions:
- Is the GCM Service really free? Because in the member area there is a display "Excpected fees this month: 0,00 €" --> will the fees increase?
- If a user downloads and installs my app from the playstore: How does HE get a sender ID and if i want to send him a message --> How do I know his sender ID to start messenging with him?
I haven't understood the GCM-thing in principle.
Can anyone give me a little help?
Best regards
Daniel
The GCM service itself is free, as mentioned here.
I'm not familiar with setting up Phonegap projects, but the google-services.json file was intended for use with the Google Services plugin for Gradle. Gradle itself is a build tool used by Android Studio. I'm not sure if Phonegap has a similar plugin, but in case it doesn't, what you'll be needing is the project number/sender ID. You register your app/client with that. More on this below.
You use your server API key in your server code, which is the app server that will be sending messages to your app.
More on registration. You'll need to check with some Phonegap tutorials, because GCM's new (and recommended) way for registering is through Instance IDs. It still uses the same sender ID, but you'll need to interface with Google Play Services to do this.

push notification success in console but not received in android device

i've to send push notification to android and apple devices, apple devices are getting the push notification but android not, its showing successfully sent notification but there's no notification in my android device.
following is my code, in this i'm sending one hardcoded device id and an API key:
var pushToAndroid=function(tokens,message)
{
var message = new gcm.Message();
var sender = new gcm.Sender('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
var registrationIds = [];
message.addData('id',message.title);
registrationIds.push('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
sender.send(message,['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'],2,
function (err, result) {
if(err) console.log(err);
else console.log("Send Notification Android"+ JSON.stringify(result));
});
};
output:
{"multicast_id":6582780084434899000,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1426068793442479%b980d923f9fd
7ecd"}]}
kindly tell what am i doing wrong?

Categories

Resources