Introduction
Google Cloud Messaging for Android (GCM): Helps the developer send data from servers and send data to our application. In other words when we send the request to the server then server returns a response to your application whenever new data is available instead of making a request to the server in a timely fashion.
Introduction to Google cloud messaging PHP and MySQL
This tutorial uses PHP as the server-side programming language and MySQL as the server-side database. The flow is provided by Android Google cloud Messaging.
Step 1
First an Android device sends its device id (sender id) to the GCM server for registration.
Step 2
When the registration is successfull the GCM Server returns a registration id to the Android device.
Step 3
After successfully receiving the registration id the device will send the registration id to our server.
Step 4
Store the registration id into the database.
Registering with Google Cloud Messaging.
Creating MySQL Database
- Open the phpmyadmin panel by going to http://localhost/phpmyadmin and create a database called GCM.
- Creating the database, select the database and execute the following query in the SQL tab to create the gcm_pushnotification_users table.
- CREATE TABLE IF NOT EXISTS `gcm_pushnotification_users ` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `gcm_regid` text,
- `name` varchar(50) NOT NULL,
- `email` varchar(255) NOT NULL,
- `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Creating the PHP Project
Click on the xammp icon in the system tray then select PHP -> PHP Extensions -> Enable php_curl.
- Go to your xammp folder and inside the htdocs folder create a folder called gcm_server_php.
- Create a field called database_config.php. This field holds the database configuration and Google API key.
database_config.php
- <?php
- /**
- * Database config variables
- */
- define("DB_HOST", "localhost");
- define("DB_USER", "root");
- define("DB_PASSWORD", "");
- define("DB_DATABASE", "pushnotification");
- /*
- * Google API Key
- */
- define("GOOGLE_API_KEY", "BIzajiCRLa4LjkiuytloQBcRCYcIVYA45048i9i8zfClqc"); // Place your Google API Key
- ?>
- Create another file called database_connect.php. This file handles database connections and mainly opens and closes the connection.
b_connect.php
- <?php
- class Database_Connect.{
-
- public function connect() {
- require_once database_config.php ';
-
- $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
-
- mysql_select_db(DB_DATABASE);
-
- return $con;
- }
-
- public function close() {
- mysql_close();
- }
- }
- ?>
- Create functions.php. This file contains the function to do database CRUD operations.
functions.php
- <?php
- class Functions {
- private $db;
-
-
- function __construct() {
- include_once './database_connect.php';
-
- $this->db = new Database_Connect();
- $this->db->connect();
- }
-
- function __destruct() {
- }
-
-
-
-
- public function storeUser($name, $email, $gcm_regid) {
-
- $result = mysql_query("INSERT INTO gcm_pushnotification_users (name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");
-
- if ($result) {
-
- $id = mysql_insert_id();
- $result = mysql_query("SELECT * FROM gcm_pushnotification_users WHERE id = $id") or die(mysql_error());
-
- if (mysql_num_rows($result) > 0) {
- return mysql_fetch_array($result);
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
-
-
-
- public function getAllUsers() {
- $result = mysql_query("select * FROM gcm_pushnotification_users ");
- return $result;
- }
- }
- ?>
- Create GCM.php. This file sends push notification requests to the GCM server.
GCM.php
- <?php
- class GCM {
-
-
-
- public function send_notification($registatoin_ids, $message) {
-
- include_once './database_connect.php';
- $url = 'https://android.googleapis.com/gcm/send';
- $fields = array(
- 'registration_ids' => $registatoin_ids,
- 'data' => $message,
- );
- $headers = array(
- 'Authorization: key=' . GOOGLE_API_KEY,
- 'Content-Type: application/json'
- );
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
- $result = curl_exec($ch);
- if ($result === FALSE) {
- die('Curl failed: ' . curl_error($ch));
- }
-
- curl_close($ch);
- echo $result;
- }
- }
- ?>
- Create a register_user.php file. This file is used to receive requests from the Android device and stores the user in the database.
register_user.php
- <?php
- $json = array();
-
-
-
-
- if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"])) {
- $name = $_POST["name"];
- $email = $_POST["email"];
- $gcm_regid = $_POST["regId"];
-
- include_once './functions.php';
- include_once './GCM.php';
- $db = new Functions();
- $gcm = new GCM();
- $res = $db->storeUser($name, $email, $gcm_regid);
- $registatoin_ids = array($gcm_regid);
- $message = array("product" => "shirt");
- $result = $gcm->send_notification($registatoin_ids, $message);
- echo $result;
- } else {
- echo " user details missing";
- }
- ?>
- Create a send_pushnotification_message.php file. This file is used to send push notification to an Android device to send a request to the GCM server.
send_pushnotification_message.php
- <?php
- if (isset($_GET["regId"]) && isset($_GET["message"])) {
- $regId = $_GET["regId"];
- $message = $_GET["message"];
- include_once './GCM.php';
- $gcm = new GCM();
- $registatoin_ids = array($regId);
- $message = array("price" => $message);
- $result = $gcm->send_notification($registatoin_ids, $message);
- echo $result;
- }
- ?>
- Last and finally create a file called index.php and paste the following code into it. 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.
index.php
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- });
- function sendPushNotification(id){
- var data = $('form#'+id).serialize();
- $('form#'+id).unbind('submit');
- $.ajax({
- url: "send_pushnotification_message.php",
- type: 'POST',
- data: data,
- success: function(data, textStatus, xhr) {
- $('.txt_message').val("");
- },
- error: function(xhr, textStatus, errorThrown) {
- }
- });
- return false;
- }
- </script>
- </head>
- <body>
- <?php
- include_once 'functions.php';
- $db = new Functions();
- $users = $db->getAllUsers();
- if ($users != false)
- $no_of_users = mysql_num_rows($users);
- else
- $no_of_users = 0;
- ?>
- <div class="container">
- <h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
- <hr/>
- <ul class="devices">
- <?php
- if ($no_of_users > 0) {
- ?>
- <?php
- while ($row = mysql_fetch_array($users)) {
- ?>
- <li>
- <form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
- <label>Name: </label> <span><?php echo $row["name"] ?></span>
- <div class="clear"></div>
- <label>Email:</label> <span><?php echo $row["email"] ?></span>
- <div class="clear"></div>
- <div class="send_container">
- <textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
- <input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
- <input type="submit" class="send_btn" value="Send" onclick=""/>
- </div>
- </form>
- </li>
- <?php }
- } else { ?>
- <li>
- No Users Registered Yet!
- </li>
- <?php } ?>
- </ul>
- </div>
- </body>
- </html>