Sunday 22 May 2016

send push notification in android using node js?


send push notification in android ?
send push notification in android using node-gcm ?


save below code pushnotification.js

run code with this command

node pushnotification.js

register your token using  /register api call

open http://localhost:3000

send push notification
http://localhost:3000/push  (open in browser)







var express = require('express');
var gcm = require('node-gcm');


var app = express();


var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());


var server = app.listen(3000, function() {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port)
});

var device_token= " ";


// your device token like :
 //APA91bEnA2xyEmfyhWr2OKlAalBO95vo0tVWjSs5r7nk6A8TBW7wqfFGURWjp4LIVh7HfM7/
// W-kaw3mAd_c0I3rwkOurQ1pYB6UtPsfNTEGzjQaQ




app.use(function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});


app.post('/register', function(req, res){

    device_token = req.body.device_token;
    console.log('device token received');
    console.log(device_token);
    res.send('ok');
});

app.get('/push', function(req, res){

    var device_tokens = [];
    var message = new gcm.Message();
    var sender = new gcm.Sender(' your sender Key');

  //sender Key Like :  AIzaSyCu_w--TOdrwU

    message.addData('title', 'New Message');
    message.addData('message', 'Hello this is a push notification');
    message.addData('sound', 'notification');

    message.collapseKey = 'testing';
    message.delayWhileIdle = true;
    message.timeToLive = 3;

    console.log('sending to: ' + device_token);

    device_tokens.push(device_token);

    sender.send(message, device_tokens, 4, function(result){
        console.log(result);
        console.log('push sent to: ' + device_token);
    });

    res.send('ok');
});

1 comment:

  1. Its a wonderful post that you are giving to us.I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.Custom essay writing services provides you the better tips for writing an essay that have been created by well educated and qualified writers.

    ReplyDelete