Thursday, December 26, 2013

Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

Download Code(download zip, file->download)

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

1. How to enable  the GCM Service

1.1Goto Google APIs Console page and create a new project.
1.2. Create a new Project.
1.3After creating project you can see the Project Number in the following image. Note down the      project id which will be used as SENDER ID in android project. 


1.4. After that, Click on APIs & auth and turn on Google Cloude Messaging for android  .
1.5. After that, Click on Credencials from left pannel.
1.6. You can see the 
OAuth and Public API access.
1.7. Click on  CREATE NEW CLIENT ID 
choose a option Client ID for web application, Click ok.
1.8 After, Click  C REATE NEW KEY
Choose a option Key for browser applications,Click ok.



1.9 API key-This API key will be used when sending requests to GCM server.

2. Creating android project.
Download Code

File->Dowload or press CTRL+S

2.1  import this downloaded source code in eclipse.
2.2. open CommonUtilities.java, and give the parameters, 
SERVER_URL="your php file link";
SENDER_ID="This is your Project Number check it in above image1";
2.3 Debug the app.
2.4 During registration we are posting three parameters, regId, name, email.
regId is the id generated by GCM Server.
2.5 You can check the regId in logcat.

3. PHP code.


<?php

/**
 * The following function will send a GCM notification using curl.
 *
 * @param $apiKey [string] The Browser API key string for your GCM account
 * @param $registrationIdsArray [array] An array of registration ids to send this notification to
 * @param $messageData [array] An named array of data to send as the notification payload
 */

function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);

$ch = curl_init();

curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );

$response = curl_exec($ch);
curl_close($ch);

return $response;
}
// Message to send
$message = "the test message";
$tickerText = "ticker text message";
$contentTitle = "content title";
$contentText = "content body";

$registrationId = 'DEVICE_ID';
$apiKey = "YOUR_BROWSER_API_KEY";

$response = sendNotification(
$apiKey,
array($registrationId),
array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText) );

echo $response;
?>

1 comment: