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.


Prepare your PhoneGap app

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

You also need the PhoneGap device plugin:

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:

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

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:

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 .
  • 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:

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.