Google Cloud Messaging (GCM) in Android using PHP Server

GCM for Android is a service which is basically used to send the data from the server to the android devices. One use of this GCM is a push notification service. In this tutorial, I am going through all the steps needed to setup the GCM and build a simple but complete android application in Eclipse.

GCM architecture

GCM Architecture – source: official GCM documentation

The GCM architecture contains the following main three components.

  1. GCM connection server: It receives the messages from the application server and sends these messages to the GCM enabled Android devices.
  2. Application server: It sends the message to the GCM connection server. I will use PHP to build the application server in this tutorial.
  3. Android Application: It receives the messages from GCM connection server after application server sends a message to the GCM connection server.

Life Cycle Flow

GCM life cycle
  1. The Android application enables the GCM by registering to the GCM. The application needs Sender ID to get the registration ID.
  2. GCM connection server receives the sender ID from the application and returns the unique registration id.
  3. The application sends the registration ID to the back-end application server for the storage.
  4. The application server stores the registration Id in the database.
  5. When a new message needs to send, the application server fetches the registration ids from a database and send to the GCM connection server along with the message.
  6. The GCM server sends the message to the application.

Basic Library and Tools Installation
Step I: Install Google Play Services SDK
In order to use Google Services like GCM, you need to have Google Play Services SDK. Look at this official documentation to set up the SDK. One important thing you should take care is in referencing the library. You should not reference the library directly from the Android SDK. Instead first copy the library (i.e. google-play-services_lib) into your current workspace and then reference. In Eclipse, you can do this by checking the “Copy projects into workspace” checkbox while importing the project.

Step II: Install Google APIs 
For testing the project in an emulator, you need Google APIs. Install the Google APIs and create a new AVD with Google APIs as the platform target.

Step III: Install GCM for Android library
In SDK Manager.exe, expand the extras, select and install the Google Cloud Messaging for Android. Now you have set up all the library needed to create a GCM application.

Registering with Google Cloud Messaging 
1. Open the Google Cloud Console.
2. If you haven’t created the API project yet, click CREATE PROJECT. Give the name of the project and click Create.

3. Note down the project number. You will use the project number as sender ID in the registration process.
4. In the sidebar on the left, click APIs and auth.
5. In the displayed list of APIs, turn the Google Cloud Messaging for Android toggle to ON.
6. In the sidebar on the left, click APIs and auth > Credentials.
7. Click CREATE NEW KEY and select Server Key.

 









8. Provide the list of IP address from which the GCM server accepts the request. Left blank if you want to allow any IP.
9. Copy down the Server Key, you will need this later.

Creating a simple PHP application 
So far we have installed necessary libraries and register our account to the Google Cloud Console. Now let us create a simple application server in PHP. Our application server receives the registration id from the application, stores it in the database and sends the message to the application using GCM connection server. To store the registration id, create a simple MySQL table using the following query. [I have created a database named ‘GCMDemo’ for this example]

CREATE TABLE  `GCMDemo`.`tblRegistration` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`registration_id` TEXT NOT NULL
) ENGINE = INNODB;

When the android application runs for the first time, it registers the application to the GCM using sender ID (i.e. project ID mentioned above) and gets the registration Id. The application then sends the registration ID to the application server to store in the database. Here is the PHP file register.php which does the above-mentioned task i.e. it receives the registration id and stores it in the database.

<?php 
$regId = $_GET['regId'];
 
 $con = mysql_connect("localhost","root","");
 if(!$con){
  die('MySQL connection failed'.mysql_error());
 }
 
 $db = mysql_select_db("GCMDemo",$con);
 if(!$db){
  die('Database selection failed'.mysql_error());
 }
 
 $sql = "INSERT INTO tblregistration (registration_id) values ('$regId')";
 
 if(!mysql_query($sql, $con)){
  die('MySQL query failed'.mysql_error());
 }
 
mysql_close($con);

mysql_close($con);

If you want to send the message to the application then you write a message and fetch all the registration ids from the database. You then send the registration ids along with the message to the GCM server. The GCM server gives the response back to the application server. index.php file does the above-mentioned task i.e. it sends the message to the application and echo back the response from the GCM server.

<html>
<head>
 <title>GCM Demo application</title>
</head>
<body>
 <?php
  if(isset($_POST['submit'])){
   $con = mysql_connect("localhost", "root","");
   if(!$con){
    die('MySQL connection failed');
   }
 
   $db = mysql_select_db("GCMDemo");
   if(!$db){
    die('Database selection failed');
   }
 
 
   $registatoin_ids = array();
   $sql = "SELECT *FROM tblregistration";
   $result = mysql_query($sql, $con);
   while($row = mysql_fetch_assoc($result)){
    array_push($registatoin_ids, $row['registration_id']);
   }
 
   // Set POST variables
         $url = 'https://android.googleapis.com/gcm/send';
   
    $message = array("Notice" => $_POST['message']);
         $fields = array(
             'registration_ids' => $registatoin_ids,
             'data' => $message,
         );
   
         $headers = array(
             'Authorization: key=AIzaSyCjGBiwaP3jrEZJoqcq7P-tHUrgBrNYU0E',
             'Content-Type: application/json'
         );
         // Open connection
         $ch = curl_init();
   
         // Set the url, number of POST vars, POST data
         curl_setopt($ch, CURLOPT_URL, $url);
   
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   
         // Disabling SSL Certificate support temporarly
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   
         curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
   
         // Execute post
         $result = curl_exec($ch);
         if ($result === FALSE) {
             die('Curl failed: ' . curl_error($ch));
         }
   
         // Close connection
         curl_close($ch);
         echo $result;
  }
 ?>
 <form method="post" action="index.php">
  <label>Insert Message: </label><input type="text" name="message" />
 
  <input type="submit" name="submit" value="Send" />
 </form>
</body>
</html>

Note

Put the files index.php and register.php inside the folder GCMDemo to run this code.

Creating the android application
The final steps are to create an android application named GCMDemo. The project structure is given below




AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.programmingtechniques.gcmdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />
    
    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <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="com.google.android.c2dm.permission.RECEIVE" />
    <permission android:name="com.programmingtechniques.gcmdemo.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
 <uses-permission android:name="com.programmingtechniques.gcmdemo.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.programmingtechniques.gcmdemo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />
        
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.programmingtechniques.gcmdemo" />
            </intent-filter>
        </receiver>
        <service android:name=".GcmIntentService" />
    </application>

</manifest>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button 
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register Device">
    </Button>"

</RelativeLayout>

GcmBroadcastReceiver

package com.programmingtechniques.gcmdemo;
 
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
 
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
  
    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

GcmIntentService.java

package com.programmingtechniques.gcmdemo;
 
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
 
public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
 private static final String TAG = "GcmIntentService";
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
 
    public GcmIntentService() {
        super("GcmIntentService");
    }
 
    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);
 
        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM
             * will be extended in the future with new message types, just ignore
             * any message types you're not interested in, or that you don't
             * recognize.
             */
            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.i(TAG, "Working... " + (i+1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                sendNotification(extras.getString("Notice"));
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }
 
    // 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.getSystemService(Context.NOTIFICATION_SERVICE);
 
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
 
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
       // .setSmallIcon(R.drawable.ic_stat_gcm)
        .setContentTitle("GCMDemo")
        .setSmallIcon(R.drawable.ic_launcher)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);
 
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
}

RegisterApp.java

package com.programmingtechniques.gcmdemo;
 
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
 
 
public class RegisterApp extends AsyncTask<Void, Void, String> {
 
 private static final String TAG = "GCMRelated";
 Context ctx;
 GoogleCloudMessaging gcm;
 String SENDER_ID = "343594554298";
 String regid = null; 
 private int appVersion;
 public RegisterApp(Context ctx, GoogleCloudMessaging gcm, int appVersion){
  this.ctx = ctx;
  this.gcm = gcm;
  this.appVersion = appVersion;
 }
  
  
 @Override
 protected void onPreExecute() {
  super.onPreExecute();
 }
 
 
 @Override
 protected String doInBackground(Void... arg0) {
  String msg = "";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(ctx);
            }
            regid = gcm.register(SENDER_ID);
            msg = "Device registered, registration ID=" + regid;
 
            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.
            sendRegistrationIdToBackend();
 
            // For this demo: we don't need to send it because the device
            // will send upstream messages to a server that echo back the
            // message using the 'from' address in the message.
 
            // Persist the regID - no need to register again.
            storeRegistrationId(ctx, regid);
        } catch (IOException ex) {
            msg = "Error :" + ex.getMessage();
            // If there is an error, don't just keep trying to register.
            // Require the user to click a button again, or perform
            // exponential back-off.
        }
        return msg;
 }
 
 private void storeRegistrationId(Context ctx, String regid) {
  final SharedPreferences prefs = ctx.getSharedPreferences(MainActivity.class.getSimpleName(),
             Context.MODE_PRIVATE);
     Log.i(TAG, "Saving regId on app version " + appVersion);
     SharedPreferences.Editor editor = prefs.edit();
     editor.putString("registration_id", regid);
     editor.putInt("appVersion", appVersion);
     editor.commit();
   
 }
 
 
 private void sendRegistrationIdToBackend() {
  URI url = null;
  try {
   url = new URI("http://10.0.2.2/GCMDemo/register.php?regId=" + regid);
  } catch (URISyntaxException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
  HttpClient httpclient = new DefaultHttpClient();
  HttpGet request = new HttpGet();
  request.setURI(url);
  try {
   httpclient.execute(request);
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 
 @Override
 protected void onPostExecute(String result) {
  super.onPostExecute(result);
  Toast.makeText(ctx, "Registration Completed. Now you can see the notifications", Toast.LENGTH_SHORT).show();
  Log.v(TAG, result);
 }
}

MainActivity.java

package com.programmingtechniques.gcmdemo;
 
import java.util.concurrent.atomic.AtomicInteger;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends Activity {
  
 private static final 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 static final String TAG = "GCMRelated";
 GoogleCloudMessaging gcm;
 AtomicInteger msgId = new AtomicInteger();
 String regid;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  final Button button = (Button) findViewById(R.id.register);
   
  if (checkPlayServices()) {
      gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
            regid = getRegistrationId(getApplicationContext());
            if(!regid.isEmpty()){
             button.setEnabled(false);
            }else{
             button.setEnabled(true);
            }
  }
   
  button.setOnClickListener(new View.OnClickListener() {
    
   @Override
   public void onClick(View view) {
    // Check device for Play Services APK.
       if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
              regid = getRegistrationId(getApplicationContext());
               
              if (regid.isEmpty()) {
               button.setEnabled(false);
                  new RegisterApp(getApplicationContext(), gcm, getAppVersion(getApplicationContext())).execute();
              }else{
               Toast.makeText(getApplicationContext(), "Device already Registered", Toast.LENGTH_SHORT).show();
              }
       } else {
              Log.i(TAG, "No valid Google Play Services APK found.");
       }
   }
  });
   
   
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
  
 /**
  * Check the device to make sure it has the Google Play Services APK. If
  * it doesn't, display a dialog that allows users to download the APK from
  * the Google Play Store or enable it in the device's system settings.
  */
  
 private boolean checkPlayServices() {
     int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
     if (resultCode != ConnectionResult.SUCCESS) {
         if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
             GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                     PLAY_SERVICES_RESOLUTION_REQUEST).show();
         } else {
             Log.i(TAG, "This device is not supported.");
             finish();
         }
         return false;
     }
     return true;
 }
  
 /**
  * Gets the current registration ID for application on GCM service.
  * <p>
  * If result is empty, the app needs to register.
  *
  * @return registration ID, or empty string if there is no existing
  *         registration ID.
  */
 private String getRegistrationId(Context context) {
     final SharedPreferences prefs = getGCMPreferences(context);
     String registrationId = prefs.getString(PROPERTY_REG_ID, "");
     if (registrationId.isEmpty()) {
         Log.i(TAG, "Registration not found.");
         return "";
     }
     // Check if app was updated; if so, it must clear the registration ID
     // since the existing regID is not guaranteed to work with the new
     // app version.
     int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
     int currentVersion = getAppVersion(getApplicationContext());
     if (registeredVersion != currentVersion) {
         Log.i(TAG, "App version changed.");
         return "";
     }
     return registrationId;
 }
  
 /**
  * @return Application's {@code SharedPreferences}.
  */
 private SharedPreferences getGCMPreferences(Context context) {
  // This sample app persists the registration ID in shared preferences, but
     // how you store the regID in your app is up to you.
     return getSharedPreferences(MainActivity.class.getSimpleName(),
             Context.MODE_PRIVATE);
 }
  
 /**
  * @return Application's version code from the {@code PackageManager}.
  */
 private static int getAppVersion(Context context) {
     try {
         PackageInfo packageInfo = context.getPackageManager()
                 .getPackageInfo(context.getPackageName(), 0);
         return packageInfo.versionCode;
     } catch (NameNotFoundException e) {
         // should never happen
         throw new RuntimeException("Could not get package name: " + e);
     }
 }
}

When you run the above Android application, it displays a layout with a simple button. After clicking the button, the application checks whether it has registration id or not. If not then the application registers the device in the background. Once it gets the registration id, it sends that Id to the application server to store in the database.

The application now can receive the messages sent by the application server. Whenever it sense the new message, then it pushes the message as a notification using notification manager.

SHARE Google Cloud Messaging (GCM) in Android using PHP Server

You may also like...

56 Responses

  1. Perfecto!! me sirvió bastante. Gracias!

  2. Thanks for the tutorial Bibek Subedi, I am getting error 401, unathorized while sending message, do you know how to resolve it?

  3. That may be due to IP blocking. Try allowing all IPs.

  4. Anonymous says:

    Obrigado pelo tutorial, é bastante útil. Tenho só uma questão. É possível o servidor estar a gerar constantemente notificações para o cliente, sendo estas automáticas?

  5. Anonymous says:

    Very work.
    Much thanks

  6. melowomana says:

    Muchas gracias por el estupendo trabajo que has realizado en este tutorial
    (a lot of thanks for the great job that you realized in this tutorial, sorry for my English disastrous)

    Tengo un problema, el teléfono se registra bien en la base de datos, pero cuando envío un mensaje recibo este error:
    (the phone is registered in the database, but when I send a message I get this error:)

    {"multicast_id":4647079667721900339,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1394010001477465%566f028cf9fd7ecd"}]}

    ¿Sabe a qué puede deberse?
    (Do you know what causes that?)

    MUchísiiiiiimas gracias

  7. Anonymous says:

    am getting this error Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/public_html/push/index.php on line 19
    "registration_ids" field cannot be empty

    gcm_regid is my registration id table name in my database

  8. Pankaj says:

    on server side giving error like : {"multicast_id":8006655331888267212,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

  9. Check your sender ID in your account and in code and make sure they are same.

  10. Hola buen dia, me sale este error que podra ser, ya verifique el sender id y esta bien
    {"multicast_id":4613554401423551353,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

  11. $message = array("Notice" => $_POST['message']);
    should be changed to:
    $message = array("message" => $_POST['message']);

    additionally you can also pass the message count:
    $message = array("message" => $_POST['message'], "msgcnt" => 100);

  12. rakhi says:

    am developing chat application using openfire XMPP, in that i want to send message as a notification when user comes to online . So how to create 3rd party gcm server for sending push notification in android

  13. Anonymous says:

    Hi! Thanks for the tutorial! I am getting the error :

    Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:Program Files (x86)EasyPHP-DevServer-14.1VC11datalocalwebgmcindex.php on line 8
    "registration_ids" field cannot be empty

    where line 8 is

    $con = mysql_connect("localhost", "root","");

    do you know how to resolve it? Thank you very much.

  14. Anonymous says:

    I want to share some thing. The problems i faced using this code was the @integer/google_play_service_version.
    Solution for this is simple just copy the version.xml file from
    android-sdkextrasgooglegoogle_play_serviceslibprojectgoogle-play-services_libresvalues
    to
    Android ProjectsPush2appsrcmainresvalues
    That's it.
    It works fine.
    Thanks alot Bibek Subedi

  15. Thanks for the tutorial Bibek, I have register with two different emulators registration ids are saved in a table, when i sent message from index.php i got the success message "{"multicast_id":5376523602110645561,"success":2,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1403070567743368%e2acea95f9fd7ecd"},{"message_id":"0:1403070567743748%e2acea95f9fd7ecd"}]} " but i did not get any notification on any emulator why so?

  16. ma100 says:

    I had the same problem but it turns out if background data is turned off the messages wont deliver. My question though is how to receive message even if background data is turned off?

  17. Thanks for your work. How do this in background? where call doInBackground?

  18. Anonymous says:

    Hello I'm not getting any notification, but I see the message on my logcat?

  19. {"multicast_id":7846920213726960532,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
    im getting this error please help me to slove this

  20. First of all thank you very much for this post.Finally i was able to make it work.
    In create table command the table name is 'tblRegistration' but in the php script it is 'tblregistration'.So just change in the create table command.

    Also after uninstalling and again reinstalling in the emulator,on sending a message,we will get two notifications with the same message.Again uninstall and reinstall you will get 3 messages and so on.So to avoid this just make the 'registration_id' column of the mysql database 'UNIQUE'.

    Thanks.

  21. Thanks for the tutorial, helped me a lot. Very complete and easy to implement!

  22. Anonymous says:

    nice tutorial dude….really helpful

  23. Anonymous says:

    I have same error. how to fix?

  24. Anonymous says:

    Excellent very good Thanks.

    Greetings from México

  25. Anonymous says:

    Usted loco…yo hablo espanol..

  26. Anonymous says:

    dherai dherai thank you again

  27. Anonymous says:

    Dai thank you soo much for the tutorial. And hajur lai naya barsa ko Dherai Dherai Suvakamana.

  28. thank's a lot for this simple and easy tutes

  29. Haresh says:

    Nice Work! It Works For me!

  30. how can i do this….:(

  31. Anonymous says:

    extremely perfect !!!

  32. osiux says:

    ese es el mensaje de respuesta, "success 1" significa que se envio 1 mensaje satisfactoriamente, por otro lado dice "failure 0" lo que significa que hay 0 mensajes que no se enviaron.

  33. Anonymous says:

    {"multicast_id":7651411768730114094,"success":0,"failure":4,"canonical_ids":0,"results":[{"error":"MissingRegistration"},{"error":"MissingRegistration"},{"error":"MissingRegistration"},{"error":"MissingRegistration"}]}

    getting this error

  34. Omolara says:

    This worked for me. I eventually used GcmListenerService instead of IntentService as seen on the developer's site.

  35. Omolara says:

    Hello. You might need to check the url that is being called. Registration id might be missing.

  36. Anonymous says:

    I implemented this tutorial in my workspace. include google-play-service-lib in my project as per above suggestion. First copied it from /extra/google/… in my workspace and referred it to in my project as library.
    But when I am running my project, I got following error :
    Unable to execute dex:Java Heap Space
    Unhandled event loop exception
    Please, help me.

  37. Anonymous says:

    Hello, I installed Google Cloud Messaging for android library(obsolete) in sdk manager. But I am getting problem when starting android app "Unfortunately app has stopped". And i included Google Play Service Lib in my app project. but still I am getting above error. please help me I am newbie in case of android.

  38. Anonymous says:

    I try to implement your above code in new app, but I am getting error "Unfortunately gcmDemo app stopped "
    please, help me as soon as possible. and in logcat error is :

    07-27 19:51:56.569: E/AndroidRuntime(32081): java.lang.NoClassDefFoundError: com.google.android.gms.common.GooglePlayServicesUtil

    I included Google Play service in app as library. because in sdk I am not getting option of Google Colud Messaging.

    please help me please

  39. Mohi says:

    I am trying to implement this tutorial in my application. But when I go to sdk manager to check "Google Cloud Messaging for Android" this option is not available because of that I used Google Play Service but I am getting problem to load app. I am getting error popup with message "Unfortunatelly appname has stopped." and in Logcat I am getting error as below :
    E/AndroidRuntime(1279): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/GooglePlayServicesUtil;

    Could you tell me solution, please.

  40. Anonymous says:

    I implemented this tutorial in my workspace. include google-play-service-lib in my project as per above suggestion. First copied it from /extra/google/… in my workspace and referred it to in my project as library.
    But when I am running my project, I got following error :
    Unable to execute dex:Java Heap Space
    Unhandled event loop exception
    Please, help me.

  41. I implemented this tutorial . but when I registered , it gives unfortunately stop error
    plz give me solution …
    logcat gives no error regarding registration …so i can't able to find any solution..

  42. Harsh Shah says:

    Hi…But there is one limitation of using gcm that we can send only 1000 notifications at time. If we have to send notifications to more than thousands or millions of people than what will be the solution?

  43. Hi Haresh, can u send ur working code web and client to [email protected] urgent
    Thanks in advance.

  44. Prince says:

    I'm also getting following same error:
    {"multicast_id":8201740163271886631,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

    here is my project number on google console:413996049345
    and Server key:AIzaSyAeWSgz6EuCOzIQy0vdyD6lr_ouaRKXLew

  45. monika says:

    I'm also getting following same error:
    {"multicast_id":8500569696540779464,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

  46. nothing is inserted in my databse !

  47. Example for php usage is very old, maybe update this using some simple framework and guzzle?

  48. java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Bundle.isEmpty()' on a null object reference
    at com.assameseonline.gcm.GCMMessageHandler.onHandleIntent(GCMMessageHandler.java:28)

  49. Anonymous says:

    Excellent Article for Demonstration of Push Notification.

  50. Anonymous says:

    Working great hats off………..

  51. I am facing the same problem. How did you fix it?

  52. Unknown says:

    I am facing the same problem. How did you fix it?

  53. i got toast message and record store in database but no notification in device

  54. Unknown says:

    I has try it, but failed.
    Can you send me the whole source code to me at [email protected]
    thank!

Leave a Reply

Your email address will not be published.

Share