Android Google Cloud Messaging GCM Using PHP Tutorial

In this tutorial, you will learn how to implement Google Cloud Messaging GCM in your Android application. Google Cloud Messaging GCM is a free service that helps developers to send notifications to their Android application. GCM is a service that handles all aspects of queueing of messages and delivery to the target Android device. We will be creating a Client service that allows you to register your Android Device into GCM server. The GCM Server will generate a registration ID and returns it to your Android Device and by using the registration ID in our PHP web server will allow notification messages to be sent. So lets begin…

Google Cloud Messaging

Go to Google APIs Console and click on Create project.


Switch on the Google Cloud Messaging for Android.


Go to API Access on the sidebar menu and Click on Create new Server key.


Click on Create button to proceed.

GCM Google API Create Server Configuration

Note down your API Key for server apps (with IP locking) shown on below screenshot. This API key will be used when sending requests to the GCM server.


Go to Overview on the sidebar menu and note down your Project Number. This will be your SENDER ID in GCM.

GCM Google API Project Number

Install Android Google Cloud Messaging Library

Open Eclipse and click on Android SDK Manager

Open Android SDK Manager

Locate Google Cloud Messaging for Android Library and click Install.

Install GCM Library 

Locate your downloaded Android GCM Library folder.

Android SDK GCM Library Folder

Copy the gcm.jar file into your project library folder libs

Copy GCM Jar

Create a CLIENT Service

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project GCMTutorial.

Application Name : GCMTutorial

Project Name : GCMTutorial

Package Name : com.androidbegin.gcmtutorial

Then name your activity and paste the following code.

package com.androidbegin.gcmtutorial;


import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class GCMMainActivity extends Activity {

	String TAG = "GCM Tutorial::Activity";

	protected void onCreate(Bundle savedInstanceState) {

		// Register Device Button
		Button regbtn = (Button) findViewById(;

		regbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Log.i(TAG, "Registering device");
				// Retrive the sender ID from
				// Sender ID will be registered into GCMRegistrar

In this activity, we have created a button and on button click will send the SENDER ID to the GCM Server.

Next, create an XML graphical layout for your MainActivity. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file activity_main.xml and paste the following code.


<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >

        android:text="@string/regbutton" />


GCMMainActivity XML Layout

Next, create a GCMIntentService class. Go to File > New > Class and name it Select your package named com.androidbegin.gcmtutorial and click Finish.

Open your and paste the following code.

package com.androidbegin.gcmtutorial;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;


public class GCMIntentService extends GCMBaseIntentService {

	private static final String TAG = "GCM Tutorial::Service";

	// Use your PROJECT ID from Google API into SENDER_ID
	public static final String SENDER_ID = "394127269050";

	public GCMIntentService() {

	protected void onRegistered(Context context, String registrationId) {

		Log.i(TAG, "onRegistered: registrationId=" + registrationId);

	protected void onUnregistered(Context context, String registrationId) {

		Log.i(TAG, "onUnregistered: registrationId=" + registrationId);

	protected void onMessage(Context context, Intent data) {
		String message;
		// Message from PHP server
		message = data.getStringExtra("message");
		// Open a new activity called GCMMessageView
		Intent intent = new Intent(this, GCMMessageView.class);
		// Pass data to the new activity
		intent.putExtra("message", message);
		// Starts the activity on notification click
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
		// Create the notification with a notification builder
		Notification notification = new Notification.Builder(this)
				.setContentTitle("Android GCM Tutorial")
		// Remove the notification on click
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		manager.notify(R.string.app_name, notification);

			// Wake Android Device when notification received
			PowerManager pm = (PowerManager) context
			final PowerManager.WakeLock mWakelock = pm.newWakeLock(
							| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");

			// Timer before putting Android Device to sleep mode.
			Timer timer = new Timer();
			TimerTask task = new TimerTask() {
				public void run() {
			timer.schedule(task, 5000);


	protected void onError(Context arg0, String errorId) {

		Log.e(TAG, "onError: errorId=" + errorId);


In this activity, we will display the received message on a notification and on notification click will pass the notification message to a new activity. Using PowerManager to wake up the device when notification has been received. Insert your Project ID into the SENDER ID string.

Next, create an activity to show the notification message. Go to File > New > Class and name it Select your package named com.androidbegin.gcmtutorial and click Finish.

Open your and paste the following code.

package com.androidbegin.gcmtutorial;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class GCMMessageView extends Activity {
	String message;
	TextView txtmsg;

	public void onCreate(Bundle savedInstanceState) {

		// Retrive the data from
		Intent i = getIntent();

		message = i.getStringExtra("message");

		// Locate the TextView
		txtmsg = (TextView) findViewById(;

		// Set the data into TextView

In this activity, we used an intent to retrieve the data from GCMIntentService class and set it into a TextView.

Next, create an XML graphical layout for GCMMessageView. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file messageview.xml and paste the following code.


<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android=""
    android:layout_height="fill_parent" >

        android:text="@string/msglbl" />

        android:layout_toRightOf="@+id/msglbl" />



GCMMessageView XML Layout

Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code.


<?xml version="1.0" encoding="utf-8"?>

    <string name="app_name">GCM Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="regbutton">Register Device</string>
    <string name="msglbl">"Message : "</string>


In your AndroidManifest.xml, we need to declare an activity and permissions to allow the application to communicate with GCM and our PHP Web Server. You can check the permission guidelines here or just follow the code below.
Open your 
AndroidManifest.xml and paste the following code.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="15" />

    <permission android:name="com.androidbegin.gcmtutorial.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.androidbegin.gcmtutorial.permission.C2D_MESSAGE" />
    <uses-permission android:name="" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

        android:label="@string/app_name" >
            android:launchMode="singleTask" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
        <activity android:name=".GCMMessageView" >

        <service android:name=".GCMIntentService" />

            android:permission="" >
                <action android:name="" />
                <action android:name="" />

                <category android:name="com.androidbegin.gcmtutorial" />



GCM Client ScreenShot


Create a simple PHP server to communicate with GCM.

We have prepared a sample PHP server. Link :


GCM Server Side ScreenShot

To host your own server file, upload both Server Side PHP Source Code to a folder in the root of your server run gcm.html.

Server Side PHP Source Code :

[wpfilebase tag=file id=41 tpl=download-button /]



<title>AndroidBegin - Android GCM Tutorial</title>
<link rel="icon" type="image/png" href=""/>


<a href="" target="_blank">
<img src="" alt=""></br></a></br>

<form action="gcm_engine.php" method="post">
Google API Key (with IP locking) : <INPUT size=70% TYPE="Text" VALUE="" NAME="apiKey"></br>
Get your Google API Key : <a href="" target="_blank">Google API</a></br></br>
<img src="" alt="Google API Key" ></br></br>

Device Registration ID : <INPUT size=70% TYPE = "Text" VALUE="" NAME = "registrationIDs"></br></br>
Tap on the Register button in your GCM Tutorial App and locate Device Registration ID in LogCat</br>
<img src="" alt="Device Registration ID" ></br></br>

Notification Message : <INPUT size=70% TYPE = "Text" VALUE="" NAME = "message"></br></br>
<input type="submit" value="Send Notification"/>



// Message to be sent
$message = $_POST['message'];

// Set POST variables
$url = '';

$fields = array(
                'registration_ids'  => array($_POST['registrationIDs']),
                'data'              => array( "message" => $message ),

$headers = array( 
                    'Authorization: key=' . $_POST['apiKey'],
                    '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 );

curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

// Execute post
$result = curl_exec($ch);

// Close connection

echo $result;


Device Registration ID

To retrieve your Device Registration ID, run your project in Eclipse either on an AVD or Android Device.

Tap on Register Device Button

Tap on Register Device Button

Open your LogCat, type “onRegistered” in the search box.

Eclipse LogCat Device Registration ID

Your Device Registration ID should be something like this :



Android GCM Tutorial ScreenShot

Android GCM Tutorial ScreenShot

Source Code

[purchase_link id=”7926″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

Many thanks for this tutorial it saves my time .but now when i create a new Api key and hit it on your server like the url ( have given it shows the error UnauthorizedError 401 but when i used old api key its working fine why it is happen please help???

monish monish

Android Google Cloud Messaging GCM Using PHP Tutorial

thanks i love u you're my hero

Wetcha Chaima

Android Google Cloud Messaging GCM Using PHP Tutorial

does reg id register on gcm only one time? what i have to do to use the same device

azad chouhan

Android Google Cloud Messaging GCM Using PHP Tutorial

I have problem with the permission you have defined, please elaborate C2D_MESSAGE

Akash kumar

Android Google Cloud Messaging GCM Using PHP Tutorial