Mobile
Article

Push Notifications in Ionic Apps with Google Cloud Messaging

By Wern Ancheta

Updated on January 13th to reflect comments and changes with the Google Cloud Messaging Platform

In this tutorial we're going to look at how to implement push notifications in an Android App using the Google Cloud Messaging Platform. We will be using the Ionic framework and Cordova to create the app. The server component will be implemented using Node. You can checkout all the code for the project that we will be building from Github.

Create a Google Console Project

The first step, is to create a new project on the Google Developer Console. You will need an account if you don't have one.

new project

Once the project is created, click on the APIs & auth menu found on the left side of the screen and then credentials. This allows you to create a new API key that you can use for the server. Click on Add credentials and select API key.

api key

Next you will be asked what kind of key you want to create. Select server key since the key will be primarily used in the server. Don't add an IP address yet and skip the step by not adding anything and click the create button. Note the resulting API key.

server api key

Still under the APIs & auth menu, click on the APIs link and search for Cloud Messaging for Android. This is the API needed, click and enable it.

enable gcm

Setting Up

Create a new ionic app that uses the blank template.

ionic start ionic-gcm blank

Move into the project directory and install Phonegap Builds' Push Plugin. This is used by the app to register the device and to receive push notifications sent by the server.

cordova plugin add https://github.com/phonegap-build/PushPlugin.git

At the time of writing, sound doesn't work when a notification is received. The default is to vibrate, even if you've set the phone to use sounds. If you want to play a sound, you have to change the GCMIntentService.java file. You can find it on the following path plugins/com.phonegap.plugins.PushPlugin/src/android/com/plugin/gcm

Open the file and add the following on lines 12 and 13.

import android.content.res.Resources;
import android.net.Uri;

And from lines 125 to 131.

String soundName = extras.getString("sound");
if (soundName != null) {
    Resources r = getResources();
    int resourceId = r.getIdentifier(soundName, "raw", context.getPackageName());
    Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceId);
    mBuilder.setSound(soundUri);
}

Remove line 105:

.setDefaults(defaults)

You can look at this pull request for reference.

If you have already added the android platform, you might need to update the corresponding file at platforms/android/src/com/plugin/gcm/GCMIntentService.java with the same changes.

Aside from the Push Plugin, we need to install the cordova whitelist plugin.

cordova plugin add cordova-plugin-whitelist

This activates the settings included in the config.xml file which can be found in the root directory of the Ionic project. By default, it allows access to every server. If you're planning to deploy this app later, you should to update the following line to match only those servers that your app is communicating with. This improves the security of the app.

<access origin="*"/>

Building the Project

Now we can start to build the project.

Requests Service

Create a services folder under the www/js directory and create a RequestsService.js file. This will be the service that passes the device token to the server. The device token is needed to send push notifications to a specific device. Add the following to the file.

(function(){

    angular.module('starter')
    .service('RequestsService', ['$http', '$q', '$ionicLoading',  RequestsService]);

    function RequestsService($http, $q, $ionicLoading){

        var base_url = 'http://{YOUR SERVER}';

        function register(device_token){

            var deferred = $q.defer();
            $ionicLoading.show();

            $http.post(base_url + '/register', {'device_token': device_token})
                .success(function(response){

                    $ionicLoading.hide();
                    deferred.resolve(response);

                })
                .error(function(data){
                    deferred.reject();
                });


            return deferred.promise;

        };


        return {
            register: register
        };
    }
})();

Breaking the code down. First we wrap everything in an immediately invoked function expression. This allows encapsulation of the code that's contained inside and avoids polluting the global scope.

(function(){

})();

Next we create a new angular service for the starter module. This module was created in the js/app.js file and was called starter, so it's referred to here. The service depends on $http, $q, and $ionicLoading, these are services provided by Angular and Ionic.

angular.module('starter')
    .service('RequestsService', ['$http', '$q', '$ionicLoading',  RequestsService]);

function RequestsService($http, $q, $ionicLoading){
    ...
}

Inside the RequestsService function, declare the base_url used as the base URL for making requests to the server. It should be an internet accessible URL so that the app can make requests to it.

var base_url = 'http://{YOUR SERVER}';

If you do not have a server where you can run the server component, you can use 'ngrok' to expose any port in your localhost to the internet. Download the version for your platform from the project downloads page, extract and run it. I'll show you how to run ngrok later once we get to the server part.

Returning to the code. We create a register function that will make a POST request to the server to register the device using the device token from the push plugin.

function register(device_token){

    var deferred = $q.defer(); //run the function asynchronously
    $ionicLoading.show(); //show the ionic loader animation

    //make a POST request to the /register path and submit the device_token as data.
    $http.post(base_url + '/register', {'device_token': device_token})
        .success(function(response){

            $ionicLoading.hide(); //hide the ionic loader
            deferred.resolve(response);

        })
        .error(function(data){
            deferred.reject();
        });


    return deferred.promise; //return the result once the POST request returns a response

};

Finally we use the revealing module pattern to expose the register method as a public method of RequestsService.

return {
    register: register
};

Add the javascript to index.html right after the link to the app.js file.

<script src="js/services/RequestsService.js"></script>

Open the plugin/com.phonegap.plugins.PushPlugin/www directory and copy the PushNotification.js file to the www/js folder. Add a link to it in the index.html file right after the link to the css/style.css file.

<script type="text/javascript" charset="utf-8" src="js/PushNotification.js"></script>

Registering the Device

In the app.js file, create a global variable for the Push Plugin. Add this code just after the closing brace for the $ionicPlatform.ready function.

pushNotification = window.plugins.pushNotification;

To register the device, call the register function. This function accepts 3 arguments. First is the function executed once a notification is received, second is the function executed if an error occured and third are options. The options is an object where you specify configuration for the push notification that will be received. From the code below, you can see the badge (the icon in the notification), sound and alert (the text in the notification) options. The ecb is the event callback function that gets executed every time a notification is received. This is the same function used in the first argument. Lastly, the senderId is the ID of the project that you created earlier on the Google Console. You can find it by clicking on the Overview menu of your project.

To register the device, call the register function. This function accepts 3 arguments. First is the function that will be executed once a notification is received, second is the function that will be executed if an error occurred and third is the options. The options is an object where you specify different options for the push notification that will be received. From the code below, you can see that you can enable the badge (the icon in the notification), sound or alert (the text in the notification). The ecb is the event callback function that gets executed every time a notification is received. This is basically the same function used in the first argument. Lastly, the senderId is the project number of the project that you have created earlier on the Google Console. You can find it by clicking on the Overview menu of your project.

Add this code to app.js:

pushNotification.register(
  onNotification,
  errorHandler,
  {
    'badge': 'true',
    'sound': 'true',
    'alert': 'true',
    'ecb': 'onNotification',
    'senderID': 'YOUR GOOGLE CONSOLE PROJECT NUMBER',
  }
);

Receiving Notifications

The onNotification function should be attached to the window object so that the plugin can find it. The argument passed to this function is the actual notification. You can check which type of notification event occured by extracting the event property.

This can have 3 possible values: registered, message, and error. The registered event is fired when the device is registered. The message event when a push notification is received while the app is in the foreground. And the error when an error occured. When the registered event is fired, check if the length of regid is greater than 0.

If it is then assume that a correct device token has been returned. Call the register function in the RequestsService service and pass the device_token as an argument. Once it returns a response, inform the user that the device has been registered.

Add this code to app.js:

window.onNotification = function(e){

      switch(e.event){
        case 'registered':
          if(e.regid.length > 0){

            var device_token = e.regid;
            RequestsService.register(device_token).then(function(response){
              alert('registered!');
            });
          }
        break;

        case 'message':
          alert('msg received: ' + e.message);
          /*
            {
                "message": "Hello this is a push notification",
                "payload": {
                    "message": "Hello this is a push notification",
                    "sound": "notification",
                    "title": "New Message",
                    "from": "813xxxxxxx",
                    "collapse_key": "do_not_collapse",
                    "foreground": true,
                    "event": "message"
                }
            }
          */
        break;

        case 'error':
          alert('error occured');
        break;

      }
};

When an error occurs, notify the user using an alert message.

Add this code to app.js:

window.errorHandler = function(error){
  alert('an error occured');
}

Playing Sounds

If you want to play a sound when a notification is received, we need to add the mp3 file inside the platforms/android/res/raw folder. Mine is named notification.mp3. Take note of the file name and we will add it to the server side later when pushing a notification. You can download some notification sounds here.

Server Side

The server is responsible for accepting the device token submitted from the app as well as sending push notifications.

Create a server folder inside the root directory of the project then create an ionic-gcm.js file. This is the file that will contain the code for running a node server. This file has three dependencies: express, node-gcm and body-parser. Install those using npm.

npm install express node-gcm body-parser

Open the ionic-gcm.js file and require those dependencies.

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

Use express.

var app = express();

Create a server that listens for requests on port 3000.

var server = app.listen(3000, function(){

 console.log('server is running');

});

Set the server to allow all request origins. This allows AJAX requests coming from any IP address.

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();
});

Create a global variable for storing the current device token. This will be updated when the /register route is accessed. And the current value will be used when the /push route is accessed.

var device_token;

Create a new route for the /register path. This is the route for device registration. You can access the device_token that was passed through the body property in the req object.

Note that I haven't added any code related to saving the device token into a database. I expect you to have your own so I put it there as a TODO. For now it uses the global device_token variable for storing the device token. Once you've saved the device_token, send the ok as a response.

app.post('/register', function(req, res){
    device_token = req.body.device_token;
    console.log('device token received');
    console.log(device_token);
    /*YOUR TODO: save the device_token into your database*/
    res.send('ok');
});

To send push notifications:

  1. Create a route for the /push path.
  2. In the callback function, create a new array that will store the device tokens and a variable that stores the number of times to retry sending the message.
  3. Create a new sender instance by calling the Sender function. This accepts the API key from the Google console.
  4. Create a new message by calling the Message function in the gcm object. This object is provided by the node-gcm package.
  5. Add the data to be passed in the push notification by calling the addData function of the message. This function accepts a key-value pair of the data to pass. The required keys are title and message. The title is the title of the push notification and the message is the content. In the example below, the sound key is also passed. This is the name of the sound file you want to play when the notification is received.
  6. Optionally, you can set the collapseKey to group notifications. This lets you send notification #1 with a collapseKey and then minutes later, notification #2 with the same collapseKey. What will happen is that notification #2 will replace notifiction #1. That is if the user still hasn't opened notification #1 when notification #2 arrives.
  7. delayWhileIdle is another optional property, if this is set to true, the notification isn't sent immediately if the device is idle. This means that the server waits for devices to become active before it sends the notification. Note that if the collapseKey is set, the server will only send the latest messages sent containing that collapseKey. Finally there's timeToLive which allows you to set the number of seconds that the message will be kept on the server when the receiving device is offline. If you specify this property, you also need to specify the collapseKey.
  8. This is another step that I expect you to implement on your own. Fetching the device_token from the database. In order to do that, you need to pass a user_id or other unique user identification. This would allow you to fetch the device_token by using that unique data as a key. In the example below, the value for the global device_token variable is used instead. So every time a new device is registered, that device will be the one that receives the notification.
  9. Push the device_token which you got from the database into the device_tokens array.
  10. Call the send function in the message object. This accepts the message, device_tokens, retry_times and the function to call once the message is sent.
  11. Send the ok response.
app.get('/push', function(req, res){

    var device_tokens = []; //create array for storing device tokens
    var retry_times = 4; //the number of times to retry sending the message if it fails

    var sender = new gcm.Sender('THE API KEY OF YOUR GOOGLE CONSOLE PROJECT'); //create a new sender
    var message = new gcm.Message(); //create a new message

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

    message.collapseKey = 'testing'; //grouping messages
    message.delayWhileIdle = true; //delay sending while receiving device is offline
    message.timeToLive = 3; //the number of seconds to keep the message on the server if the device is offline

    /*
    YOUR TODO: add code for fetching device_token from the database
    */

    device_tokens.push(device_token);

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

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

Run the server by calling it from the terminal:

node ionic-gcm.js

If you want to use ngrok to expose this server to the internet, open a new terminal window where you installed ngrok and execute the following command:

ngrok http 3000

This tells ngrok to expose port 3000 to the internet and assigns it a publicly accessible URL.

Deploying the App

Returning to the app. Navigate to the root directory of the app and update base_url in www/js/services/RequestsService.js to match the URL that ngrok provided.

var base_url = 'http://{YOUR SERVER}';

Add the android platform:

cordova platform add android

Don't forget to add the mp3 file to the platforms/android/res/raw directory for the sound to work.

Build the app by executing the following command:

cordova build android

Once that's complete, navigate to the platforms/android/build/outputs/apk/ directory and copy the android-debug.apk file to your Android device. Install it and open it. Once it's opened, it should forward the device token to the server.

It should show something similar to the following in the terminal window where you executed node ionic-gcm.js:

device token received
sjdlf0ojw3ofjowejfowefnosfjlsjfosnf302r3n2on3fon3flsnflsfns0f9un

You can now test the push notification by opening the following local URL in a browser:

http://localhost:3000/push

Your device should receive a push notification at this point. Here's a screenshot.

notification

Conclusion

That's it! In this tutorial, you've learned how to work with the Google Cloud Messaging Platform for Android in order to send push notifications to a Cordova app. If you have any questions, comments or problems then please let me know in the comments below.

  • http://careersreport.com Ida Nichols2

    ì want% to guíde you to amazíng online work opportunity.. 3-5 h of work a day.. payment at the end of each week.. performance dependíng bonuses…earnings of six to nine thousand dollars /month – merely few hours of your free time, a computer, most elementary familiarìty wìth www and trusted web-connection is what is needed…learn more by headìng to my page

  • http://careersreport.com Clarisa Turner

    ì want to guíde you to amazíng online work opportunity.. 3-5 h of work a day.. payment at the end of each week.. performance dependíng bonuses…earnings of six to nine thousand dollars /month – merely few hours of your free time, a computer, most elementary familiarìty wìth www and trusted web-connection is what is needed…learn more by headìng( to my page

  • http://careersreport.com Susan Grant

    I need to guide you to fantastic online freelancing opportunity… 3 to 5 h of work /a day… Weekly paycheck… Bonus opportunities…Payscale of $6k to $9k /month… Just several hrs of your free time, a pc, basic knowing of Internet and trusted internet-connection is what is required…Get% more information by visiting my disqus^profile

  • bill

    First off, excellent tut. How can I make the message custom? I have a chat app and when new messages come in, i’d like to send a push. And in the device console, show the new chat message. Is that possible with some tweeking? Or if not, perhaps just open the app from the console. Thanks

  • bill

    Everything seems to work put I’m getting this from the server: TypeError: Cannot read property ‘processIncomingMessage’ of undefined

    • Wern_Ancheta

      what platform are you deploying to?

  • Sanjay

    I follow step by step procedure. “An error occurred” alert box is coming… After $cordova run android. I use, var base_url = ‘http://127.0.0.1:3000’; ‘senderID’: Project number from google developer console. var sender = new gcm.Sender(‘API key number’); Any thing wrong on it. Please suggest me whats wrong on it.

    • MZulkarnain Jaranee

      Hi, do you solved the issue, “an error occured”?

      • Wern_Ancheta

        did you try Prateek’s suggestion above:
        instead of Project id we will have to use Project number as SENDER ID

  • Ozi Fauzi

    for php please

  • Wern_Ancheta

    I was also getting that error before. All I had to do was to go to the settings in the device and check ‘show notifications’. If that doesn’t work, remove the app then re-install it and check the setting again.

  • Jaidi Wael Leila

    thx for the tutorial but i have big problem my android cann’t build ith the plugin pushnotification,
    have a solution for this ??

    • Wern_Ancheta

      Hi Jaidi. Can you try removing the platform and then add it again:
      cordova platform rm android
      cordova platform add android

  • Mohan S Kumar

    Hi, Excellant arthicle. Thanks for that.. I have followed the approach however I am not getting device token.. not sure what could be the reason. any thoughts ?

    • Wern_Ancheta

      hi @mohanskumar:disqus did you make sure your base url can be accessed through the internet? also try to create another google project or refresh the API key.

    • MZulkarnain Jaranee

      Accidentally read your comment, if you using expres 4.0 and above, u have to install body-parser
      since it is not included the latest express

      npm install body-parser

      and add these two lines in the ionic-gcm.js:

      var bodyParser = require(‘body-parser’);
      app.use(bodyParser.json()); // add this line after declared var app = express();

  • Wern_Ancheta

    maybe you missed the definition of the onNotification function. Check the repo: https://github.com/sitepoint-editors/ionic-gcm

  • Prateek Rathore

    Great Tutorial but I have issues. in my node server service(running locally) its fetching the Device token.. when I Push message. its starts sending and sender.send() is called its shows push sent. But I don’t receive any Push notification on my device. and also result of sender.send() is null. can you help me out.

  • Prateek Rathore

    Totally worthy Tutorial. but one thing. which kept me holding is this Sender Id is not the project Id anymore. instead of Project id we will have to use Project number as SENDER ID. hope that would be helpful for other people as well.

    • Chris Ward

      Thanks @disqus_s5YKKASfrj:disqus

    • Rajesh J Nair

      its Not working For me. Can You Please share you Email or skype

    • Jameesh Moidunny

      hey, I have run this app in emulator, I dint receive any device token. I am new in Ionic. Can you please help me to fix it.

  • Basil

    Excellent tutorial, but I have some bugs!!

    when calling ionic serve I get :
    Uncaught ReferenceError: onNotification is not defined.

    And after installing the app on an android device, there is no device token sent to the running server !!!!

  • Patrick Ndukwe

    Can you send me your working source code?

  • Wern_Ancheta

    Hi Shukarullah, this tutorial is specifically for android only. Though you could use the same plugin that was used here. The server-side implementation and the steps you needed to setup push notifications for iOS is different.

  • MZulkarnain Jaranee

    Hi, for anyone using exress 4.0 and above.. please install body-parser since it is not included in the latest version of express.

    npm install body-parser

    and add these two lines in the ionic-gcm.js:

    var bodyParser = require(‘body-parser’);
    app.use(bodyParser.json());

  • Patrick Ndukwe

    I am having the same problem as well

  • Patrick Ndukwe

    When I run my code after starting my server http://localhost:3000/push. It returns ok. But on my server console I get this error: 401 – push sent to undefined. Then on my android phone the spinner keeps rolling and nothing happens. Please direct on where I am wrong.

    • MZulkarnain Jaranee

      Try my solution at the below comment. Might be due to express version.

    • adnkh

      Make sure you have entered the ‘project server key’ correctly in ‘ionic-gcm.js’

    • Wern_Ancheta

      hi Patrick, it means that the server hasn’t picked up the device token. In the console window where you have executed node ionic-gcm.js it should output: “device token received” and then your token before you can access the push route from the browser. Note that the senderID in app.js should now be set to the projectNumber in Google Console and not the projectID.

  • Rajesh J Nair

    I Done this tutorial Correctly. But its Not Getting the registering the device.

    • Rajesh J Nair

      The push Notification was Not Receving while when i was in wifi network . When i Connected Mobile Internet. All The Push Notification Come in Bulk

    • Wern_Ancheta

      Hi Rajesh. Did you try to add a console.log on the server under the /register route to see if its being called.

  • Niklas

    hello, Best tutorial….

    I have follow the tutorial from top to bottom, but all i get is: Cannot GET /register

    What can i do, hope someone have an ideé…

    • Wern_Ancheta

      Hi Niklas. Where are you getting this error? is it on the app after you have compiled it with cordova build? So when you launch the app it shows you that message immediately?

      • Niklas

        Hello thanks for The answer.. I get the error when i go to localhost:3000
        I cant register the device token…i only get this: device token received
        undefined….I have try everything. …

        • Wern_Ancheta

          Hi Niklas, the register route is called from the device, you’re not supposed to access it from the browser. The only route that you need to access from the browser is the push route. But the device needs to be registered first before it can work.

  • Wern_Ancheta

    Hi Mitko. How can you say that the register is working when you say that the pushNotification.register isn’t. The register function is being called on window.onNotification which is the callback for pushNotification.register.

    So there should be no way the device registration or the push will work if the function you are pointing out doesn’t work in the first place.

  • Wern_Ancheta

    haven’t encountered that error before. Can you link to a screenshot or type in exactly what’s in the alert.

  • Karthik Ravi

    @ Wern Ancheta, nice tutorial man , i have a doubt from how will(from where) frontend gets device token and sends it to server in req.body

  • Mohammed F. Absi

    excelant article and everything worked amazingly on my laptop using ngrok :)
    i wanna ask what to do if i want the host to be my website not on ngrok??
    what to do with the JavaScript file in the server and how can i keep it running on my website

    • Chris Ward

      That would be possible, you need to use a JavaScript task runner such as Grunt or a myriad other ways this could be accomplished, it’s pretty easy to get setup.

      • Mohammed F. Absi

        i have no idea on how to use this to integrate it into my webpage and how to make this if you have a tutorial or something like that?

  • Jacobs Hwang

    its work..!
    I really appreciate your help :)

  • Asef Ratul

    Hi, you wrote a great article. However, i have a question. How do you use the “ReqeuestsService” angularjs service outside of angular scope? Because, this service is not called from my window.onNotification function.

  • Alex

    the ecb is not being called, any suggestion on that. Thank you very much, i tried using the api 19 with the intel x86 HAXM emulator, previously it was working fine but now, the ecb is not being fired.

  • Jameesh Moidunny

    Hi wern, I have run this app in emulator, I dint receive any device token. I am new in Ionic. Can you please help me to fix it.

  • Jameesh Moidunny

    Hi wern, I have run this app in emulator, I dint receive any device token. I am new in Ionic. Can you please help me to fix it

  • Wern_Ancheta

    senderID should be the project number from the google console. If you’re using an emulator, you can check this out: http://stackoverflow.com/questions/20521600/android-emulator-not-receiving-push-notifications

  • Jeyenthaaran Nanjappan

    Hi Wern, Great Job, one of the very few comprehensive tutorial on push notification on the internet. Kudo Buddy.
    I have a question. Is it required for the app to register the device_token each and every time it runs ? Will the device token change frequently ?

    • Kingsley Simon

      @jeyenthaarannanjappan:disqus did u implement this with the new PushNotification plugin or with the plugin in this blog post that has already been deprecated?

      • Jeyenthaaran Nanjappan

        Oh Really, I do not know that. Thank you for the information. Can you please send me the link of new plugin.?

  • Kingsley Simon

    if i am not wrong, the phonegap push notification plugin used in this post has been deprecated, how does tht affect this blog post? The new plugin doesnt have PushNotification.js in it. Is this catered for?

  • Kingsley Simon

    i believe this blog post is completely outdated based on the fact tht the PushPlugin used in this blog post has been deprecated.

    • Chris Ward

      Thanks Kingsley, I will see if we can get it updated, but as you know, things change all the time!

  • OddSp

    Great tutorial! Best there is about Cordova push notifications. At least the best I’ve found after searching the web for weeks :-)

    However…

    I’ve almost got everything working. The app is building fine, and loaded on my phone. It gives a message of successful registration, and that also shows up in the Node terminal window.

    When i run localhost/push, I get this in the console window:

    sending to: APA[long key]
    null
    push sent to: APA[long key]

    No notifications arriving at my phone. I suspect that little line of null should tell me something. But what?

    • Wern_Ancheta

      the null in there is actually the error. If you check from here: https://github.com/ToothlessGear/node-gcm
      so if you get null for the error it means that it shouldn’t have any problems sending the notification. Its odd that it still doesn’t work since you’re already getting a key logged in there. Can you console.log the value of the response too?

      sender.send(message, device_tokens, 4, function(err, result){
      console.log(err);
      console.log(result);

      console.log(‘push sent to: ‘ + device_token);

      });

      • OddSp

        null

        { multicast_id: 823xxxx,

        success: 0,

        failure: 1,

        canonical_ids: 0,

        results: [ { error: ‘MismatchSenderId’ } ] }

        MismatchSenderID.. Let’s see what I can do to fix that :-)

        • OddSp

          And boom!

          I deleted all the server keys at the google console and created a new one.

          I had several server keys, maybe that was the problem? Or maybe I had simply done a stupid mistake copying from the wrong project. Now everything is working. Thank you!

  • Fabrice Kabongo

    Hi, I have a question, are they shown automatically on the phone or do I need to show them myself? Using local notification for example

  • Jameel Ahmad

    Hi Wern in my case errorcallback fired…what could be the issue

  • Babita Bhandari

    When I run this app then in my console follwing error is shown:-
    Uncaught ReferenceError: cordova is not defined in notificationpush.js line no 19

    • Nishanth Kabra

      even i see the same issue. is there any resolution?

      • Basu

        HI @Babita Bhandari and @Nishanth Kabra ,, How did you solve this issue?
        Can you please explain.
        Thanks
        basu

  • Jameel Ahmad

    Hi wern,
    i am getting this error “error = ‘java.lang.Long cannot be cast to java.lang.String’ ”
    at errorHandler function

  • Caio Laurino

    do you can share thi code project for me ? email ca.laurino@gmail.com

    • Chris Ward

      Hi @caiolaurino:disqus if you look in the first paragraph, there’s a link to a GitHub repo that has all the code you need.

  • Nishanth Kabra

    After adding the PushNotification.js to index.html , i get an error saying cordova not defined. Any pointers?

  • Ravindra S

    I’m new to ionic, its Not working For me. Can You Please share you Email or skype

  • Raksa Chao

    I need help on when user click on notification to open specific detail

  • Qiyu Zhao

    Hi Wern, Great tutorial! I have read many tutorials from you. They are really helpful!
    Here is the problem I am facing right now:
    I followed the whole process from this article, and I can successfully send the device token, and receive the “message” from GCM in my app. But, there is no any “System Notification” pops from the device. Can you help me on this?

  • Ravindra S

    Hi Wern Ancheta,

    I need ur help on small pice of code, can u help me?

  • Nishanth Kabra

    hey wern, i was able to push notifications in my ionic1 app, thanks to your neat tutorial.
    However we are in the process of migration from ionic1 to ionic2 beta. Do you have any plans for have the push implementation in ionic2 any soon?

    • Chris Ward

      Hi @nishanthkabra:disqus We have been looking at ionic2 articles generally and until now have found it too unreliable. We may look at some updates in a month or two, but not quite yet.

      • http://matheo.co Mateo Tibaquirá Palacios

        with Angular 2 Release Candidate out, and Ionic 2 beta 6 released, what’s left? any specific cordova plugin to be implemented in ionic-native?

        • Chris Ward

          I’m just passing on what my authors have said, but I can try asking again.

  • Mahesh Yatageri

    How to get device_token , i’m not getting “device_token”

    Thanks in advance ..

  • Victor Azevedo

    You probably have to run in the cellphone… This error is usually when you´re trying to run in browser. Contact me v.azevedo9@gmail.com

    • Mariam Jamal

      Hey @disqus_a97Li9UA3X:disqus , I keep getting the ionic loading sign and doesn’t go. Seems like the app is stuck at this point. Any solutions?

  • Mahesh Yatageri

    I’m not getting notification if app is closed , Please any suggestion for this …

    Please mail me the solution mvyatageri@gmail.com

  • Nishanth Kabra

    Yup, you register the device ID in you storage or database whenever push.on(“registration”) fires and then whenever you want to send the push notification , one can pull back all the stored device IDs and send notifications at once.

  • Nishanth Kabra

    Hi, did you try doing this on emulator or browser? If yes then dnt do it. Instead try deploying your app to device only then native plugins like push, camera won’t throw errors. Attach a screenshot of error if possible.

  • Seyi Falaiye

    Hello everyone. I need help with this. I have spent some time on it so far.

    No respite. Please can anyone help ? I am willing to pay for be assistant..

    Thanks in anticipation .

  • Suraz Khanal

    How did you solve this?

  • Manoj Charleston

    I run this app on mobile but i can’t get notification, i run register on URL it will be not work ,so what is a problem please help me out

  • Richard

    I get the following when I try push.on(‘registration’, () => {…: EXCEPTION: Error: Uncaught (in promise): TypeError: push.on is not a function.

  • Naresh1985

    I followed the steps given above but my ecb callback function is not getting called and due to which device is not getting registered. Please help me to know what I am missing. I have followed the exact steps given.

  • Naresh1985

    I am getting 401 error while sending notification to device. I have enable Google Cloud Messaging and I have used API Key in code. Please let me know what I am missing.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Mobile, once a week, for free.