Adobe
Products

Top destinations

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • SiteCatalyst
  • Students
  • Elements family

Adobe Creative Cloud

  • What is Adobe Creative Cloud?
  • Design
  • Web
  • Photography
  • Video
  • Students
  • Teams
  • Enterprise
  • Educational institutions

Design and photography

  • Photoshop
  • Illustrator
  • InDesign
  • Adobe Muse
  • Lightroom

Video

  • Adobe Premiere
  • After Effects

Web development and HTML5

  • Edge Tools & Services [opens in a new window]
  • Dreamweaver
  • Gaming [opens in a new window]

Adobe Marketing Cloud

  • What is Adobe Marketing Cloud?
  • Digital analytics
  • Social marketing
  • Web experience management
  • Testing and targeting
  • Media optimization

Analytics

  • SiteCatalyst
  • Adobe Discover
  • Insight

Social

  • Adobe Social

Experience Manager

  • CQ
  • Scene7

Target

  • Test&Target
  • Recommendations
  • Search&Promote

Media Optimizer

  • AdLens
  • AudienceManager
  • AudienceResearch

Document services

  • Acrobat
  • EchoSign [opens in a new window]
  • FormsCentral [opens in a new window]
  • SendNow [opens in a new window]
  • Acrobat.com [opens in a new window]

Publishing

  • Digital Publishing Suite

  • See all products
Business solutions

By business need

  • Digital analytics
  • Digital publishing
  • Document management
  • Media optimization
  • Social marketing
  • Testing and targeting
  • Video editing and serving
  • Web development [opens in a new window]
  • Web experience management
  • See all business needs

By industry

  • Broadcast
  • Education
  • Financial services
  • Government
  • Publishing
  • Retail
  • See all industries
Support & Learning

I need help

  • Products
  • Adobe Creative Cloud
  • Adobe Marketing Cloud
  • Forums [opens in a new window]

I want to learn

  • Training and tutorials
  • Certification [opens in a new window]
  • Adobe Developer Connection
  • Adobe Design Center
  • Adobe TV [opens in a new window]
  • Adobe Marketing Center
  • Adobe Labs [opens in a new window]
Download
  • Product trials
  • Adobe Flash Player
  • Adobe Reader
  • Adobe AIR
  • See all downloads
Company
  • Careers at Adobe
  • Investor Relations
  • Newsroom
  • Privacy
  • Corporate Social Responsibility
  • Customer Showcase
  • Contact us
  • More company info
Buy
  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers
  • Adobe Marketing Cloud sales [opens in a new window]
Search
 
Info Sign in
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Welcome,
My Adobe
My orders
My information
My preferences
My products and services
Sign out
My cart
Privacy My Adobe
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out Privacy My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Promotions
Estimated shipping
Tax
Calculated at checkout
Total
Review and Checkout
Adobe Developer Connection /

Android Push Notifications with PhoneGap

by Holly Schinsky

Holly Schinsky
  • devgirl.org

Content

  • Google Cloud Messaging
  • Setting up push notifications
  • Running the sample application
  • Status bar notification
  • Sending a message with node-gcm
  • Collapse key
  • Other plugin options
  • Where to go from here

Created

17 December 2012

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
AndroidHTML5JavaScriptmobilePhoneGap Build
Was this helpful?
Yes   No

By clicking Submit, you accept the Adobe Terms of Use.

 
Thanks for your feedback.

Requirements

Prerequisite knowledge

This article requires at least an intermediate level of PhoneGap development experience.

User level

All

Required products

  • PhoneGap Build

My last article covered push notifications with PhoneGap on Apple devices. In this article, I cover push notifications with PhoneGap on Android for those developing for this platform. I found that I was able to get my notifications working much faster on Android comparatively.

Google Cloud Messaging

Android push notifications are available via the Google Cloud Messaging (GCM) service, which is similar to Apple's Push Notification Service. Previously they were supported through C2DM (the Cloud to Device Messaging framework) but that API has since been deprecated and the Google Cloud Messaging services adds enhancements above and beyond what C2DM offered. There's a Cordova/PhoneGap plugin available to aid in working with the Google Cloud Messaging service.

The message size allotment for the GCM payload is 4kb (String data only), noticeably bigger than the Apple Push Notification requirements of 256 bytes. There's an article about the types of messages that can be sent in detail here. Also, I suggest you look over the documentation for using this service in general here when building your application as there are a lot of details I do not cover in this article. Some points I wanted to highlight from that article are:

  • GCM makes no guarantees about delivery or the order of messages.
  • An Android application on an Android device doesn't need to be running to receive messages. The system wakes up the Android application via Intent broadcast when the message arrives, as long as the application is set up with the proper broadcast receiver and permissions.
  • GCM does not provide any built-in user interface or other handling for message data. GCM simply passes raw message data received straight to the Android application, which has full control of how to handle it. For example, the application might post a notification, display a custom user interface, or silently sync data.

Setting up push notifications

The steps for setting up push notifications in your Android application are:

  1. Create a new Android Cordova project either via the command line tools or Eclipse (command line recommended).
  2. Download the GCM Cordova Plugin.
  3. Follow the steps in the plugin's Readme:
    • Don't forget to setup your Google Cloud Messaging Account as noted in the readme and note your project ID located in the URL. For instance, the number in bold below is the id you need to send in the register() function:

      https://code.google.com/apis/console/?pli=1#project:824841663942
    • Don't forget to change the following to use your GCM project id (from the step above) so that the following code:

      window.GCM.register("[your_sender_id]", "GCM_Event", GCM_Success, GCM_Fail );
    • contains your sender ID:

      window.GCM.register("824841663942", "GCM_Event", GCM_Success, GCM_Fail );
  4. Add code handling for the actions to take when the application receives a message while open or not. For example, you might display a popup alert or a status bar notification.

    Note:
    The plugin handles registering with GCM and has methods for receiving a message, however it does not actually provide the response to the notification code itself, this is something you need to add. Read on further for how to add native code to produce a status bar notification.

If you need more information about GCM project creation, specific steps can be found here.

The PhoneGap plugin includes a sample project already setup to register for push notifications including the AndroidManifest.xml changes and plugin configuration. All you have to do is edit the CORDOVA_GCM_script.js file to use your GCM sender/project id in the register() function and you can run it immediately or use this project as a reference while making the changes to your own.

If you prefer to use Eclipse for your editing, you can simply import the existing Android project that you just created above or the sample included in the plugin and start working from there.

  1. Choose File | New | Project.
  2. Select “Android Project from Existing Code.”
 Figure 1. Select “Android Project from Existing Code”.
Figure 1. Select “Android Project from Existing Code”.

Running the sample application

When you run the sample code from the plugin, it automatically attempts to register your device. If registration is successful, you see a message containing the registration token id. (See the REGID string I circled below in the screenshot of mine running on my Galaxy Tablet.).

Figure 2. You see a message containing the registration token id.
Figure 2. You see a message containing the registration token id.

You should also see the following trace in your console:

10-24 18:24:20.720: V/GCMReceiver:onRegistered(21989): Registration ID arrived! 10-24 18:24:20.730: V/GCMReceiver:onRegisterd(21989): {"regid":"APA91bFobAwM7P3Okxy2al8RI12VcJFUS-giXWTOoWXIObtSPOE1h7FuH1VPLBPgshDI_Fp7aIYVET-ssvGUErlWYA0cKPGhoXT1daqyDsEfem9ZtgZNRhQFv7kLCIVSigYlpMluToPiSHSsFSEdtCDfKoOZqNPsfg","event":"registered"} 10-24 18:24:20.730: V/GCMPlugin:sendJavascript(21989): javascript:GCM_Event({"regid":"APA91bFobAwM7P3Okxy2al8RI12VcJFUS-giXWTOoWXIObtSPOE1h7FuH1VPLBPgshDI_Fp7aIYVET-ssvGUErlWYA0cKPGhoXT1daqyDsEfem9ZtgZNRhQFv7kLCIVSigYlpMluToPiSHSsFSEdtCDfKoOZqNPsfg","event":"registered"})

Once you obtain a registration id as above, you can write server code. The section below covers how to use Node.JS code to send a message to your application. Alternatively, you can use a service like Urban Airship or PushWoosh to start sending notifications. When a message is received, you see additional text displayed as shown in the screenshot below:

Figure 3. When a message is received, you see additional text displayed.
Figure 3. When a message is received, you see additional text displayed.

At this point though, the plugin does not do anything. The next section covers how you can add some additional code for showing a status bar notification when the message is received.

Status bar notification

Since the plugin simply receives the message—whether your app is running or not—but doesn't do anything with it from there, you have choices for what you do with it. One common requirement is to show a message in the native status bar. On iOS, the process is different and the notification is automatically shown. But on Android you have to explicitly code for it.

One option is to use the Cordova StatusBarNotification plugin along with this one. If you want a faster solution, simply add the native Java code into your GCMIntentService.java onMessage() function, as in the following code:

String message = extras.getString("message"); String title = extras.getString("title"); Notification notif = new Notification(android.R.drawable.btn_star_big_on, message, System.currentTimeMillis() ); notif.flags = Notification.FLAG_AUTO_CANCEL; notif.defaults |= Notification.DEFAULT_SOUND; notif.defaults |= Notification.DEFAULT_VIBRATE; Intent notificationIntent = new Intent(context, TestSampleApp.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notif.setLatestEventInfo(context, title, message, contentIntent); String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); mNotificationManager.notify(1, notif);

Also, add the following imports at the top of the file to support the above code:

import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent;

Be sure to replace YourActivityClassName.class with the name of your stub class that extends DroidGap. For instance, in the sample project it is called MainActivity.

The above code sets the notification to include a star icon, vibration and the default sound. An example of it running on my Android Galaxy Tablet is shown below (circled in red).

Figure 4. Status bar notification when it includes a star icon, vibration and default sound.
Figure 4. Status bar notification when it includes a star icon, vibration and default sound.

When you click on the notification, the app opens and shows that a message was in fact received.

Figure 5. Clicking on the notification causes app to open and show that a message was received.
Figure 5. Clicking on the notification causes app to open and show that a message was received.

Status bar notifications displays differently depending on the type of device. For example, Android phones typically show them at the top versus at the bottom as shown in my screenshots.

Sending a message with node-gcm

There's a Node.js library for sending notifications through Google Cloud Messaging. It's called node-gcm. Below is the code I used to send my device a message.
Note that I have changed the keys. In the Sender parameter, specify your own API key that Google gave you when you registered for the Google Cloud Messaging service. You received two API keys, a browser and server key, either should work here. If one does not, try the other. Also specify the token returned to your application when you registered using the plugin above. This is the registration id that was printed to the screen and console when you ran the application and called the GCM register function.

var gcm = require('node-gcm'); var message = new gcm.Message(); var sender = new gcm.Sender('AIzaSyCDx8v9R0fMsAsjoAffF-P3FCFWXlvwKgL'); var registrationIds = []; message.addData('title','My Game'); message.addData('message','Your turn!!!!'); message.addData('msgcnt','1'); message.collapseKey = 'demo'; message.delayWhileIdle = true; message.timeToLive = 3; // At least one token is required - each app registers a different token registrationIds.push('APA91bFobAwN7P3Okxy2al8RI12VcJFUS-giXWTOoWXIObtSPOE1h7FuH1VPLBPgshDI_Fp7aIYVET-ssvGUErlWYA0cKPGhoXT1daqyDsEfem9ZtgZNRhQFv7kLCIVSigYlpMluToPiSHSsFSEdtCDfKoOZqNPgfs'); /** * Parameters: message-literal, registrationIds-array, No. of retries, callback-function */ sender.send(message, registrationIds, 4, function (result) { console.log(result); }); /** Use the following line if you want to send the message without retries sender.sendNoRetry(message, registrationIds, function (result) { console.log(result); }); **/

Set the name of the title and message keys explicitly to title and message as the application plugin code is looking for that in GCMIntentService.java:

Bundle extras = intent.getExtras(); if (extras != null) { try { String title = extras.getString("title"); String message = extras.getString("message"); .... } }

Collapse key

According to the Android developer documentation, when you define a collapse key, it only deliver the last notification received with a given collapse key, therefore saving the user from becoming 'over-notified' such as in the case of sports scores for example.

Figure 6. Set the name of the title and message keys explicitly to title and message. Also, note these status bar notifications appear in the expanded list (if not dismissed yet), as in the Figure 7.
Figure 6. Set the name of the title and message keys explicitly to title and message. Also, note these status bar notifications appear in the expanded list (if not dismissed yet), as in the Figure 7.
 Figure 7. Status bar notifications are shown in the expanded list.
Figure 7. Status bar notifications are shown in the expanded list.

Other plugin options

Lastly, I wanted to point out that if you are searching for information about Cordova push notification plugins for Android, you may also come across another plug-in in shader's GitHub here. This plugin is designed to be more specific to using notifications from PushWoosh, which I covered in my blog post, "Easy PhoneGap Push Notifications with Pushwoosh." The plugin's API more closely resembles the iOS Cordova PushNotification plugin and, interestingly enough, still worked in receiving push notifications from my Node.js service completely outside of the PushWoosh service when I tested it. Additionally, I did not have to add the native Java code shown above to show the status bar notification.

Where to go from here

Below are some related links you may want to check out:

  • Easy PhoneGap Push Notifications with Pushwoosh
  • Cordovapush Project – cross-platform push server based on node-apn and node-gcm
  • Urban Airship Push Notification Service – integrates with PhoneGap

Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

More Like This

  • Getting started with Kendo UI Mobile
  • Using Parse.com with PhoneGap – Part 1: A marriage made in Awesome
  • Building PhoneGap applications powered by Database.com
  • Using Parse.com with PhoneGap – Part 2: The phone strikes back

Products

  • Adobe Creative Cloud
  • Creative Suite
  • Adobe Marketing Cloud
  • Acrobat
  • Photoshop
  • Digital Publishing Suite
  • Elements family
  • SiteCatalyst
  • For education

Download

  • Product trials
  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR

Support & Learning

  • Product help
  • Forums

Buy

  • For personal and professional use
  • For students, educators, and staff
  • For small and medium businesses
  • Volume Licensing
  • Special offers

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2013 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy | Cookies

Ad Choices

Reviewed by TRUSTe: site privacy statement