Android Push Notification using Google Cloud Messaging (GCM) – Part 2

If you are here, you are already done with Google API Console Registration and WebServer Configuration. If not, it is suggested to refer Google API Console Registration and WebServer Configuration before proceeding further.

GCM Enabled Android Application

1. Setting Google Play Service For enabling support, Google Play Services library is required to add in project. Refer to Google Play Services Setup.

If you are eclipse user, Go to menu Window -> Android SDK Manager -> Extras. Install Google Play Service library from there. It will be downloaded to “sdk\extras\google\google_play_services”.

2. Preparing application manifest Add following permissions in your application manifest file. Declare a receiver in your manifest to receive GCM message and registration id. Add meta data for google play services. Add a service for handling GCM messages in background. Replace all occurrences of com.androidsrc.gcmsample with your package name.

 

3. Setting up UI We will keep it simple. Our launcher activity will have simple one button to register it with GCM server. And one text view for showing registration id after successful registration. Modify your layout res/layout/activity_main.xml as below.

 

4. Setting up SRC files

Create GCMBroadcastReceiver which will extend WakefulBroadcastReceiver in order to keep device awake while processing message from GCM.

 

Create service GCMIntentService which will extend IntentService to perform task of showing notification in a background thread.

 

In MainActivity.java, on clicking of register button we will handle task of registering our application with help of GoogleCloudMessaging api’s. After getting registration id from GCM, we will register with our web server for saving registration id.

We are done with Sample GCM Application. After registration, Go to your web server and try sending message to registered devices via GCM. You will receive push notification from GCM server.

You may also like...

  • Pingback: Android Push Notification using Google Cloud Messaging GCM()

  • johndoe

    Message and Server Time are coming in as null?

    • elricloud .

      Replace $message = array(“Hola zelda”=>$message);
      with $message = array(“message”=>$message, “timestamp”=>”10-Aug-2015”);
      File: device_sendmsg.php and register_user.php

      • Ishmael Chibvuri

        Hello There.. Mine is not registering on my web server.. What URL should I put on the WEB_SERVER_URL. Thanks.

        • Blair Doyle

          “http:///register_user.php”

  • Nelson Díaz Nuñez

    and how can i unregister to the service?

    • Blair Doyle

      Did you every sort this out? Unregistering works in a strange way in that the client will be automatically unregistered if a GCM message is pushed to the device and the app is no longer installed.

      Problem you can run into with this tutorial is if you successfully register to GCM but fail to input the client ID into your web server.. you now have a registered device that wont push the data to the web server after you solved the problem.

      I solved that only by artificially inputting the client ID into the MySQL DB and sending a push message while the app was not on my device. Next install it worked.

    • Jatin Rane

      Just Uninstall it !!

  • Ravi Sanchala

    Hi,
    Really great tutorial .. its working perfectly fine for me … and thanks for this tutorial
    i was wondering .. that can i send the image message also using GCM and if yes can you please guide..

    thanks in advance…
    cheers 🙂

    • Mahadev Prasad

      Sir, can you give some inputs how you are able to achieve? what are the changes you have done. The tutorial, straight out of the box not working. You can share the complete code files also.

      In my case the device is registered in Web server without problem. But
      the message is not delivering. There is no clear information with
      screenshots in the PHP webserver tutorial. The index.php is showing the
      number of users registered with the register IDs. But when I type
      message in the text area box and submit, there is no confirmation
      message appearing on the screen about what happened to this message.
      But, the message is not delivered to Device. I have tried all the
      changes suggested here but no success.

      Your input will help so many peoples.

      • Holger

        Ever sorted this out?

  • Lucas Soares

    Hi. The registration with the webservice always failed. Can anyone help me?

    • Harry Martin

      I would recommend you to get the services from experts mentioned here http://learnsauce.com/googlecloudmessagingtutorial/ The tutorials comes for FREE with 100% source code.

      • Mahadev Prasad

        I have gone there and downloaded the GCM project sources files and worked as per their instructions. But, that project is also imperfect and no use unless you have ability to de-bug the code.

        Surprisingly the said website uses the same Code given in this blog for server side and part of the code for client side applications authored by Ravi Tamada, but seems to be latest. Some of the errors mentioned here were corrected and user registration is expanded with input of User Name and Mail Id.

        The main drawback and the funny thing of the project source is, the server side coding and messaging(browser) interface is having GCM push concept(copy of the same code in this blog). Whereas, the Client side code is having Device to Device Chatting Code. The message sent from server is not delivered to devices.

        Either way, the description of the project is misguiding and I really unable to understand, why these people do not test their files thoroughly before distributing, and extend further help by answering the queries raised in the forum/comments.

    • Blair Doyle

      If you used the first part of this tutorial, you may encounter an issue in the register_user.php

      line 9 , the tutorial has this in the code:

      if (isset(isset($_POST[“regId”])) {

      Adjust it to read:

      if (isset($_POST[“regId”])) {

      Hope that helps!

    • Mahadev Prasad

      Do not forget to check the error in the ‘db_functions.php’ INSERT query it is mentioned table ‘reg_users’ in another place SELECT query it is mentioned as ‘users’. Update both with identical name.

      In my case the device is registered in Web server without problem. But the message is not delivering. There is no clear information with screenshots in the PHP webserver tutorial. The index.php is showing the number of users registered with the register IDs. But when I type message in the text area box and submit, there is no confirmation message appearing on the screen about what happened to this message. But, the message is not delivered to Device. I have tried all the changes suggested here but no success.

      I request the writer of this tutorial to give some more information on the above. Even, the writer has not corrected the identified mistakes in the tutorials. If out of 100, one or two getting success with their efforts by de-bugging the code, then there is no point in writing this type of incomplete tutorials. We have to remove everything from device, webserver and look for different tutorials. By that time, lot of time and efforts are wasted.

      • Arcenio

        Heya! The RegId that is saved in the database seems to turn into a random jumbled combination of characters and integers and NOT the one initialized here:

        private static final String PREF_GCM_REG_ID = “chars-3dd1e”;

        Is this supposed to be correct? or am i doing something wrong? thanks!

  • shaymol

    how can I get this PREF_GCM_REG_ID

    • Junaid TT

      I am having the Same problem

  • Seetharaman

    Hi I followed this tutorial and implemented GCM in one of my prod app,device getting registered well but I am facing a serious issue that for few users of my app gcm.register(GCM_SENDER_ID) giving empty registration id almost for 2 out of every 10 users i am seeing this issue,i faced this issue with my device itself but if i uninstall and reinstall app then registration id is getting generated Please help me out to resolve this issue as my app is a prod app with daily more than 300 users coming in.

  • Bryan Torres Vega

    I’m getting the “registration with web server failed” and another question guys what am I suppose to put in the PREF_GCM_REG_ID ?

  • Nork

    ERES UN CRACK TIOOOOOOOOOOOO!!! GRACIAS!!

  • Pritish Joshi

    I followed the Tutorial and successfully registerd with GCM?

    but the problem is how can i send push notification

    because my index.php shows that ) connected users

    • ulimhd

      in register_user.php , change
      if (isset(isset($_POST[“regId”])) {
      to
      if (isset($_POST[“regId”])) {

      • nrj

        thnku

  • ulimhd

    I managed to receive the notification on my Bluestacks emulator.

    Here’s what I did (basically I did what the other suggested in this comment section):

    1. In the register_user.php file, change the line
    if (isset(isset($_POST[“regId”])) {
    to
    if (isset($_POST[“regId”])) {

    2. in the db_functions.php file, edit the table name “users” to “reg_users”

    3. in the device_sendmsg.php file, edit the part
    $message = array(“Hello Zelda” => $message);
    to add timestamp, for example
    $message = array(“message”=>$message, “timestamp”=>”04-01-2016”;

    4. put register_user.php in the WEB_SERVER_URL part in MainActivity.java

    • ulimhd

      So I have found what cause the problem. It seems that my phone was really already registered with gcm, but the regId is not registered in my database. The logical thing to do is to unregister my phone from gcm. But first I should add the regId to my reg_users table manually.

      Following this link: http://stackoverflow.com/a/16279189 , to unregister your device from gcm is by uninstalling the apps and try to send message again to the device. The device regId will still exists in your database, so you could still see it when open index.php . It is said it will take 5 minutes before the device fully unregistered from gcm, but I could not confirm this.

  • sunny sun

    it doesn’t work with me and give me errors

  • sunny sun

    The registration process is going well but no notification is coming , could you plz help me ?

  • rabih kahaleh

    hello there,
    i faced the following error
    FATAL EXCEPTION: AsyncTask #1

    java.lang.RuntimeException: An error occurred while executing doInBackground()

    at android.os.AsyncTask$3.done(AsyncTask.java:309)

    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)

    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)

    at java.util.concurrent.FutureTask.run(FutureTask.java:242)

    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

    at java.lang.Thread.run(Thread.java:818)

    Caused by: java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()

    at android.os.Handler.(Handler.java:200)

    at android.os.Handler.(Handler.java:114)

    at android.widget.Toast$TN.(Toast.java:685)

    at android.widget.Toast.(Toast.java:143)

    at android.widget.Toast.makeText(Toast.java:450)

    at android.os.AsyncTask$2.call(AsyncTask.java:295)

    at java.util.concurrent.FutureTask.run(FutureTask.java:237)

    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

    at java.lang.Thread.run(Thread.java:818)

    • Caused by: java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()

      As per logs you are creating handler in thread for which looper.prepare() is not called.
      Please call looper.prepare() and then looper.loop() before creating handler.

      have a look at this video for more clarification.
      https://www.youtube.com/watch?v=UJY55QF5-xA

  • Andrea

    Hi! I also had a problem with sending notifications and I solved it!

    There is an error in gcm_sendmsg.php. Change “include_once ‘./config.php’;” with “include_once ‘./db_config.php’;”

    • Andrea

      sorry, i’ve made a mistake. I had changed the name of the config.php file when i create it. anyway, the tutorial works correctly for me.

  • Jatin Rane

    Thanks for the tutorial !!

  • dhika.

    hello sir, i have a problem, my phone is successfully registered with CGM server, but my server cant send a message to my phone, can you help me?

  • Pingback: ESP8266 – Google Cloud Messaging without external server()