2016-02-09

Google Cloud Messaging allows you send lightweight messages from the backend server to all the devices whenever there is new data available. This saves lot of user’s battery by avoiding poll request to server for new data. Using GCM you can build powerful multi platform (iOS, Android & Web) apps like real time chat, news feed, cloud storage and lot more. On top of everything, GCM is completely free and there are no limitations.

As parse.com announced their shutdown recently, GCM is the only best option even though it won’t comes with an admin interface. But don’t worry, we’ll build a simple admin panel in this article.



DOWNLOAD CODE

LIVE DEMO

VIDEO DEMO

As this article is pretty lengthy, I have divided it into 3 parts. Each part covers a unique part in building the final realtime chat app.

Part 1: Covers building the REST API for chat app including the GCM server app.

Part 2: Explains integrating GCM into your android app including a test message.

Part 3: Building Simple Realtime Chat App.

1. Google Cloud Messaging

Typically GCM implementation involves three components. Google cloud messaging server, the app server and the client app. We should take care of writing the app server and the client app. In order to make calls from the app server to GCM server, you can follow HTTP or XAMP protocol. HTTP supports downstream (gcm to client) messages only. XAMP supports both downstream and upstream (device to gcm, then from gcm to server) messages.

Below is the pictorial representation of the overall architecture.



1. First the app connects to GCM server and register itself.

2. Upon successful registration, GCM issues gcm registration token to device. This registration token uniquely identifies each device.

3. The device sends the registration token to our server to store it in MySQL.

4. Whenever app server wants to send push notification, it sends a request to GCM server sending the push message along with the registration token.

5. GCM server identifies the device using the registration token and initiates the push message.

6. The device receives the push messages and further action takes place.

2. Obtaining Google API Key

Google API key is necessary to interact with GCM server. GCM uses this key to identify your server app. Follow the below steps to obtain your API key. Note that the developer console interface is changing more frequently. So, the below steps may vary in future.

1. Goto Google developers console and create a new app. If you have already created one, select the app.

2. Give a name to your new project. Once the project is created, goto project’s dashboard and click on Use Google APIs

3. Under Mobile APIs, click on Cloud Messaging for Android and enable the API by clicking on top enable API button.

4. Once enabled, click on Credentials on the left. You will be asked to create new credentials by showing multiple options. Choose API Key and then Server Key.

5. After choosing Server Key, your API key will be displayed on the dashboard. Note down the API key as we need to use it in our PHP project.

3. Building Simple Realtime Chat App

In this article, we are going to learn how to create a simple realtime chat app by using Android, GCM, PHP, MySQL, HTML & CSS. We use HTML & CSS to build the admin panel for the server app.

Below are the screens of the android app.



And the server app comes with the option of choosing the user(s) / topic and send the push notification.

This part of the article involves building the server app including designing the MySQL database, REST API for mobile app and an admin panel to send push notifications. I am using Netbeans IDE to develop the PHP code and WAMP / MAMP server to create the php, mysql environment.

Now let’s start designing the database first.

4. Designing MySQL Database

For this app we need only three tables. users, chat rooms and messages.

users – This table holds the user information like name, email and other profile information along with gcm registration id.

chat_rooms – Contains the chat room information.

messages – Contains the messages sent in the chat rooms.

Open phpmyadmin and execute the below sql query to create the required database and tables.

5. Creating PHP REST API

I am using Slim framework to create the REST endpoints. If you are not aware of PHP Slim, refer my previous tutorial REST API for Android app using PHP, Slim and MySQL to understand how easily you can create the REST API endpoints for your android app.

Below is the project structure of the PHP app. You have to make sure that you are following same structure while following the further steps.

include – Contains the database classes to perform CRUD operations on the database.

libs – Contains the libraries needed for the app (slim, gcm)

v1 – Root directory of the REST API

index.php, demo.php, styles.css – Required to create the admin interface.

1. Goto your WAMP/MAMP installation location and open the web directory. On windows, it will be c:/wamp/www directory. On Mac, the path will be /Applications/MAMP/htdocs.

2. Inside the web directory (www or htdocs), create a directory named gcm_chat. This will be the root directory of our project.

3. Inside gcm_chat folder, create the remaining directories as shown in the above image. Create folders named include, libs and v1. Inside libs, create another folder named gcm.

4. Download Slim framework and paste it inside libs folder.

5. Create a file named config.php in include. This file contains the app configuration like database credentials, google API Key and other information.

Replace GOOGLE_API_KEY with your API Key which you obtained in 2nd section. Also keep the correct database credentials.

6. Create a file named db_connect.php inside include folder. This class takes care of database connection.

7. Create another file named db_handler.php inside include folder. This file contains all the necessary functions to interact with database tables.

8. Now let’s start creating the files required for GCM. Create a file named gcm.php inside libs ⇒ gcm folder. This file contains necessary functions required to interact with GCM server. These functions basically makes a CURL request to GCM server by passing required parameters in order to invoke a push notification.

send() – Function sends push notification to a single user

sendToTopic() – Sends push notification to a topic

sendToMultiple() – Send push notification to multiple users

9. Under libs ⇒ gcm, create another file named push.php. This class prepares the required json format that is transferred as a push message to device. If you want to add additional fields to json, you need to add them in this class.

10. At this stage, we have all the necessary functions ready. Let’s start preparing the REST API endpoints for the android app. Create a file named .htaccess inside v1 folder and add below rules.

11. Create index.php inside v1 folder. All the rest api requests will be handled by this file only.

REST API Endpoints

The index.php inside v1 folder providers the below endpoints.

Base URL: http://localhost/gcm_chat/v1

Endpoint

Params

Method

Description

/user/login

name, email

POST

User login or registration

/user/:id

gcm_registration_id

PUT

Updates user’s gcm registration id in database

/chat_rooms



GET

Fetches all chat rooms

/chat_rooms/:id

replace :id with actual chat room id

GET

Fetches single chat room messages

/chat_rooms/:id/message

replace :id with actual chat room id

POST

Posting a message in a chat room

/users/:id/message

replace :id with actual user id

POST

Sending a message to user

/users/message

user_id, to, message

`to` – param is user ids separated by comma (,)

POST

Sending a message to multiple users

/users/send_to_all

user_id, message

POST

Sending a message to all the users subscribed to `global` topic

6. Testing the REST API

Before starting the android project, make sure that the php project is running without any errors. Follow the below steps to test the API.

1. Enable apache mod_rewrite module (link)

2. Enable curl extension. This allows php to make http requests from the backend (link).

3. Install Postman Chrome REST API extension. You can use any other rest api clients too.

The below video takes you through testing the API using Postman.

7. Building the Admin Panel

I created very simple admin panel using PHP, HTML, CSS & jQuery. This admin panel might not be used in production stage, but gives you necessary functions to build a better one.

1. Create a file named demo.php in the root directory of gcm_chat. This class contains function for the admin panel.

2. Create a style sheet named style.css in the root directory.

3. Paste the loader.gif image in the same directory.

4. Create index.php in the root directory. Here I have written necessary php, html and jQuery code to build the admin UI.

5. Finally access the

Show more