QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads Push Notification in Intel XDK using Push Plugin

Push Notification in Intel XDK using Push Plugin

push-notificaton

This post is a part 26 of Intel XDK Complete Tutorial post series.

In this tutorial I will show how to integrate push notification in a Cordova Hybrid apps. Intel XDK legacy apps use pushMobi webservice to integrate push notifications but in cordova hydrid apps you have to use third party plugins.

Include Push Plugin

In this tutorial we will use third party Push Plugin to integrate push notification in Intel XDK cordova hydrid APP.

Screen Shot 2015-01-03 at 8.05.31 pm

iOS Prerequisite

There are two things you need to setup push plugin in iOS app

  1. App ID configured for Push Notifications on Apple Developer Portal
  2. Generate .pem file for sending push messages from your server to apple servers

Android Prerequisite

For android you need to create a Google Developers Console project and retrieve project ID and API key

Understanding Push Notification Mechanism

Push Notification is useful when app is in background or lock state and you want to notify user about something important. You need to send the messages from your server to mobile vendor server’s and they will deliver the message to the respective phones.

When app is in background a tile is usually displayed when a new notification is received. When user clicks on the tile the app is switched to foreground state and a callback is fired by passing the message as parameter.

If app is in foreground then just a callback is fired when a new notification is received.

Registering User

Some apps require user to login to use it. For example: Gmail, Facebook etc apps require you to create or login to account. Some apps like Flappy bird, blog etc doesn’t require user to login.

Apps that require login actually sends different push notifications to different users. But the apps that don’t require login send same push notifications to all users.

If your app falls into login required category than When a user installs your app, your app needs to register the user to identify it uniquely. This will allow you to send notifications to specific users identified uniquely. Your app will get a unique token to identify the device in which app is installed. You need to send the token along with user credentials to your server so that you know to which device you need to send notification to for a particular user.

If your app falls into non-login category than also you need to register the user but in this case you can just send the unique token to your server. And then send push notification to all tokens.

Here is the code on how to register and retrieve the unique token for Android and iOS

        var tokenID = "";

        document.addEventListener("deviceready", function(){
            //Unregister the previous token because it might have become invalid. Unregister everytime app is started.
            window.plugins.pushNotification.unregister(successHandler, errorHandler);
           
            if(intel.xdk.device.platform == "Android")
            {
                //register the user and get token
                window.plugins.pushNotification.register(
                successHandler,
                errorHandler,
                {
                    //senderID is the project ID
                    "senderID":"",
                    //callback function that is executed when phone recieves a notification for this app
                    "ecb":"onNotification"
                });
            }
            else if(intel.xdk.device.platform == "iOS")
            {
                //register the user and get token
                window.plugins.pushNotification.register(
                tokenHandler,
                errorHandler,
                {
                    //allow application to change badge number
                    "badge":"true",
                    //allow application to play notification sound
                    "sound":"true",
                    //register callback
                    "alert":"true",
                    //callback function name
                    "ecb":"onNotificationAPN"
                });
            }
        }, false);
 
        //app given permission to receive and display push messages in Android.
        function successHandler (result) {
            alert('result = ' + result);
        }
       
        //app denied permission to receive and display push messages in Android.
        function errorHandler (error) {
            alert('error = ' + error);
        }
       
        //App given permission to receive and display push messages in iOS
        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 the token to your server along with user credentials.
            alert('device token = ' + result);
            tokenID = result;
        }
       
        //fired when token is generated, message is received or an error occured.
        function onNotification(e)
        {
            switch( e.event )
            {
                //app is registered to receive notification
                case 'registered':
                    if(e.regid.length > 0)
                    {
                        // Your Android push server needs to know the token before it can push to this device
            // here is where you might want to send the token to your server along with user credentials.
                        alert('registration id = '+e.regid);
                        tokenID = e.regid;
                    }
                    break;

                case 'message':
                  //Do something with the push message. This function is fired when push message is received or if user clicks on the tile.
                  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;
            }
        }
       
        //callback fired when notification received in iOS
        function onNotificationAPN (event)
        {
            if ( event.alert )
            {
                //do something with the push message. This function is fired when push message is received or if user clicks on the tile.
                alert(event.alert);
            }

            if ( event.sound )
            {
                //play notification sound. Ignore when app is in foreground.
                var snd = new Media(event.sound);
                snd.play();
            }

            if ( event.badge )
            {
                //change app icon badge number. If app is in foreground ignore it.
                window.plugins.pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
            }
        }

This is how it looks on iOS

IMG_0587

IMG_0589

IMG_0588

Sending Push Notification from PHP Server to Apple Push Servers

Here is the PHP code snippet to send push notification from your own server to apple servers so that apple can deliver it to the app.

<?php

    $passphrase = ""; //enter passphrase that you created while generating .pem file
    $message = "Sample Notification"; //notification message
    $token = ""; //enter the token received by the app to uniquely identify device on which app is installed.

    $payload = '{"aps":{"alert":"' . $message . '","sound":"default","badge":"1"}}';//set message, sound and badge number for the app callback to receive
    $result = 'Start' . '<br />';
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); //last parameter is the name of the .pem file.
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
    $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
    if (!$fp) {
        exit("Failed to connect: $err $errstr" . '<br />');
    } else {
        echo 'Apple service is online. ' . '<br />';
    }
     
    $msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
    $result = fwrite($fp, $msg, strlen($msg));
    if (!$result) {
        echo 'Undelivered message count: ' . $token . '<br />';
    } else {
        echo 'Delivered message count: ' . $token . '<br />';
    }
 
    if ($fp) {
        fclose($fp);
        echo 'The connection has been closed by the client' . '<br />';
    }

This is how it looks on iOS when notification is received

IMG_0590

IMG_0591

Sending Push Notification from PHP Server to Google Cloud Messaging Android Servers

Here is the PHP code snippet to send push notification from your own server to android servers so that Google can deliver it to the app.

<?php

class GCMPushMessage {
    var $url = 'https://android.googleapis.com/gcm/send';
    var $serverApiKey = "";
    var $devices = array();
   
    function GCMPushMessage($apiKeyIn){
        $this->serverApiKey = $apiKeyIn;
    }
    function setDevices($deviceIds){
   
        if(is_array($deviceIds)){
            $this->devices = $deviceIds;
        } else {
            $this->devices = array($deviceIds);
        }
   
    }
    function send($message, $data = false){
       
        if(!is_array($this->devices) || count($this->devices) == 0){
            $this->error("No devices set");
        }
       
        if(strlen($this->serverApiKey) < 8){
            $this->error("Server API Key not set");
        }
       
        $fields = array(
            'registration_ids'  => $this->devices,
            'data'              => array( "message" => $message ),
        );
       
        if(is_array($data)){
            foreach ($data as $key => $value) {
                $fields['data'][$key] = $value;
            }
        }
        $headers = array(
            'Authorization: key=' . $this->serverApiKey,
            'Content-Type: application/json'
        );
        $ch = curl_init();
       
        curl_setopt( $ch, CURLOPT_URL, $this->url );
       
        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
       
        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
       
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
       
        $result = curl_exec($ch);
       
        curl_close($ch);
       
        return $result;
    }
   
    function error($msg){
        echo "Android send notification failed with error:";
        echo "\t" . $msg;
        exit(1);
    }
}


$apiKey = ""; //api key
$devices = array(); //array of tokens
$message = "The message to send"; //message o send

$gcpm = new GCMPushMessage($apiKey);
$gcpm->setDevices($devices);
$response = $gcpm->send($message, array('title' => 'Test title')); //title of the message
Jan 4, 2015Narayan Prusty
Share Button for Intel XDK APPGet Excerpt in WordPress
Comments: 108
  1. vimal
    6 years ago

    Can you please give me latest Push Plugin Github link? When I use plugin : https://github.com/phonegap/phonegap-plugin-push . It gives me Gradle Script error. Please help.

    Also,i don’t get anything when I do this : alert(intel.xdk.device.model); Do I need to install any plugin?

    ReplyCancel
    • Flavio Ceratti
      6 years ago

      did you tried to use One Signal?,

      ReplyCancel
  2. Mak
    6 years ago

    Wouldn’t it have been better if you just zipped up a full sample code instead of telling of people finding out that things have either changes in version or nothing hangs together and works.

    A complete sample – includes the pushnotification.js – would be really appreciated not just code snippets.

    Thanks

    ReplyCancel
  3. Luis
    6 years ago

    What’s with Firebase Cloud Mess. Thank’s

    ReplyCancel
  4. Gugum
    6 years ago

    thanks for the tutorial . I ‘ve tried and succeeded , I have a question if there is more than one user . whether notifications are sent in the token or terikirim notification to all users . thank you

    ReplyCancel
  5. redha
    6 years ago

    Hi Narayan Prusty,
    thank you for this tutorial is useful i run it successfully but i have one tiny problem when my phone receive first notification is OK but if there is another notification comes, it replaces the previous one.

    ReplyCancel
  6. anthonydecastro
    6 years ago

    Hi
    Code is not working for me showing the error “Warning: the Cordova CLI 3.3 and 3.5 build options have been deprecated and will be removed before the end of 2015 (or sooner). Applications built with these versions of the Cordova CLI are no longer or will soon be no longer accepted by either the Google Play or the Apple Store.”

    ReplyCancel
  7. Raj
    7 years ago

    i did everything.. i got the device id too..and i sent it to the .php file.. but the token in php is not getting populated..

    ReplyCancel
  8. kurus
    7 years ago

    Hello all, here every one is sharing these kinds of know-how, so it’s good to
    read this webpage, and I used to go to see this webpage every day.

    ReplyCancel
  9. hariyanto
    7 years ago

    Thanks a good tutorial, I want to ask how to receive two or more notifications without removing the notification that has not been opened before ?

    ReplyCancel
    • Raj
      7 years ago

      can u help me in this local notifications .. im not able to get it

      ReplyCancel
  10. Paolo
    7 years ago

    Ok… I have the Android app working nicely. I cannot seem to get a token for the iOS app.

    I have created the .pem file and have it hosted on my server. If I open the apple php file which is hosted in the same folder as my .pem file I get the info below:

    Apple service is online.
    Delivered message count:
    The connection has been closed by the client

    I assume this means everything is set up correctly.

    Does anyone know what point which I am missing, and why my app is not receiving a iOS token?

    Thanks in advance for any help.

    ReplyCancel
  11. Paolo
    7 years ago

    Great tutorial, thank you.

    One thing I’m struggling to understand. At the moment there’s a button to press to receive a message. from the server. Obviously we want this to happen automatically. Should we create a function which checks every hour?? Am I missing the point??

    ReplyCancel
  12. Jonathan
    7 years ago

    i’m getting this error when i’m trying to build my app Error: Plugin PushPlugin failed to install.
    What can i do ?
    I tried to build your app as well still same pool. help please.

    ReplyCancel
    • Baljinder Singh
      7 years ago

      I am also getting same error & not able to build an app on both IOS & Android. I have not changed anything in my app since one month but now it suddenly giving this error.

      ReplyCancel
      • Narayan Prusty
        7 years ago

        I would recommend you guys to try adding the plugin locally.

        ReplyCancel
        • Baljinder Singh
          7 years ago

          Have tried it to add locally as well but could not yield results. Can you please let us know why this is happening ?

          ReplyCancel
          • jonathan
            7 years ago

            @Narayan Prusty can you look into the problem please, thank you.

            ReplyCancel
          • Webcraft
            7 years ago

            Whats version of the cordova Cli are you building with, i use 4.1.2 for my apps and the plugins works well

            ReplyCancel
            • Baljinder Singh
              7 years ago

              Hello Dear

              Yes it started working now with 4.1.2. But earlier it was not working with even 4.1.2. I think there was some problem with the Intel XDK external plugins.

              Thanks for the help.

              ReplyCancel
        • Gumilar
          5 years ago

          I have a problem in the notifications that always stray to the phone that is not the intended token

          ReplyCancel
      • Roman.B
        7 years ago

        There was recent update for intel xdk (2496 )that have issue with 3rd party plugins. Until they solve it. I’m afraid it wont work. Also plugin is deprecated now so you may move on to new version that support CLi 5.x+

        ReplyCancel
    • Roman.B
      7 years ago

      There was recent update for intel xdk that have issue with 3rd party plugins. Until they solve it. I’m afraid it wont work.

      ReplyCancel
  13. Flavio
    7 years ago

    Is it possible to do it using only a windows pc?, i didn’t see the p12 file when i tried.
    thanks

    ReplyCancel
  14. EZ
    7 years ago

    Don’t worry – I’m not gonna ask about the inability to get a token…lol

    I’ve got that part worked out- and I’ve got the token just fine. :)

    Just a quick question on the PHP part – where you send the message to Google and it relays it back to the phone…

    setDevices($devices);
    $response = $gcpm->send($message, array(‘title’ => ‘Test title’)); //title of the message
    ?>

    Nothing happens in the app when I pass those values. I assume it’s supposed to send “Test Title”, “The Message To Send” as a push notification…but nothing is received.

    Is there something I’m missing? Is there an additional plugin (like events/notifications) that I need to enable? Should I go to Google and see if there’s a different PHP script to try? :)

    Thanks for the tutorial – it’s been invaluable up to this point!

    ReplyCancel
    • Paolo
      7 years ago

      Hi Ez,

      Did you figure out your issue? I too have everything working correctly but the app is not receiving a push message.

      Paolo

      ReplyCancel
  15. nitrous
    7 years ago

    when i m trying to rebuild my mobile app on android using Intel XDK, it gave me build failed.
    because there are a problem in the push plugin since week ago. anyone can help?

    ReplyCancel
    • nitrous
      7 years ago

      This problem is on push plugin version 2.5.0

      ReplyCancel
    • Flavio
      7 years ago

      Hi, you have to put this id “com.clone.phonegap.plugins.pushplugin” , a check the checkbox ‘Plugin is located in the Apache Cordova Plugins Registry’

      ReplyCancel
  16. Jeferson
    7 years ago

    Hi, I’ve tried to follow your tutorial in my XDK app and also tried to run your XDK from the imported project, but I always get the error “cannot read property ‘push notification’ of undefined”, as the plugin was not loaded. Any advice?
    Thanks and regards.

    ReplyCancel
    • Jeferson
      7 years ago

      This seems to be related to current version 2.5.0 (https://github.com/phonegap-build/PushPlugin/issues/611). Using version 2.4.0 fixed it.

      ReplyCancel
  17. EROS
    7 years ago

    HI HO tried PROJECT BUT I CAN NOT GET ME THE SECOND PUSCH COIN ID
    DOES NOT WARRANT from the app TRACKS PHP THEN THE MESSAGE IS NOT SENT EC SOMEONE WHO CAN post A SOURCE THAT THIS IS NOT THAT I MAKE SURE IT WORKS THANKS

    ReplyCancel
    • EROS
      7 years ago

      integrating code in index.html
      exsample code
      http://qnimate.com/push-notification-in-intel-xdk-using-push-plugin/

      and using plugin Cordova
      https://github.com/phonegap-build/PushPlugin

      index.html:

      @-ms-viewport { width: 100vw ; zoom: 100% ; }
      @viewport { width: 100vw ; zoom: 100% ; }
      @-ms-viewport { user-zoom: fixed ; }
      @viewport { user-zoom: fixed ; }

      <button onclick="send_notification();">Test Push Notification</button>

      <script src="intelxdk.js"></script>
      <script src="cordova.js"></script>
      <script src="xhr.js"></script>
      <script src="js/app.js"></script>
      <script src="js/init-app.js"></script>
      <script src="js/init-dev.js"></script>

      <script>
      var tokenID = "";
      function send_notification()
      {
      var xhr = new XMLHttpRequest(); "page php"
      xhr.open("GET", "http://labs.qnimate.com/ios-push/android.php?token=" + encodeURIComponent(tokenID), false);
      xhr.send();
      }

      document.addEventListener("deviceready", function(){
      //Unregister the previous token because it might have become invalid. Unregister everytime app is started.
      window.plugins.pushNotification.unregister(successHandler, errorHandler);

      if(intel.xdk.device.platform == "Android")
      {
      //register the user and get token
      window.plugins.pushNotification.register(
      successHandler,
      errorHandler,
      {
      //senderID is the project ID
      "senderID":"my id project",
      //callback function that is executed when phone recieves a notification for this app
      "ecb":"onNotification"
      });
      }
      }, false);

      //app given permission to receive and display push messages in Android.
      function successHandler (result) {
      alert('result = ' + result);
      }

      //app denied permission to receive and display push messages in Android.
      function errorHandler (error) {
      alert('error = ' + error);
      }

      //fired when token is generated, message is received or an error occured.
      function onNotification(e)
      {
      switch( e.event )
      {
      //app is registered to receive notification
      case 'registered':
      if(e.regid.length > 0)
      {
      // Your Android push server needs to know the token before it can push to this device
      // here is where you might want to send the token to your server along with user credentials.
      alert('registration id = '+e.regid);
      tokenID = e.regid;

      }
      break;
      case 'message':
      //Do something with the push message. This function is fired when push message is received or if user clicks on the tile.
      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;
      }
      }
      </script>

      pagina php:
      <?php
      class GCMPushMessage {
      var $url = ‘https://android.googleapis.com/gcm/send';
      var $serverApiKey = “”;
      var $devices = array();

      function GCMPushMessage($apiKeyIn){
      $this->serverApiKey = $apiKeyIn;
      }
      function setDevices($deviceIds){

      if(is_array($deviceIds)){
      $this->devices = $deviceIds;
      } else {
      $this->devices = array($deviceIds);
      }

      }
      function send($message, $data = false){

      if(!is_array($this->devices) || count($this->devices) == 0){
      $this->error("No devices set");
      }

      if(strlen($this->serverApiKey) < 8){
      $this->error("Server API Key not set");
      }

      $fields = array(
      'registration_ids' => $this->devices,
      'data' => array( "message" => $message ),
      );

      if(is_array($data)){
      foreach ($data as $key => $value) {
      $fields['data'][$key] = $value;
      }
      }
      $headers = array(
      'Authorization: key=' . $this->serverApiKey,
      'Content-Type: application/json'
      );
      $ch = curl_init();

      curl_setopt( $ch, CURLOPT_URL, $this->url );

      curl_setopt( $ch, CURLOPT_POST, true );
      curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

      curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

      curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
      curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);

      $result = curl_exec($ch);

      curl_close($ch);

      return $result;
      }

      function error($msg){
      echo "Android send notification failed with error:";
      echo "\t" . $msg;
      exit(1);
      }

      }
      sleep(5);
      $apiKey = i put here my server key api”; //api key
      $devices = array($_GET[“token”]); //array of tokens
      $message = “ciao”; //message to send
      $gcpm = new GCMPushMessage($apiKey);
      $gcpm->setDevices($devices);
      $response = $gcpm->send($message, array(‘title’ => ‘Test title’)); //title of the message
      This code allows you to send Pusch even if the app is in the background????
      source code project: https://github.com/qnimate/intel-xdk-android-push
      I hope you can help me greetings giuseppe

      ReplyCancel
  18. Jonas
    7 years ago

    successHandler alert ‘ok’ but tokenid is always empty

    ReplyCancel
    • Jonas
      7 years ago

      aparently onNotification(e) is not being executed, or none of the events match. any alert is show.

      ReplyCancel
      • Roman.B
        7 years ago

        take your code outside function register_event_handlers(). put it all on boottom of file.

        ReplyCancel
        • Jonas
          7 years ago

          I think that my problem was the problem of many. Beware the other plugins that must have active. i’ve put on as in qnimate example and everthing work well in my app

          ReplyCancel
  19. Jonas
    7 years ago

    Man…
    This is your code:
    “var tokenID = “”;
    function send_notification()
    {
    var xhr = new XMLHttpRequest();
    xhr.open(“GET”, “http://labs.qnimate.com/ios-push/android.php?token=” + encodeURIComponent(tokenID), false);
    xhr.send();
    }”

    Are you sending an empty var? Where the hell is the tokenID ?

    ReplyCancel
  20. Rajeev
    7 years ago

    Hi, Thanks for the tutorial. I did the same as you said. BUt where do I include the pem file or have a separate push certificate in the cordova build? There are only two options one to upload a provisioning profile in the projects section and 1 certificate section in the build tab

    ReplyCancel
    • Roman.B
      7 years ago

      PEM file should be on your server, the server that contact apple server when sending push message. The other certificate you are including in build section of XDK. It wont let you build without it. Of course you also need Apple Developer Certificate that cost you $100 per year and your personal developer account on apple servers where you create all needed certificates.

      ReplyCancel
  21. Curvello
    7 years ago

    Is possible customize the sound of push notification? How?

    ReplyCancel
  22. Roman.B
    7 years ago

    All done and tested on Android.

    To everyone who doesnt seem to make this work. I download code uploaded by this tutorial author and make some changes. First, do everything what he say on the beginnig of this course with registering with Google Cloud. Then you need to update code with your own ProjectID. Next, make sure you have running own server. I used XAMPP on Windows and run android.php from author’s git repository. Changes API key to my from Google Cloud and in app change AJAX request to IP of my local machine. And one more thing. In app I had to change line

    intel.xdk.device.platform

    to

    device.platform

    Please stop sending rude, racial abusive messages to this guy. He knows what he is doing , just maybe isnt great with describing all details required.
    Its also worth to read PushPlugin documentation. It includes sample code to make all run with Intel XDK

    https://github.com/phonegap-build/PushPlugin

    ReplyCancel
    • keith
      7 years ago

      You are truly right.
      The issue that most guy experienced is changing
      from
      “intel.xdk.device.platform”
      to
      “device.platform”

      once I did this change, my app instantly works perfectly.

      ReplyCancel
      • Roman.B
        7 years ago

        To all who using XDK. Move to native cordova calls with ‘navigator’. Once I did that suddenly my device started to vibrate when I told it to, native popup messages worked and many many more.
        intel.xdk namespace works…. but only on emulators. On real device when you deploy app it just doesnt.

        ReplyCancel
        • Raj
          7 years ago

          roman… plss help me..
          how did u change ur ajax… i tried all d ways

          ReplyCancel
    • Raj
      7 years ago

      hey…
      pls give me a example how did u change the ajax request to ur ip address..
      plss help me..
      thank you in advance

      ReplyCancel
  23. Hubi
    7 years ago

    Program doesn’t work for me :/ I copied all files and have PushPlugin installed. When i turn the app on my device there is altert “result OK” but when i click in button “test push notification” nothing happens.

    ReplyCancel
    • Roman.B
      7 years ago

      The alert comes from code for unregistering the device. Google claims to not do that very often, only if you have to. And also change ‘intel.xdk.device.platform’ in your code to ‘device.platform’. Try again

      ReplyCancel
  24. Curvello
    7 years ago

    It is possible to provide the source code ready for download? Intel XDK project?
    Because I am trying to make it work days and I can not …

    ReplyCancel
    • Narayan Prusty
      7 years ago

      https://github.com/qnimate/intel-xdk-android-push

      ReplyCancel
      • Curvello
        7 years ago

        Thanks!!!!
        It is possible to make an administrative system where we register users and then I can send “Push Notification” individually?

        ReplyCancel
  25. Robson
    7 years ago

    How get TokenID???

    ReplyCancel
  26. Ivan
    7 years ago

    $serverApiKey and $apikey is the same (in android.php) ? $serverApiKey is GCM key and $apikey what is ?

    ReplyCancel
    • Ivan
      7 years ago

      I solved my trouble. Thanks for your post.

      ReplyCancel
  27. Siphiwe
    7 years ago

    Hi there Narayan,

    Thanks for a great article on this. I wonder if you can assist. I’m testing this on an android device and I get “error = Class not found” which comes from the errorHandler when trying to register the device. I’ve banged my head against the wall and am just not getting past this error. I suspect that the issue is that adding Push Plugin is not happening sucessfully. When I inspect the apk file, I don’t see any jar files. I tried adding it as suggested and by downloading the plugin and using the “Import local plugin” option on XDK. I’d appreciate your assistance.

    Thanks,

    Siphiwe

    ReplyCancel
  28. Raiden
    8 years ago

    Hi!

    Thanks for tutorial!

    The app doesn’t send notification when it isn’t running (in the background). Why is that?

    ReplyCancel
  29. Sajeesh
    8 years ago

    Hi,
    Do you know one issue ? the key generate by the phone is too long and it wont allow you to pass via GET or POST

    ReplyCancel
  30. Sajeesh
    8 years ago

    Hi,
    Thanks for your turotial, its working fine for me. But I have one question
    “change app icon badge number” can you explain to me how to do it ? Sorry I am new to the mobile app development

    ReplyCancel
  31. Alex Beltrán
    8 years ago

    For all people that doesn’t work the demo uploaded by Narayan, must verify if they have the requiered plugins selected at the ‘Cordova 3.X Hybrid Mobile App Settings in the Projects section’, must checked in included plugins ‘Device’ in Standard Cordova Plugins section and in the Featured & Custom Cordova Plugins section.

    This tutorial resulted very useful for me.

    ReplyCancel
    • Rajeev
      7 years ago

      Hi, I did the same. BUt where do I include the pem file or have a separate push certificate in the cordova build, like in the legacy build option?

      ReplyCancel
  32. reytabs
    8 years ago

    why i can’t receive push notification when my app is already running or opened. .how to solve this. .i’m using this plugin.

    ReplyCancel
  33. Siniorcola
    8 years ago

    Hi, awesome tut! , why do you unregister the previous token on every app start? that way it’s imposible to track users count

    ReplyCancel
  34. Andre
    8 years ago

    Nice tutorial, tks for your time! Well, I made my app work with your code and create an message sender in python on my server.

    ReplyCancel
    • Andre
      8 years ago

      I was passing an hash/dictionary as this data = {‘the_message': ‘You have x new friends’, ‘sender':’andre’}, so i have changed to data = {‘message': ‘You have x new friends’, ‘sender':’andre’} and the notification now apears on the notification tray.

      ReplyCancel
  35. Indodogs
    8 years ago

    fuck this shit… stupid author can’t even give full source code… fucking indiashit… ALLAHU AKBAR..

    ALOHA SNACKBAR!!!

    ReplyCancel
    • Anonymous
      6 years ago

      dont be a fucking racist.
      and dont be a stupid dependent asshole.
      try it out yourself. cant even ask for source code properly. it’s his right to whether share or not.

      ReplyCancel
  36. PUNX
    8 years ago

    how can I get this shit list of $device when I build the app it alerts only result = OK…

    ReplyCancel
    • Tabada
      8 years ago

      this tuts not so accurate… how to insert that arrays of devices when we dont know what to input there and didn;t even alert what device code…

      ReplyCancel
    • Hedi Herdiana
      8 years ago

      yes, the same as I get.

      ReplyCancel
      • Narayan Prusty
        8 years ago

        Even if I provide complete to you, you still needs to make changes on it to run. I cannot let you guys use my credentials and server for testing.

        All the code I provided above is tested. If something not works then debug it using JavaScript console.

        Check you build log to make sure plugin is installed properly.

        You need to write some ajax to send the tokenID to server which will be used for the $device variable.

        ReplyCancel
        • Hedi Herdiana
          8 years ago

          You can use my server. Please give me all scripts for I upload on my server and your project .XDK to I build and test it. If it works, I will willingly spread this tutorial. Thanks.

          ReplyCancel
          • Narayan Prusty
            8 years ago

            Its not possible to host the app on server for iOS because to test you have to make adhoc build and the device UUID’s are predefined while creating the app. So pem file and certificates are different for all devices.

            But for android its possible to upload to server. Give me couple of days I will upload it on my server for testing. Remember its only for android.

            device ID is stored in tokenID JavaScript variable.

            ReplyCancel
            • Hedi Herdiana
              8 years ago

              Well, I’ll wait. thanks.

              ReplyCancel
              • Narayan Prusty
                8 years ago

                Done https://github.com/qnimate/intel-xdk-android-push

                Download and try. I have tested it works fine. Let me know your result.

                ReplyCancel
                • Hedi Herdiana
                  8 years ago

                  Ok, I’ll try it..

                  ReplyCancel
                • Hedi Herdiana
                  8 years ago

                  Hi, I get the message “An error occurred while building the application. Verify your build assets are correct and try again.”

                  This is my debug: http://i.imgur.com/JtBvE2p.png

                  What is wrong? I have tried to fix many times but until make me confused. Help me please.

                  ReplyCancel
                  • Narayan Prusty
                    8 years ago

                    1. Create a new Project and then Copy the code from index.html
                    2. Install Push Plugin
                    3. Don’t run the app in emulator. Run it in device using android build. Create .apk file.

                    Now it must work.

                    ReplyCancel
                    • Hedi Herdiana
                      8 years ago

                      Hi, I get alert “message = The message to send msgcnt = undefined”
                      why undefined? How do I fix it? Help me please.

                      ReplyCancel
                    • Narayan Prusty
                      8 years ago

                      The message is want you need. Just remote alerting of the msgcnt.

                      ReplyCancel
                    • reytabs
                      8 years ago

                      how to notify the message notification?can u helpme.

                      ReplyCancel
                    • reytabs
                      8 years ago

                      hey buddy i need to notify the message in my android notification. .not alerting the message can u help me how to insert that code to notify the message. please..

                      ReplyCancel
            • PUNX
              8 years ago

              yeah when I try tokenID it is undefined…

              ReplyCancel
            • PUNX
              8 years ago

              just please upload the XDK project and all done… really fail so hard badly… maybe I got a problem inserting that code on different lines of HTML… just want it a preview…

              ReplyCancel
        • PUNX
          8 years ago

          I know ajax but the part is this app doesn’t alert you the devideID… how can we know the ID when it just return “RESULT = OK” …. we cant test… please really need help so badly… almost many days

          ReplyCancel
        • PUNX
          8 years ago

          can u give us ur HTML just remove your API/Project Number…. really hard to understand these…

          ReplyCancel
  37. Jasa Aplikasi
    8 years ago

    I also have the same problem. it does not work on android. what is meant by “array of tokens” in the script server. where I get it? which parts that produces “array of tokens”? so I can fill it.

    I want to send push message to all device without register.

    ReplyCancel
    • Narayan Prusty
      8 years ago

      Hey Buddy, Above I have clearly mentioned that token is produced by app and sends it to server while registering user.

      ReplyCancel
      • Sitmar
        8 years ago

        Hi Master, I just beginners in mobile development. Sorry if I’m slow to understand. Would you like to share your demo project (.xdk) on github so I can try it. It will further enhance the value of your tutorial.

        ReplyCancel
        • Narayan Prusty
          8 years ago

          I have provide the complete source code above. Just copy/paste it. Once you have registered the user….send the token to server and store it there.

          You have to code that yourself. Because I don’t know your server domain any other details.

          As you are a beginner, first u need to understand how push notification work before programming it.

          If I will find time then I will surely create a github project. Thanks.

          ReplyCancel
          • Tabada
            8 years ago

            stupid author… u provide complete sourcecode? where the fuck is it? it’s just a fucking code not a complete HTML…

            ReplyCancel
          • Narayan Prusty
            8 years ago

            Done https://github.com/qnimate/intel-xdk-android-push

            ReplyCancel
            • kevin
              8 years ago

              this is an error how to fix it?

              An error occurred while building the application. Verify your build assets are correct and try again.

              ReplyCancel
              • Narayan Prusty
                8 years ago

                1. Create a new Project and then Copy the code from index.html
                2. Install Push Plugin
                3. Don’t run the app in emulator. Run it in device using android build. Create .apk file.

                Now it must work. Let me know if it works.

                ReplyCancel
                • kevin
                  8 years ago

                  its the same master.. help me .

                  ReplyCancel
                  • Narayan Prusty
                    8 years ago

                    I just tried to import the project in a new computer and build it successfully.

                    Make sure you are importing the “QNimate/QNimate.xdk” file.

                    ReplyCancel
                • kennyworker
                  7 years ago

                  It works !
                  Thank you very much! Your sample is the best one I ever seen.

                  ReplyCancel
                • Varun Sharma
                  7 years ago

                  Hi
                  Code is not working for me showing the error “Warning: the Cordova CLI 3.3 and 3.5 build options have been deprecated and will be removed before the end of 2015 (or sooner). Applications built with these versions of the Cordova CLI are no longer or will soon be no longer accepted by either the Google Play or the Apple Store.”

                  every time I include push plugin is give me error , please help me out

                  ReplyCancel
                • Renzo
                  7 years ago

                  I have problems installing pushPlugin. How do I install pushPlugin locally (no repo)? Help!
                  With repo I always Error: Plugin PushPlugin failed to install. thank you

                  ReplyCancel
  38. Hedi Herdiana
    8 years ago

    Hi, not working for android. where the source code?

    ReplyCancel
    • Narayan Prusty
      8 years ago

      App source code and server side push code is given above. All code is tested by me on Android and iOS. Make sure you installed the push plugin and making a cordova build not legacy build.

      If still you getting error then debug and check for errors in JavaScript console.

      ReplyCancel
      • Hedi Herdiana
        8 years ago

        I get: “Android send notification failed with error: No devices set”

        This is my app: https://www.dropbox.com/s/ghjzf1hkpomzct7/TestPushNotification.apk?dl=0

        This is my push.php:
        http://olshop.id/push/

        Please help me.

        ReplyCancel
        • Narayan Prusty
          8 years ago

          You need to execute the server script with api key and device token.

          You need to send device token from mobile to server once user is registered.

          You will find API key in google developer console.

          ReplyCancel
          • Hedi Herdiana
            8 years ago

            I have followed all your instructions, this is my source code: http://olshop.id/push/sender.html Please fix what is wrong?

            ReplyCancel
            • Narayan Prusty
              8 years ago

              dude please concentrate. The $devices variable is empty in server script. Populate it with the device identifier. Please read the tutorial carefully.

              ReplyCancel
              • Tabada
                8 years ago

                yeah it’s empty cause u didn’t teach us where to get that and where we can see that shit u fucking shit.. I have 10 hours already and I cant sleep very well… fuck this shit

                ReplyCancel
                • Metrophobe
                  7 years ago

                  you don’t get it do you? THE XDK APP GETS THE TOKEN FOR YOU but you got to have a GOOD PROJECT ID FOR THIS TO WORK

                  ReplyCancel
              • Hedi Herdiana
                8 years ago

                hi, it still does not work.

                ReplyCancel
              • Metrophobe
                7 years ago

                To all those who are having a hard time understanding why TOKEN is EMPTY.

                This is to clarify that the tutorial is perfectly fine. You are NOT getting the whole concept of how GCM works.

                THERE ARE THREE PARTS HERE INVOLVED

                THE PHP SERVER
                THE PHONE APP
                THE GCM SERVICE

                STEP 1 – PHONE APP CONNECTS TO GCM SERVICE AND GETS TOKEN BACK. NOTE PHONE APP HAS TO HAVE VALID PROJECT ID IN IT. THIS IS WHY THAT TOKEN Variable is empty … it gets POPULATED by the GCM
                STEP 2 – SEND the TOKEN TO the SERVER
                STEP 3 – SERVER can now CONNECT TO GCM with the TOKEN and GCM knows WHERE to send the message thanks to the token……
                STEP 4 – STOP OFFENDING THE TUTOR! GO OFFEND INTEL INSTEAD THEY GOT NO DOCUMENTATION ON XDK and THIS GUY IS DOING YOU a BLOODY FAVOUR.

                ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 109 Comments Cordova
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Include Push Plugin
  • iOS Prerequisite
  • Android Prerequisite
  • Understanding Push Notification Mechanism
  • Registering User
  • Sending Push Notification from PHP Server to Apple Push Servers
  • Sending Push Notification from PHP Server to Google Cloud Messaging Android Servers
Related Articles
  • Push Notifications in Intel XDK using pushMobi
  • Retrieve Device Information Using Intel XDK
  • Find Recorded Audio File Location in Cordova
  • Working with File System using Intel XDK
  • Share Button for Intel XDK APP
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license