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.

apiproject

Switch on the Google Cloud Messaging for Android.

GCMon

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

serverkey

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.

apikey

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 GCMMainActivity.java and paste the following code.

GCMMainActivity.java

package com.androidbegin.gcmtutorial;

import com.google.android.gcm.GCMRegistrar;

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

public class GCMMainActivity extends Activity {

	String TAG = "GCM Tutorial::Activity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);

		// Register Device Button
		Button regbtn = (Button) findViewById(R.id.register);

		regbtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i(TAG, "Registering device");
				// Retrive the sender ID from GCMIntentService.java
				// Sender ID will be registered into GCMRegistrar
				GCMRegistrar.register(GCMMainActivity.this,
						GCMIntentService.SENDER_ID);
			}
		});
	}
}

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.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/regbutton" />

</RelativeLayout>

Output:
GCMMainActivity XML Layout

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

Open your GCMIntentService.java and paste the following code.

GCMIntentService.java

package com.androidbegin.gcmtutorial;

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

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

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() {
		super(SENDER_ID);
	}

	@Override
	protected void onRegistered(Context context, String registrationId) {

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

	@Override
	protected void onUnregistered(Context context, String registrationId) {

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

	@Override
	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,
				PendingIntent.FLAG_UPDATE_CURRENT);
		// Create the notification with a notification builder
		Notification notification = new Notification.Builder(this)
				.setSmallIcon(R.drawable.ic_launcher)
				.setWhen(System.currentTimeMillis())
				.setContentTitle("Android GCM Tutorial")
				.setContentText(message).setContentIntent(pIntent)
				.getNotification();
		// 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
					.getSystemService(Context.POWER_SERVICE);
			final PowerManager.WakeLock mWakelock = pm.newWakeLock(
					PowerManager.FULL_WAKE_LOCK
							| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
			mWakelock.acquire();

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

	}

	@Override
	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 GCMMessageView.java. Select your package named com.androidbegin.gcmtutorial and click Finish.

Open your GCMMessageView.java and paste the following code.

GCMMessageView.java

package com.androidbegin.gcmtutorial;

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

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

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.messageview);

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

		message = i.getStringExtra("message");

		// Locate the TextView
		txtmsg = (TextView) findViewById(R.id.message);

		// Set the data into TextView
		txtmsg.setText(message);
	}
}

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.

messageview.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/msglbl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/msglbl" />

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/msglbl" />

</RelativeLayout>

Output:

GCMMessageView XML Layout

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

strings.xml

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

    <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>

</resources>

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.

AndroidManifest.xml 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.gcmtutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        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="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:allowBackup="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".GCMMainActivity"
            android:launchMode="singleTask" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

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

        <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.androidbegin.gcmtutorial" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

Output:

GCM Client ScreenShot

 

Create a simple PHP server to communicate with GCM.

We have prepared a sample PHP server. Link : https://www.androidbegin.com/tutorial/gcm.html

Output:

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 /]

gcm.html

<html>

<head>
<title>AndroidBegin - Android GCM Tutorial</title>
<link rel="icon" type="image/png" href="https://www.androidbegin.com/wp-content/uploads/2013/04/favicon1.png"/>
</head>

<body>

<a href="http://www.AndroidBegin.com" target="_blank">
<img src="https://www.androidbegin.com/wp-content/uploads/2013/04/Web-Logo.png" alt="AndroidBegin.com"></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="https://code.google.com/apis/console/" target="_blank">Google API</a></br></br>
<img src="https://www.androidbegin.com/wp-content/uploads/2013/05/Google-API-Key.png" 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="https://www.androidbegin.com/wp-content/uploads/2013/05/Device-Registration-ID.png" alt="Device Registration ID" ></br></br>

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

</body>
</html>

gcm_engine.php

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

// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

$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
curl_close($ch);

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 :

APA91bFQCD9Ndd8uVggMhj1usfeWsKIfGyBUWMprpZLGciWrMjS-77bIY24IMQNeEHzjidCcddnDxqYo-UEV03xw6ySmtIgQyzTqhSxhPGAi1maf6KDMAQGuUWc6L5Khze8YK9YrL9I_WD1gl49P3f_9hr08ZAS5Tw

Output:

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 (https://www.androidbegin.com/tutorial/gcm_engine.php)you have given it shows the error Unauthorized Error 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

Nice post.. well explained but I guess this method is now deprecated and we cannot use it now.. I have written an updated tutorial on my blog.. you can refer to it if want to implement push notification in your android app using android studio https://www.simplifiedcoding.net/android-push-notification-using-gcm-tutorial/

Belal Khan

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