Push notifications with PhoneGap and Android

In this article I’ll explain how to setup push notifications with PhoneGap and Android. I also wrote an article in how to setup push notifications with PhoneGap for iOS.

android

Prepare your PhoneGap app

First off, you have to install the Push Plugin for PhoneGap:

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

You also need the PhoneGap device plugin:

$ cordova plugin add org.apache.cordova.device

The next thing you need to do, is copy the PushNotification.js -file to the www-folder of your app (or in a subdirectory in your app, whatever, your app just needs this file). Include this file in your apps’ index.html -file:

<script type="text/javascript" src="js/PushNotification.js"></script>

Now we just need to add some JavaScript to allow our app to register the users’ device and to receive push notifications on it:

// Setup push notifications:
try
{
    var pushNotification = window.plugins.pushNotification;
    if (window.device.platform == 'android' || device.platform == 'Android') {
        // Register for Android:
        pushNotification.register(
            pushSuccessHandler,
            pushErrorHandler, {
                "senderID":"...", // Project number from Google Developer Console
                "ecb":"onNotificationGCM"
            }
        );
    }
}
catch(err)
{
    // For this example, we'll fail silently ...
    console.log(err);
}

/**
 * Success handler for when connected to push server
 * @param result
 */
var pushSuccessHandler = function(result)
{
    console.log(result);
};

/**
 * Error handler for when not connected to push server
 * @param error
 */
var pushErrorHandler = function(error)
{
    console.log(error);
};

/**
 * Notification from GCM
 * @param e
 */
var onNotificationGCM = function(e)
{
    // ...
};

Tip: console.log() on Android

If you develop with PhoneGap you sometimes want to have access to the  console.log() -messages which derive from the Android device your testing on. By entering the following command in your terminal you can read these messages:

$ adb logcat CordovaLog:D \*:S

Setup your app within Google Developer Console

This is the part where we register our app with Google’s Cloud Messaging for Android-API (GCM), so our app is allowed to send push notifications by Google. I’ll try to explain step-by-step on how to set this all up:

  • Log in on the Google Developer Console.
  • Create a new API Project.
  • In the menu, select ‘API’s & Auth’.
  • Select ‘Google Cloud Messaging for Android’ en set it ‘ON’.
  • Then in the menu, select ‘Credentials’.
  • At ‘public key access’, create a new public key.
  • Select ‘server’-key and add the IP address(es) which is/are allowed to send push notifications. For test purposes you can add the address 0.0.0.0/0 .
  • Copy the API key that’s generated here. You need this in your PHP script to connect to the GCM server.
  • Log in on the Google Play Developer Console.
  • Select your app and go to ‘Services & Api’s’.
  • Bind your GCM App ID with your App. Your GCM App ID is the Project Number that’s assigned to your Google API Project.

That’s it! You now have set you app up at Google to send push notifications!

Setup your PHP Server

This example provides a simple example on how to setup a simple PHP server to send your push notifications to Google’s GCM server. There are out-of-the-box solutions for this, but it’s also good to have a bare minimum example on how to achieve this:

// Set parameters:
$apiKey = '...'; // API key from Google Developer Console
$gcmUrl = 'https://android.googleapis.com/gcm/send';

// Get the device token (fetch from database for example):
$regid  = '...';

// Set message:
$message = 'Hello Android!';

// Send message:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $gcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
    array(
        'Authorization: key=' . $apiKey,
        'Content-Type: application/json'
    )
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(
        array(
            'registration_ids' => array($regid),
            'data' => array(
                'message' => $message
            )
        ),
        JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
    )
);

$result = curl_exec($ch);
if ($result === false) {
    throw new \Exception(curl_error($ch));
}

curl_close($ch);

That’s it! Now you are able to send push notifications from your PHP server to your Android PhoneGap app.

Special thanks go out to Gonzalo Ayuso who wrote an excellent article on how to setup a PHP server to send push notifications to Android. I also wrote a dutch translation of this article.

One thought on “Push notifications with PhoneGap and Android

Leave a Reply

Proudly powered by WordPress
Theme: Esquire by Matthew Buchanan.