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:
1 |
$ cordova plugin add https://github.com/phonegap-build/PushPlugin.git |
You also need the PhoneGap device plugin:
1 |
$ 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:
1 |
<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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
// 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 Android GCM * @param e */ var onNotificationGCM = function(e) { // Check which event: switch(e.event) { case 'registered' : { console.log('android reg id: ' + e.regid); break; } } }; |
Please note that there is one minor difference between the Android and the iOS-approach: whereas iOS gives the registration ID in the pushSuccessHandler , Android sends a notification of the registered -event.
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:
1 |
$ 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// 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.
Visitors give this article an average rating of 3.4 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Great article Giel! Thank you for sharing
Hi,
I am trying to implement push notification in Android-Phonegap. I am successfully getting following response – 1. deviceready event received 2. registering Android
but i am not getting Google Reg. ID. I am following the following source code https://github.com/phonegap-build/PushPlugin
Please let me know if i am missing something. Thanks in Advance.
This could have various reasons. Did you for example make sure to:
Another ‘gotcha’ here might be that iOS gives you the registration ID on the successHandler, but GCM gives it in the notification handler:
Hi Giel i have setup my php server,I dont know where to mentioned this url in the javascript code.Please help me.
You don’t have to setup a URL in your JavaScript code; the Phonegap plugin handles the requests. Your PHP server makes a request to the GCM server and the GCM server communicates with your app.
Hey thanks for this, i need more clarification on where to put the url. Where exactly in the phonegap plugiin.
Hi Giel can we setup a java server for this. Please let me know
Of course you can, any server can do. You’ll just have to write the Java equivalent to the code above.
hi,
everything works perfectly, but when I click on the notification and the app is in the background, in the DOM shows only the last notification.
Collpasse_key is not set
How to receive all messages in order of arrival?
Thank you in advance
hi,
can you please tell how to redirect to specific page/state/url when the user taps on that push notification!
hi,
i´m getting ClassNotFound-Error (guess the PushPlugin).. i did exactly as you described – added the plugin and the javascript, customized the project id from the google developer console)
what am i doing wrong? 🙁
Just one question: Do I really need to install Cordova to use the Push Plugin for PhoneGap? I’ve been told I can use only PhoneGap, without Cordova, is this even possible? I’m tryint to avoid Cordova whenever possible, thanks…
Can you specifiy where to add (// Setup push notifications:) script
do you got a reply for your question
Good article . Don’t you have an example with asp.net MVC WEB API? Thamk you
I’m sorry, I don’t work with asp.net.
hey there, I do not understand this line
Log in on the Google Play Developer Console.
Select your app and go to Services & Apis.
Bind your GCM App ID with your App. Your GCM App ID is the Project Number thats assigned to your Google API Project.
If I have not uploaded my application and try to check the push notification, how can I do that?
Congratulations. It’s Works!
Hello, I want to introduce a new push notification service which supports Chrome and Firefox Browsers in both Mobile and Desktop, called Pushify.
Pushify offers you Unlimited Free Browser Push Notifications to Unlimited Subscribers by which you can connect with your customers easily even customer not in your website. Notifications will deliver to your Customers Mobile and Desktop. We are offering Unlimited REST API calls, Geo-Targeting, Scheduled Notifications, Free Plugins to CMS & e-commerce, RSS2Push and many features for free. To know more just visit http://www.pushify.com