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]

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.

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.

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

activity_main.xml

GcmBroadcastReceiver

GcmIntentService.java

RegisterApp.java

MainActivity.java

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. Required fields are marked *

Share