Push Notifications in Android Platform


I am looking to write an app that receives pushed alerts from a server. I found a couple of methods to do this.

  1. SMS - Intercept the incoming SMS and initiate a pull from the server
  2. Poll the server periodically

Each has its own limitations. SMS- no guarantee on arrival time. Poll may drain the battery.

Do you have a better suggestion please? Thanks very much.

8/3/2017 3:04:46 PM

Accepted Answer

Google's official answer is the Android Cloud to Device Messaging Framework (deprecated) Google Cloud Messaging(deprecated) Firebase Cloud Messaging

It will work on Android >= 2.2 (on phones that have the Play Store).

5/29/2016 3:14:20 AM

(cross-posting from an answer I gave to a similar question - Does Android support near real time push notification? )

I recently started playing with MQTT for Android as a way of doing this sort of thing (i.e. push notification that is not SMS but data driven, almost immediate message delivery, not polling, etc.)

I have a blog post with background information on this in case it's helpful

(Note: MQTT is an IBM technology, and I should point out that I work for IBM.)


My understanding/experience with Android push notification are:

  1. C2DM GCM - If your target android platform is 2.2+, then go for it. Just one catch, device users have to be always logged with a Google Account to get the messages.

  2. MQTT - Pub/Sub based approach, needs an active connection from device, may drain battery if not implemented sensibly.

  3. Deacon - May not be good in a long run due to limited community support.

Edit: Added on November 25, 2013

GCM - Google says...

For pre-3.0 devices, this requires users to set up their Google account on their mobile devices. A Google account is not a requirement on devices running Android 4.0.4 or higher.*


Android Cloud to Device Messaging Framework

Important: C2DM has been officially deprecated as of June 26, 2012. This means that C2DM has stopped accepting new users and quota requests. No new features will be added to C2DM. However, apps using C2DM will continue to work. Existing C2DM developers are encouraged to migrate to the new version of C2DM, called Google Cloud Messaging for Android (GCM). See the C2DM-to-GCM Migration document for more information. Developers must use GCM for new development.

Kindly check the following link:


Here I have written few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find complete tutorial in below URL link

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snip to get Registration ID (Device Token for Push Notification).

Configure project for GCM

Update AndroidManifest file

For enable GCM in our project we need to add few permission in our manifest file Go to AndroidManifest.xml and add below code Add Permission

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.VIBRATE" />

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration

add GCM Broadcast Receiver declaration in your application tag

            android:permission="" ]]>
                <action android:name="" />
                <category android:name="" />


Add GCM Servie declaration

     <service android:name=".GcmIntentService" />

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

protected void onCreate(Bundle savedInstanceState)
     context = getApplicationContext();
         if (checkPlayServices()) 
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);

            if (regid.isEmpty())
            Log.d(TAG, "No valid Google Play Services APK found.");

@Override protected void onResume()
       super.onResume();       checkPlayServices();

# Implement GCM Required methods (Add below methods in LaunchActivity)

private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
            } else {
                Log.d(TAG, "This device is not supported - Google Play Services.");
            return false;
        return true;

private String getRegistrationId(Context context) 
   final SharedPreferences prefs = getGCMPreferences(context);
   String registrationId = prefs.getString(PROPERTY_REG_ID, "");
   if (registrationId.isEmpty()) {
       Log.d(TAG, "Registration ID not found.");
       return "";
   int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
   int currentVersion = getAppVersion(context);
   if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    return registrationId;

private SharedPreferences getGCMPreferences(Context context) 
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),

private static int getAppVersion(Context context) 
         PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
      catch (NameNotFoundException e) 
            throw new RuntimeException("Could not get package name: " + e);

private void registerInBackground() 
{     new AsyncTask() {
     protected Object doInBackground(Object... params) 
          String msg = "";
               if (gcm == null) 
                        gcm = GoogleCloudMessaging.getInstance(context);
               regid = gcm.register(SENDER_ID);               Log.d(TAG, "########################################");
               Log.d(TAG, "Current Device's Registration ID is: "+msg);     
          catch (IOException ex) 
              msg = "Error :" + ex.getMessage();
          return null;
     }     protected void onPostExecute(Object result) 
     { //to do here };
  }.execute(null, null, null);

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM also keep in mine this will be unique for all device, by using this only GCM will send Push Notification.

Receive Push Notifications

Add GCM Broadcast Receiver Class

As we have already declared “” in our Manifest file, So lets create this class update receiver class code this way

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    public void onReceive(Context context, Intent intent) 
    {        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());        startWakefulService(context, (intent.setComponent(comp)));
        Toast.makeText(context, “wow!! received new push notification", Toast.LENGTH_LONG).show();

Add GCM Service Class

As we have already declared “” in our Manifest file, So lets create this class update receiver class code this way

public class GcmIntentService extends IntentService
{     public static final int NOTIFICATION_ID = 1;     private NotificationManager mNotificationManager;     private final static String TAG = "GcmIntentService";     public GcmIntentService() {
     }     @Override
     protected void onHandleIntent(Intent intent) {
          Bundle extras = intent.getExtras();
          Log.d(TAG, "Notification Data Json :" + extras.getString("message"));

          GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
          String messageType = gcm.getMessageType(intent);          if (!extras.isEmpty()) {          if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
               .equals(messageType)) {
               sendNotification("Send error: " + extras.toString());
          } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
          .equals(messageType)) {
          sendNotification("Deleted messages on server: "
          + extras.toString());          // If it's a regular GCM message, do some work.
          } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
          .equals(messageType)) {
          // This loop represents the service doing some work.
          for (int i = 0; i < 5; i++) {
               Log.d(TAG," Working... " + (i + 1) + "/5 @ "
               + SystemClock.elapsedRealtime());               try {
               } catch (InterruptedException e) {
             Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
        }        // Release the wake lock provided by the WakefulBroadcastReceiver.
     }     // Put the message into a notification and post it.
     // This is just one simple example of what you might choose to do with
     // a GCM message.
     private void sendNotification(String msg) {          mNotificationManager = (NotificationManager) this
          PendingIntent contentIntent = PendingIntent.getActivity(this, 0,          new Intent(this, LaunchActivity.class), 0);

          NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(          this)
          .setContentTitle("Ocutag Snap")
          .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
          .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

          mBuilder.setContentIntent(contentIntent);          mNotificationManager.notify(NOTIFICATION_ID,;

There is a new open-source effort to develop a Java library for push notifications on Android based on the Meteor web server. You can check it out at the Deacon Project Blog, where you'll find links to Meteor and the project's GitHub repository. We need developers, so please spread the word!


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]