Push Notifications Plugin Support added to PhoneGap Build

January 24, 2013By 81 Comments

pgb I’m happy to post today there is now support for a generic push notifications plugin for PhoneGap Build. The new plugin is called PushPlugin and works for both iOS and Android push notifications. The iOS support is based on the Apple Push Notifications Service (APNS) and the Android support is based on Google Cloud Messaging (GCM). This has been a highly awaited need and I’m so glad I can finally share the good news. apple-push-notification-service

The details are all outlined well here with some sample code but I also created a quick sample project you can use for a reference that will work for both iOS and Android. I put the whole project including the XCode project in github, but you really only need the www folder for PhoneGap Build. There’s also a config.xml included you can use that includes the plugin reference there and is required for the native code to be added when built through PhoneGap Build. You will just need to change the application name, author and personal information in there to match your own :) You will also need to change the GCM id to match your sender id in the index.js file. Also, see my previous tutorials on push notifications for iOS and Android to get some sample code in PHP or node.js to send a push notification quickly for testing so you can see it all in action. Those posts used the previous plugins available however, you should use the most currently supported PushPlugin one now. Those posts also talk in-depth about signing up for GCM and how to use APNS as well.

I will also be holding two webinars on push notifications in February via Adobe TechLive, so come check those out for a walkthrough of how to get started with adding push notifications to your application for iOS and Android. I will talk more about the APIs and how to use them at that time as well. The PhoneGap Build team is busy working on additional support for more plugins. The currently supported ones can be found here: http://build.phonegap.com/docs/plugins.

The important parts of the code are outlined in the PushPlugin documentation but I’m also showing them from my sample here. It’s easier to see quickly how this new plugin could be used to register your device to receive notifications, and how you might handle the incoming message simply in the following:

    receivedEvent: function(id) {
        var pushNotification = window.plugins.pushNotification;
        if (device.platform == 'android' || device.platform == 'Android') {
            pushNotification.register(successHandler, errorHandler,{"senderID":"834841663931","ecb":"onNotificationGCM"});
        }
        else {
            pushNotification.register(this.tokenHandler,this.errorHandler,   {"badge":"true","sound":"true","alert":"true","ecb":"app.onNotificationAPN"});
        }
...
    }

   // iOS
    onNotificationAPN: function(event) {
        var pushNotification = window.plugins.pushNotification;
        console.log("Received a notification! " + event.alert);
        console.log("event sound " + event.sound);
        console.log("event badge " + event.badge);
        console.log("event " + event);
        if (event.alert) {
            navigator.notification.alert(event.alert);
        }
        if (event.badge) {
            console.log("Set badge on  " + pushNotification);
            pushNotification.setApplicationIconBadgeNumber(this.successHandler, event.badge);
        }
        if (event.sound) {
            var snd = new Media(event.sound);
            snd.play();
        }
    },
    // Android
    onNotificationGCM: function(e) {
        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.
                    alert('registration id = '+e.regid);
                }
            break;

            case 'message':
              // this is the actual push notification. its format depends on the data model
              // of the intermediary push server which must also be reflected in GCMIntentService.java
              alert('message = '+e.message+' msgcnt = '+e.msgcnt);
            break;

            case 'error':
              alert('GCM error = '+e.msg);
            break;

            default:
              alert('An unknown GCM event has occurred');
              break;
        }
    }

Please see the sample for the rest of the code.

Filed in: CordovaMobile DevelopmentPhoneGapPush Notifications Tags:

About the Author ()

Comments (81)

Trackback URL | Comments RSS Feed

  1. Nikhil says:

    Thanks Holly!!!

    Gr8 work for putting it together.

  2. Cesidio says:

    This is awesome news. One less headache to manage. Great job by yourself and the whole Cordova/Phonegap team

  3. Brian says:

    Holly, just finished implementing the example and running through the git tests. Works as described.

    Do you know how to go from the regid from Google/Android to a 3rd Party like Urban Airship? They use APID, which seems to come from adding their jar to the project. If you are using Phonegap Build, this doesn’t seem like an option.

    Am I missing something obvious here…?

    Thanks!

  4. Birdaram Gehlot says:

    Awesome nice .

  5. Tim says:

    I’m very pleased that this is finally out because it will save our development team a lot of time when deploying on iOS. Sounds like your Facebook connect plugin is on the way as well, which gives us all the plugins we need to use Build. However, like Brian i’m confused how this will work with services like Urban Airship where tokens are registered through their client library. To my knowledge, their documentation does not expose the endpoint for registering tokens.

  6. Ed says:

    This is indeed great news! I am also interested in 3rd party push providers. We use PushWoosh and I have heard rumors of a PushWoosh plugin for PhoneGap Build. Any info is appreciated and keep up the great work.

  7. Ed says:

    Thanks for the reply Brian, that makes perfect sense. One more question (you knew it was coming) what about plans for supporting other devices with this plugin — specifically BlackBerry, Win8 and Win8 phones?

  8. Hi guys!

    I know there are other plugins for PushWoosh and Urban Airship services outside of the generic one that is now supported in PhoneGap Build. The generic plugin that is supported now was actually built based on the original Urban Airship plugin, however after taking a look at the latest (which appears to be here: https://github.com/urbanairship/phonegap-ua-push), it looks like there are more specific APIs there for UA.

    PushWoosh also has plugins for PhoneGap outside of this generic one supported for Build. The PG Build team is working on adding support for these 3rd party plugins from UA and PushWoosh, but as of today you would not be able to use those specific ones with PG Build. You would just need to build your .ipa and .apk using the manual means per platform (like using XCode/Eclipse+PhoneGap) for development. You can see prior posts I’ve done on implementing with PushWoosh in this manner on both platforms. I haven’t tried the Urban Airship plugin and service myself yet but it looks to be a pretty similar approach if you were to implement it manually (outside of PG Build).

    The team is aware of the need for these other plugins, and I hope to report more news soon on when it is coming.

    Hope that helps clarify some :)!!
    Holly

  9. Kostas David says:

    I downloaded the www folder from here: https://github.com/hollyschinsky/PhoneGapBuildPushProject2/tree/master/www

    I did this:
    I changed Sender_ID from index.js to mine, I uploaded the zip file to PhoneGap Build and installed the apk on my Android 2.2 device.
    It didn’t work so I put a try/catch handler to catch the error.

    The error caught was: successHandler not defined
    I supposed that it needs to be defined absolutely so I changed this line:

    pushNotification.register(successHandler, errorHandler,{“senderID”:”**********”,”ecb”:”onNotificationGCM”});

    to that:
    pushNotification.register(app.successHandler, app.errorHandler,{“senderID”:”**********”,”ecb”:”onNotificationGCM”});

    I installed again on my device and there was no error anymore from try/catch.
    But a new error came out from function’s errorHandler:function(error):
    It says:

    “Class not found”

    I cannot find out what’s wrong. I haven’t changed anything to your code except the Sender_id!

    Can you help?

    P.S. The only thing I did is that I renamed the file cordova2.3.0.js to phonegap.js.

  10. Kostas David says:

    Have you deleted my post? The sample app doesnt work on android device when compiled by phonegap build, the error ‘class not found’ occurs.

    Can you suggest a solution instead of deleting my posts?

  11. Kostas David says:

    I am sorry
    Due to pending moderation setting i thought you have deleted my post. I am really sorry
    Can you please give me a solution to the above problem i face of not being able to run successfully your sample on android?

  12. Kostas David says:

    Update:
    It seems that the javascript code cannot get executed if the app is not running. The only solution, that also suggested and worked on the mentioned forum, is to to create a java plugin to raise a notification on the statusbar, instead of trying to reach your project’s javascript code. This can be done only with Phonegap Desktop, not PhoneGap Build, of course. It’s a pity, because we had great expectations from the PushPlugin.

    • Nathan says:

      I had the same problems with the plugin that you did. The first problem with “class not found” is solved by changing the plugin name in config.xml. The sample project referenced above lists it as but according to PhoneGap build docs it should be . I assume you already figured that out and got it to work.

      Also, I had the same problem where if the app is not in the foreground on Android, no notification is shown in the notification bar (iOS does not have this problem). However, the latest build (Feb 5th, 2013?) of the plugin has this feature added. I downloaded the plugin and got it to work by manually building the android source. Hopefully this will be integrated into PhoneGap build soon!

      • John Cardozo says:

        What is the correct name of the plugin in “config.xml”?
        I guess you wrote it in your post but for some reason it’s not visible.

        • Hi John, I believe it should still be PushPlugin. I see some refer to GenericPush, but PushPlugin is what worked for me last I worked with it. Let me know if you have issues with that. Thanks! Holly

          • John Cardozo says:

            Hi Holly, thanks for the quick help.
            I changed the plugin name in config.xml to GenericPush and it worked. What do you suggest?
            Thanks a lot…

          • Ok, thanks, I guess they have updated that name in PhoneGap Build since the original version I wrote about. I know there’s been a few fixes etc, so that must have been part of other changes. As long as GenericPush worked, then that should be the one to use :) Thanks for the feedback! Holly

          • John Cardozo says:

            Thanks for your help.
            I still can’t make it work. The “class not found” error was fixed but the function onNotificationGCM is not fired. It doesn’t raise any error or exception. It just doesn’t execute… any ideas?
            Thanks again
            :D

  13. Kostas David says:

    The forum is:
    http://permalink.gmane.org/gmane.comp.handhelds.phonegap/39027

    And you should start with Arjan de Vries | 18 Oct 2012 17:06 answer.

  14. iCode says:

    Much thanks to the team !!
    Awesome

  15. Casey Wise says:

    Does it matter which Cordova version we’re using? I’m using 2.2, is that ok?

  16. Please note there have been some additions to the PushPlugin android-specific code to support status bar notifications. More details can be found at https://github.com/phonegap-build/PushPlugin.

    Also, I fixed a couple of minor issues in the index.js file for the sample so you should not be receiving the successHandler errors anymore (latest can be found at https://github.com/hollyschinsky/PhoneGapBuildPushProject2).

    Thanks!
    Holly

  17. Hi all, the new android code for the PushPlugin now supports showing status bar notifications when the app is running in the background or closed. The support was also added to PhoneGap Build and should work there too. Please post if you have any trouble, but find all the latest here: https://github.com/phonegap-build/PushPlugin

    I’ll be covering this in a webinar this Friday Feb 22nd at 1pm via TechLive as well if you would like to join. Details can be found here: http://techlive.adobe.com/ai1ec_event/getting-started-with-android-push-notifications-and-phonegap/?instance_id=714

    Cheers!
    Holly

  18. Bart van Hommel says:

    Hi all, first of all GREAT work!
    I have a few questions about the plugin:
    1) When tapping a statusbarnotification, and the app opens why doesn’t it remove the notification from the statusbar?
    2) When the app was exited (not via the home button), tapping the notification will not start the app..Kostas David gave some info on this, but I didn’t manage to implement it all together.

    • Hi Bart! There’s a new change now to the plugin that will remove the notification upon opening from the status bar. You can grab the latest changes in the plugin here: https://github.com/phonegap-build/PushPlugin. We were aware of #2 and looking to see if we can address it. Stay tuned for any more updates and thanks for your feedback!! Holly

      • Bart van Hommel says:

        Hi Holly!
        The update works great!
        I will also keep trying to fix the other bug, when I have something I will notify you.

      • Nathan says:

        Unfortunately there are even more problems than that. It also doesn’t get the new message text if the app is paused.

        1. Open app then press home button to put app in background.

        2. Send notification. New text correctly appears in notification bar.

        3. Tap notification bar. Now the notification disappears and app opens, but the text (e.payload.message) is from a previous notification.

        I’m using the demo project that comes with the notification plugin.

        Where should we report bugs like this? In the official github repo?

        I believe pushwoosh solved the background notification problem with a separate android “service” that listens for the notifications then starts the main activity if it isn’t already running.

        • Hi Nathan, I’ll test out your scenario to make sure I see the same results and contact the internal folks to make them aware and see where to best file bugs for it. Thanks! Holly

          • Paul Ronan says:

            Hey Holly,

            Any updates on this bug? I’m having the same problem.

          • Hi guys, Paul are you having the same problem where a previous message is shown as what Nathan was having, or which problem are you experiencing? I passed this feedback to the internal engineer and he was getting the new message each time, not the previous. What mechanism are you guys using for sending notifications? He’s still looking into it and I will try it myself as well. Also, please feel free to file something about any issues here: http://community.phonegap.com/nitobi/

            Thanks!!
            Holly

          • Also, I was assuming this was happening on android? Just let me know… Thanks!

          • Paul Ronan says:

            Hey Holly, thanks for the reply.

            And, yes, I’m having the same problem as Nathan with a slight twist…

            to his point 3. Tap notification bar. Now the notification disappears and app opens, but the text (e.payload.message) is from a previous notification.

            - The first time a message is delivered in the background it’s fine.

            - anything after that, the FIRST background message sent shows up, not the previous one.

            again, only in the background.

            - as Nathan pointed out, the text correctly appears in the notification bar

            If I leave the app in the foreground everything works fine. And I’m on an Android 4.04 Atrix 2.

          • Paul Ronan says:

            did you want me to file a bug on http://community.phonegap.com/nitobi/

          • Sure, that would be great, thanks for the info as well! I’ve passed it along internally again ~ thanks! Holly

          • Hi guys, a fix was made for this and you can get the latest version of the plugin here https://github.com/phonegap-build/PushPlugin. Please let me know if this works for you! Thanks! Holly

      • Rajat says:

        Hi Holly,
        Firstly THANKS to the Phonegap Build team for incorporating the push notifications, its working seamlessly for us!
        Are you planning to address the above #2 issue(tapping the notification does not start the app) in the coming update.
        Thanks!!

  19. Juan Aguiar says:

    Hello Holly,

    First of all let me start off by congratulating you on your great work. Keep it up!

    My question is the following… If I already have a Phonegap build app on both the Google and Apple markets and I want to add push notifications to them. Will I have to create a new one due to the signing keys and certificates I already created for them or can I update the existing app with the new certificates for push notifications without affecting my existing app?

    • Thanks Juan :)

      You can update the existing app, but you will have to download new certificates with push notifications enabled on iOS and re-submit to the app store… You’ll have to update the code handling for both too anyway, so you will end up having to re-submit to both stores in the end.

      I have two video webinars I presented with the process of enabling the push notifications for both platforms in the archives on Adobe TechLive in case that helps at all – you can find them here: http://techlive.adobe.com/archives/

      Hope that helps!
      Holly

  20. Hi,

    I´m experiencing a weird behavior in a test ios app, after the receivedEvent is fired none of the callbacks are executed(tokenHandler, errorHandler). I’m using Phonegap Build to construct the application. Do you have any idea what could be the cause?

    Thank you very much for your time.

  21. Peter says:

    Hi, Holly
    Is it possible to create Local notifications with this plugin? Or do you planing to add support them in next plugin releases.
    Thanks in advance.

  22. Jerome says:

    Hey
    I am getting the “class not found error” when running the sample project after building on phonegap build.
    Nathan mentioned changing the plugin name in config.xml but didn’t mention to which value, and I can’t figure it out. The value I have is “PushPlugin” e.g.

    Thanks
    Jerome

  23. Sabin says:

    I am building mobile apps using Phonegap Build and I am trying to implement this into my app.
    I did a test on iOS and the push notifications are not getting to my device.
    Where can I get a real example to test it out? Thank you!

  24. Steven says:

    Great writeup. I was searching around for just this info for an app I have been playing with and this was perfect! Thanks again!

  25. Eduardo says:

    Hi Holly Schinsky, i have two problems with start using Pushwoosh + Phonegap on IOs… my cordova version is 2.4 and when i start my application i recive this:

    “Your provisioning profile does not have APS entry. Please make your profile push compatible.”

    i followed phonegap and pushwoosh tutorial, create the key and certificated but i cant solve this.

    [“failed to register “, {“error”:”Error Domain=NSCoacoaErrorDomainCode=3000\” don`t have true auth code of “aps-environment” search in your app. UserInfo=”xxxxxx”…”

  26. Thomas says:

    Is it necessary to use only production provisioning profile to receive notifications? I am unable to receive notification when I use the dev profile.

    • Hi Thomas, no, you shouldn’t need to use the production profile, dev’t should work fine… Are there any errors showing? Thanks! Holly

      • Thomas says:

        Thanks Holly it worked when I used the Prod profile, my dev certificate had some issues. The other thing is, I noticed that the badge clears when you launch the app. Is there a way to prevent that?

  27. Chula says:

    It works great!!! Thanks for all you afford!

    But I still have one issue…If the App had not been executed yet (even not in background), clicking the Notification Bar could start the App, but…how can I get the Notification Message the user clicked?

  28. Hi all, quick update – the fix for the issue where tapping the notification while the application is in an exited state on Android (versus just running in the background) should be deployed to PhoneGap Build next week sometime… I will post a comment again when it’s definitely there. Thanks! Holly

  29. Thomas says:

    Could we use this plugin for setting up Local notifications?

  30. John Cardozo says:

    Hi,
    I’m trying to get it work but when I try to execute:

    pushNotification.register(this.successHandler, this.errorHandler,{“senderID”:”XXXXXXXXXXX”,”ecb”:”onNotificationGCM”});
    nothing happens, so I checked the log and this is what it happens:
    V/GCMRegistrar(16398): Registering app co.edu.usbbog.triqui of senders XXXXXXXXXXX
    E/REGISTER(16398): /data/data/co.edu.usbbog.triqui/files/cached_payload: open failed: ENOENT (No such file or directory)

    Any ideas about this error?
    Thanks a lot for your help…

  31. Colin Bau says:

    Hi Holly ~
    I am a newer in GenericPush
    If I ask a stupid question, please forgive me
    I run your example code
    change my own senderID => “senderID”:”XXXYYYZZZ”
    Then I run your example on my phone
    And the following message appears

    ====
    Cordova PushNotification Plugin Demo
    deviceready event received
    registering android
    success:OK
    EVENT -> RECEIVED:registered
    REGISTERED ->
    REGID:APA91bEwi5d4C5gy7UzKzb886VCPV522mhfMoc4Q_B8OKmTnmt4TYs9JPMiQsyCAW2zzXWSsN-REGID:APA91bEwi5d4C5gy7UzKzb886VCPV522mhfMoc4Q_B8OKmTnmt4TYs9JPMiQsyCAW2zzXWSsN-FI1agygXrWRqaSB5bcmAyClC1iawzOBQifkTrid4zSvmSX9fXzTHFPA3rs-FI1agygXrWRqaSB5bcmAyClC1iawzOBQifkTrid4zSvmSX9fXzTHFPA3rs-f0GmKe2RDfwjmZEYml0L_5IOwCwfg
    ====

    I that regarded as setting success??
    Because in the status bar of my phone does not appear Anything
    What is my next step is to??
    I have the following information: API Key, Sender ID, My website Domain…any else??

  32. I just complete the programming and it works the same. Quite impressive. :)

  33. raul says:

    Hi,
    I am a beginner and apologies if I am missing something obvious.Here is what I am doing.
    I am using sample code from below location
    https://github.com/phonegap-build/PushPlugin/tree/master/Example/www

    Only thing I am changing is senderid and making .apk through phonegap.

    However I see below error. Device is not doing registration.

    Cordova PushNotification Plugin Demo
    deviceready event received
    registering android
    error:Class not found

    I also tried using below sample code which david has pointed in his comments and did the changes mentioned i.e. changing cordova to phonegap, sender id and genericpush/phonegap( i tried both format)

    https://github.com/hollyschinsky/PhoneGapBuildPushProject2/tree/master/www

    however in above case phonegap build is not even letting me compile,throwing me either saying
    phonegap plugin not supported or genericpush plugin not supported ..

    Thanks in advance.

    Raul

  34. Lior says:

    Hi,
    The PushPlugin works great but there is only one problem on Android (I already saw its mentioned here but didn’t see any fix) – When the app is not running, clicking on the push notification doesn’t execute/brings the app to foreground. Is there any fix for this?

    Thanks! :)

    • Colin Bau says:

      I have the same problem with Lior,But my solution is as Tentative follows

      When you’ve never execute your APP,the situation just like Lior
      but if you have execute your APP before,Even after you shut down your application

      this time,clicking on the push notification message,it will execute/brings the app to foreground

      so strange~any idea?

  35. Colin Bau says:

    many people have this issue too
    https://github.com/phonegap-build/PushPlugin/issues/35
    but it still have no answer

  36. Amit says:

    Hi,

    Thanks Holly, it works great!

    I have a question regarding the plugin, why do we need to register the app each time it is loaded (pushNotification.register(..))? IMHO after a successful registration we could just save the key and reuse it over and over again.
    The strange thing is that if I try to work my way and NOT call pushNotification.register(..) when the app is loaded then the PushPlugin.java is not initialized correctly and the push notification process would be broken.

    Any idea about this?
    Thanks in advance,
    Amit

  37. Roger Large says:

    I have tired your example with Phonegap Build and i’m having issues. The callback for regid does not return a error or success it just fails. Any ideas…. I’ve installed in locally for android no problem but was hoping to use build for ios. Maybe its build or hydration…

    Thanks, Roger

    P.S. It would be cool if you made a (Phonegap-Build-FacebookConnect-PushPlugin-GAPlugin-Angularjs) Project Example…lol (now i’m just being greedy, lol)

  38. Johan says:

    I Have a problem with Cordova/Phonetgap Device API on Android, the objetc device isn’t found. I make callback to device.model or any fecture of device and return:

    ReferenceError: Can’t find variable: device at file:///android_asset/www/index.html:16

    I’m following this steps: http://cordova.apache.org/docs/en/3.3.0/cordova_device_device.md.html#Device firts create the cordova android project and later I Install plugin device through: “cordova plugin add org.apache.cordova.device”

    You know why this happens? How I can to solve this problem? helpme please :D

  39. Jeff says:

    Hello,

    I tried a lot of stuff but I’m still stuck on the same issue.
    When I run the app through Cordova CLI in emulator, SuccessHandler is called and display the success message but OnNotificationGCM is never fired. So I cannot register the device.

    Can you please gimme some help, at least how to debug and see what happend when .register is used.

    Thanks

  40. JeFF says:

    Thanks for the answer; logcat tells
    V/GCMRegistrar( 1017): Registering app ***MYAPP of senders ***MYID
    W/PluginManager( 1017): THREAD WARNING: exec() call to PushPlugin.register blocked the main thread for 162ms. Plugin should use CordovaInterface.getThreadPool().
    W/ActivityManager( 388): Unable to start service Intent { act=com.google.android.c2dm.intent.REGISTER pkg=com.google.android.gsf (has extras) } U=0: not found

    • Jeff, did you add the Intents to your AndroidManifest.xml file as outlined in the PushPlugin manual installation notes here – https://github.com/phonegap-build/PushPlugin ? Specifically step 3 where it outlines the addition of the <action android:name=”com.google.android.c2dm.intent.RECEIVE”> and <action android:name=”com.google.android.c2dm.intent.REGISTRATION”> section? The $PACKAGE_NAME needs to be replaced with your package name too. See the example AndroidManifest.xml file for more details.

      Otherwise, also double check that your project_id on GCM matches the one you’re sending in on the registration request?

      Thanks,
      Holly

  41. Jo says:

    I was following your projects and blog, however when I am trying to do the iOS notification, I can only get the notification when the app is inactive (not in foreground), how do I have an alert when the app is running in the foreground? Please help. Thank you.

Leave a Reply