2014년 8월 12일 화요일

Google Cloud Messaging (GCM) in Android using PHP Server

GCM for android is a service which is basically used to send the data from 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 application server and send 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 message to the GCM connection server.
Life Cycle Flow
GCM life cycle





























  1. 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 application and returns the unique registration id.
  3. The application send 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 need to send, the application server fetches the registration ids from database and send to the GCM connection serer 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 thisofficial documentation to setup 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 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 setup 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 lets 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 following query. [I have created a database named 'GCMDemo' for this example]

?
1
2
3
4
CREATE TABLE  `GCMDemo`.`tblRegistration` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`registration_id` TEXT NOT NULL
) ENGINE = INNODB;
When android application runs for 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.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
$regId = $_GET['regId'];
 
 $con = mysql_connect("localhost","root","");
 if(!$con){
  die('MySQL connection failed'.mysql_error());
 }
 
 $db = mysql_select_db("GCMDemo",$con);
 if(!$db){
  die('Database selection failed'.mysql_error());
 }
 
 $sql = "INSERT INTO tblregistration (registration_id) values ('$regId')";
 
 if(!mysql_query($sql, $con)){
  die('MySQL query failed'.mysql_error());
 }
 
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 servers 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.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<html>
<head>
 <title>GCM Demo application</title>
</head>
<body>
 <?php
  if(isset($_POST['submit'])){
   $con = mysql_connect("localhost", "root","");
   if(!$con){
    die('MySQL connection failed');
   }
 
   $db = mysql_select_db("GCMDemo");
   if(!$db){
    die('Database selection failed');
   }
 
 
   $registatoin_ids = array();
   $sql = "SELECT *FROM tblregistration";
   $result = mysql_query($sql, $con);
   while($row = mysql_fetch_assoc($result)){
    array_push($registatoin_ids, $row['registration_id']);
   }
 
   // Set POST variables
         $url = 'https://android.googleapis.com/gcm/send';
   
    $message = array("Notice" => $_POST['message']);
         $fields = array(
             'registration_ids' => $registatoin_ids,
             'data' => $message,
         );
   
         $headers = array(
             'Authorization: key=AIzaSyCjGBiwaP3jrEZJoqcq7P-tHUrgBrNYU0E',
             'Content-Type: application/json'
         );
         // Open connection
         $ch = curl_init();
   
         // Set the url, number of POST vars, POST data
         curl_setopt($ch, CURLOPT_URL, $url);
   
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   
         // Disabling SSL Certificate support temporarly
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   
         curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
   
         // Execute post
         $result = curl_exec($ch);
         if ($result === FALSE) {
             die('Curl failed: ' . curl_error($ch));
         }
   
         // Close connection
         curl_close($ch);
         echo $result;
  }
 ?>
 <form method="post" action="index.php">
  <label>Insert Message: </label><input type="text" name="message" />
 
  <input type="submit" name="submit" value="Send" />
 </form>
</body>
</html>

댓글 없음:

댓글 쓰기