2012-10-14

As per google’s documentation “Google Cloud Messaging for Android (GCM) is a service that helps developers send data from servers to their Android applications on Android devices”. Using this service you can send data to your application whenever new data is available instead of making requests to server in timely fashion. Integrating GCM in your android application enhances user experience and saves lot of battery power.



Overview of Google Cloud Messaging, PHP and MySQL

In this tutorial i used PHP as server side programming language and MySQL as server side database. I installed WAMP server to install php, mysql, apache for me. If you are new to connecting PHP, MySQL to android application, i suggest you go through this tutorial
How to connect Android with PHP, MySQL

You can go through the official documentation if you want to know more about GCM.

The following diagram is illustrating the overview of the tutorial and the purpose of each entity involved in this tutorial.



Registering with Google Cloud Messaging

1. Goto Google APIs Console page and create a new project. (If you haven’t created already otherwise it will take you to dashboard)



2. After creating project you can see the project id in the url. Note down the project id which will be used as SENDER ID in android project. (Example: in #project:460866929976 after semicolon 460866929976 is the sender id)

3. After that click on Services on the left panel and turn on Google Cloud Messaging for Android.

4. Once you are done, click on API Access and note down the API Key. This API key will be used when sending requests to GCM server.

Creating MySQL Database

1. Open phpmyadmin panel by going to http://localhost/phpmyadmin and create a database called gcm. (if your localhost is running on port number add port number to url)
2. After creating the database, select the database and execute following query in SQL tab to create gcm_users table.

Check the following video to know about creating database and php project.

Creating & Running the PHP Project

When we are making request to GCM server using PHP i used curl to make post request. Before creating php project enable curl module in your php extensions.

Left Click on the WAMP icon the system try -> PHP -> PHP Extensions -> Enable php_curl

1. Goto your WAMP folder and inside www folder create a folder called gcm_server_php. (In my case i installed wamp in C:\WAMP)
2. Create a filed called config.php This fill holds the database configuration and google api key.

3. Create another file called db_connect.php This file handles database connections, mainly opens and closes connection.

4. Create a new file named db_functions.php This file contains function to perform database CRUD operations. But i wrote function for creating user only.

5. Create another file named GCM.php This file used to send push notification requests to GCM server.

6. Create a new file called register.php This file receives requests from android device and stores the user in the database.

7. Create another file called send_message.php This file used to send pushnotification to android device by making a request to GCM server.

8. Finally create a file called index.php and paste the following code. The following code will create a simple admin panel to list all the user devices and provides a panel to send push notification to individual devices.

Following is a screenshot of the admin panel generated by above code (with users registered)

Until now we are done with setting up server side part. Now we can start writing android code.

Installing helper libraries and setting up the Emulator

Before start writing android code we need to install the helper libraries and make required changes to the emulator.

1. Goto your android SDK folder and open SDK Manager and install Google Cloud Messaging for Android Library under Extras section. (If you don’t see Google Cloud Messaging for Android Library update your SDK manager to latest version)

2. After installing the library it will create gcm.jar file in your Andoird_SDK_Folder\extras\google\gcm\gcm-client\dist. Later you need to add this .jar file to your android project.

3. Now open your AVD Manager and create a new Google API emulator and start the emulator. (Note: To test gcm application in emulator you need to test it on Google API device only)
4. After launching emulator press Menu button goto Settings. Select Accounts & Sync. And then press Add Account button and add a Google account.

Check the following video to know about adding google account in the emulator

Once you are done adding google account you are good to start android project.

Creating Android Project

1. Create a new android project and fill the required details. While creating project select minimum SDK version API 8 to support wider range of devices.
2. After creating new project open AndroidManifest.xml file and do the following changes.

The following permission are required to make your project support gcm.

INTERNET – To make your app use internet services
ACCESS_NETWORK_STATE – To access network state (used to detect internet status)
GET_ACCOUNTS – Required as GCM needs google account
WAKE_LOCK – Needed if your app need to wake your device when it sleeps
VIBRATE – Needed if your support vibration when receiving notification

Also add some broadcast receivers as mentioned below.

In the following code replace all com.androidhive.pushnotifications with your android package name.

3. Open your strings.xml file under res -> values folder and paste following strings. (If you don’t have strings.xml file, create a new one)

4. Create a new class named AlertDialogManager.java and paste the following code. This class used to show alert dialog in your application.

5. Create another class named ConnectionDetector.java This class used to detect internet connection status.

6. Create class file called CommonUtilities.java and type the following code. This class contains the GCM configuration and our server registration url.

SERVER_URL – Your server user registration url
SENDER_ID – Google project id

7. Create a new class called ServerUtilities.java with following content. This class has following funtions

8. Add a new class file called GCMIntentService.java This class handles all GCM related services.

9. Here i am adding a registration screen where user can register using their details. To make this tutorial simple i am asking only name and email only. Once user registration is done the user details will be sent to our server where the user details will be stored in mysql database.

Create a new xml file called activity_register.xml under res -> layout folder and paste the following code.

10. Create a new class called RegisterActivity.java This class will be used to handler user registration.

In the following code first internet status and gcm configuration is checked and once user presses the registration button user details will be send to MainActivity.java from there they will send to our server.

11. Now open your main activity file (In my case MainActivity.java) and type the following code.

In the following code

I am receiving name, email sent from RegisterActivity and storing them in static variables.

Then i am checking whether this device has gcm registration id, if not i am registering it on gcm by calling GCMRegistrar.register(this, SENDER_ID) method

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() method will be called when device gets a new push notification message. For now i am displaying the message on the screen. You might need to take appropriate action on the message depending upon your app requirement. (Example: Storing it in SQLite database)

Now we are done with our android project. Following are the enhancements to enhance the user experience.

Playing custom notification sound

If you want to play custom notification sound, copy your sound file in your project assets folder and write the following code in in private static void generateNotification() function which presents in GCMIntentService.java file.

Vibrating device on receiving new notification

If you wan’t to vibrate the device on receiving a new notification add the following lines of code in private static void generateNotification() function which presents in GCMIntentService.java file. Also make sure that you added following permission in AndroidManifest.xml file

Waking up device on receiving new notification

You can also wake the device on receiving new notification if the device is sleeping. Add the following permission in your AndroidManifest.xml file

Add a new class file named WakeLocker.java and paste the following code.

and call the following lines code in private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() presents in MainActivity.java.

Run the project and i’ll be happy to solve the errors if you got any.

Show more