Google Cloud Messaging GCM for Android and Push Notifications

23/01/2014

Google cloud messaging (GCM) is an Android platform API provided by Google for sending and receiving push notifications to and from an Android application. This is one of the most important arsenal in an Android developer’s armory.

Let us consider an email android application, it is not efficient to have the application ping the server to check for updates regularly. Mobile devices’ resources should to be used wisely as they are scarce.

gcm

Push and pull are two types of notifications using which messages are transferred. In this android tutorial, I will walk you through setting up push notification setup between an application server and an Android mobile application using Google cloud messaging (GCM) API.

Google Cloud Messaging GCM API

  • We can use GCM as a notification engine. On an event it will send a notification to an android application and vice-versa.
  • A notification is a small piece of information. Using GCM, maximum 4kb of payload can be sent in a notification.
  • For now GCM is a free service – lets use responsibly :-)
  • Android App can receive the message from Google cloud messaging server (GCM) even if the app is not running via Intent broadcasting (our example app will demonstrate this).

Getting Started with GCM

Google-GCM-Notification

This tutorial will have a complete working setup having,

  1. Part A – A custom web application running in an application server. This will connect to Google GCM server and post notification.
  2. Part B – An application running in an Android virtual device (emulator) with an Intent capable of receiving the push notification from the GCM server.

Interacting with Google cloud messaging server (GCM) is not difficult, all we need to do is get couple of configurations perfect and code wise just few number of lines. Overall setup involves IP Address, network proxy/firewall, API key and json objects which sounds like it will be difficult. Get a cup of green tea, start this on a positive note and we will get this done in half an hour.

Ads by Google

Part A – GCM Server Application

Custom web application will connect to Google cloud messaging API url and send notification message to GCM server to push it to the registered Android device.

Prerequisite for Custom Application

  1. Google API Server Key
  2. GCM RegId of the Android Device to communicate via GCM

1. Google API Server Key

  1. Create Google Project: Go to the URL https://cloud.google.com/console/project then create a project and navigate into it.
  2. Enable Google Cloud Messaging For Android: Go to menu “APIs & auth –> APIs” and switch on. Enable-Google-Cloud-Messaging
  3. Create Server Key: Go to Menu “Credentials” and under the section Public API access, click Create New Key. There are different types of keys and here we should use “Sever Key”.Google-API---Server-Key
  4. Edit Allowed IPs: This is to white-list a set of IP addresses as the server key is tied to IP addresses for security. To get your public IP address, in Google search type ‘my public ip address’. Click ‘Edit allowed IPs’ and update your IP.

2. GCM RegId of the Android Device to communicate

RegId uniquely identifies the Android device to communicate. From the Android app (client), we will make the registration and get the RegId from the Google GCM server. Then, we should communicate that RegId to the web application via some defined process.

In this tutorial, let us provide a callback url in the web application and the Android device should invoke that url to share GCM RegId. In the web application, get the RegId and persist it to a file.

GCM Server Application in Java & PHP

The example presented with this tutorial demonstrates minimal features and in future tutorials we will see about advanced capabilities of GCM.

I have written server application for Google cloud messaging in both Java and PHP. You can use either Java or PHP.

GCM Server Application in PHP

In PHP its just a single file web application, just put it in your Apache.

<?php
	//generic php function to send GCM push notification
   function sendPushNotificationToGCM($registatoin_ids, $message) {
		//Google cloud messaging GCM-API url
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message,
        );
		// Google Cloud Messaging GCM API Key
		define("GOOGLE_API_KEY", "AIzaSyDA5dlLInMWVsJEUTIHV0u7maB82MCsZbU"); 		
        $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_VERIFYHOST, 0);	
        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);
        return $result;
    }
?>
<?php
	
	//this block is to post message to GCM on-click
	$pushStatus = "";	
	if(!empty($_GET["push"])) {	
		$gcmRegID  = file_get_contents("GCMRegId.txt");
		$pushMessage = $_POST["message"];	
		if (isset($gcmRegID) && isset($pushMessage)) {		
			$gcmRegIds = array($gcmRegID);
			$message = array("m" => $pushMessage);	
			$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
		}		
	}
	
	//this block is to receive the GCM regId from external (mobile apps)
	if(!empty($_GET["shareRegId"])) {
		$gcmRegID  = $_POST["regId"]; 
		file_put_contents("GCMRegId.txt",$gcmRegID);
		echo "Ok!";
		exit;
	}	
?>
<html>
    <head>
        <title>Google Cloud Messaging (GCM) Server in PHP</title>
    </head>
	<body>
		<h1>Google Cloud Messaging (GCM) Server in PHP</h1>	
		<form method="post" action="gcm.php/?push=1">					                             
			<div>                                
				<textarea rows="2" name="message" cols="23" placeholder="Message to transmit via GCM"></textarea>
			</div>
			<div><input type="submit"  value="Send Push Notification via GCM" /></div>
		</form>
		<p><h3><?php echo $pushStatus; ?></h3></p>        
    </body>
</html>

/gcm/gcm.php is the home page using which we can send a push notification to Google cloud messaging server. /gcm/gcm.php?shareRegId=1 is the callback url and can be invoked from an external application (like the client Android app), which wants to share the GCM Registration id (RegId). On invocation, RegId will be written to a file.

Note: PHP is optional. If you prefer Java, use the following as server.

GCM PHP Server Application Output

GCM-Server Application

GCM Server Application in Java

For this tutorial, I have implemented a HTTP based App Server and have used gcm-server a Helper library for GCM HTTP server operations. It has only two files. Deploy and run using Tomcat. You can download this as a web application project bundle below.

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<%
	String pushStatus = "";
	Object pushStatusObj = request.getAttribute("pushStatus");

	if (pushStatusObj != null) {
		pushStatus = pushStatusObj.toString();
	}
%>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>

	<h1>Google Cloud Messaging (GCM) Server in Java</h1>

	<form action="GCMNotification" method="post">

		<div>
			<textarea rows="2" name="message" cols="23"
				placeholder="Message to transmit via GCM"></textarea>
		</div>
		<div>
			<input type="submit" value="Send Push Notification via GCM" />
		</div>
	</form>
	<p>
		<h3>
			<%=pushStatus%>
		</h3>
	</p>
</body>
</html>

GCMNotification.java

package com.javapapers.java.gcm;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

@WebServlet("/GCMNotification")
public class GCMNotification extends HttpServlet {
	private static final long serialVersionUID = 1L;

	// Put your Google API Server Key here
	private static final String GOOGLE_SERVER_KEY = "AIzaSyDA5dlLInMWVsJEUTIHV0u7maB82MCsZbU";
	static final String MESSAGE_KEY = "message";	

	public GCMNotification() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {


		Result result = null;

		String share = request.getParameter("shareRegId");

		// GCM RedgId of Android device to send push notification
		String regId = "";
		if (share != null && !share.isEmpty()) {
			regId = request.getParameter("regId");
			PrintWriter writer = new PrintWriter("GCMRegId.txt");
			writer.println(regId);
			writer.close();
			request.setAttribute("pushStatus", "GCM RegId Received.");
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);
		} else {

			try {
				BufferedReader br = new BufferedReader(new FileReader(
						"GCMRegId.txt"));
				regId = br.readLine();
				br.close();
				String userMessage = request.getParameter("message");
				Sender sender = new Sender(GOOGLE_SERVER_KEY);
				Message message = new Message.Builder().timeToLive(30)
						.delayWhileIdle(true).addData(MESSAGE_KEY, userMessage).build();
				System.out.println("regId: " + regId);
				result = sender.send(message, regId, 1);
				request.setAttribute("pushStatus", result.toString());
			} catch (IOException ioe) {
				ioe.printStackTrace();
				request.setAttribute("pushStatus",
						"RegId required: " + ioe.toString());
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("pushStatus", e.toString());
			}
			request.getRequestDispatcher("index.jsp")
					.forward(request, response);
		}
	}
}

GCM Java Server Application Output

GCM-Java-Server-Output

Download GCM Java Server Application

Following zip file contains the GCM Java server web application eclipse project.

Part B – GCM Android Client Application

Following Android application is a GCM client and it will,

  • Register with GCM server and receive GCM-RegId.
  • Share the GCM-RegId with the application server.
  • Receive push notification from the GCM server and alert user.

GCM Android App Prerequisite

  1. Google Play Services in SDK
  2. Google APIs
  3. Google Play Services Lib project as Android dependency
  4. Google Project Id
  5. Register/login with a Google account in the AVD

1. Google Play Services in SDK: is required for Google cloud messaging. Check your Android SDK Manager if you have installed it. It is in the bottom below Extras in the SDK Manager as shown below.

Android Google Play Services

2. Google APIs: we need “Google APIs” installed. I am using Android 4.3 with API 18. Check under your Android API version for Google API.

Google APIs

3. Google-Play-Services_Lib project as Android dependency: Import Google play services lib project into workspace (if you use Android Studio skip this step). In Eclipse, Click File > Import, select Android > Existing Android Code into Workspace. This project should be available as part of the android-sdk download. After importing we need to add this project as dependency to the Android application we are going to create.

Import Google Lib

Google-Play-services-Android-Dependency

4. Google Project Id: In the previous part during custom web application, we created a project in the Google console for creating the Google API server key. Google will assign a project Id when doing that. We need to use that Google project Id to register this Android application with the GCM server.

5. Register/login with a Google account in the AVD: We need to create an Android virtual device (emulator) with the Target as Google API. Then start the emulator, go to list of apps, click ‘Settings’, then ‘Add account’ and login with your Google/Gmail id.

Google Settings

Add Google Account in AVD

GCM Android Client Application

The complete project with source is given for download below.

RegisterActivity.java

We have two buttons in this activity, first one is to register this Android application with the Google cloud messaging server and second one is to share the RegId with the web application.

On click of the Register button, we will use the Google Project ID to register with Google cloud messaging server and get the GCM RegId.

Second button is to share this RegId with our custom web application. On click the custom application’s callback url will be invoked. I am running the web application in same machine localhost. But we should not use localhost in the url, since we are connecting from the Android virtual device, as it will loopback to the AVD itself. We should use the our local-ip.

GCM-Android-Client-App

After sharing the Google cloud messaging RegId to web application, we will forward to the next activity.

package com.javapapers.android;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class RegisterActivity extends Activity {

	Button btnGCMRegister;
	Button btnAppShare;
	GoogleCloudMessaging gcm;
	Context context;
	String regId;

	public static final String REG_ID = "regId";
	private static final String APP_VERSION = "appVersion";

	static final String TAG = "Register Activity";

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

		context = getApplicationContext();

		btnGCMRegister = (Button) findViewById(R.id.btnGCMRegister);
		btnGCMRegister.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(regId)) {
					regId = registerGCM();
					Log.d("RegisterActivity", "GCM RegId: " + regId);
				} else {
					Toast.makeText(getApplicationContext(),
							"Already Registered with GCM Server!",
							Toast.LENGTH_LONG).show();
				}
			}
		});

		btnAppShare = (Button) findViewById(R.id.btnAppShare);
		btnAppShare.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(regId)) {
					Toast.makeText(getApplicationContext(), "RegId is empty!",
							Toast.LENGTH_LONG).show();
				} else {
					Intent i = new Intent(getApplicationContext(),
							MainActivity.class);
					i.putExtra("regId", regId);
					Log.d("RegisterActivity",
							"onClick of Share: Before starting main activity.");
					startActivity(i);
					finish();
					Log.d("RegisterActivity", "onClick of Share: After finish.");
				}
			}
		});
	}

	public String registerGCM() {

		gcm = GoogleCloudMessaging.getInstance(this);
		regId = getRegistrationId(context);

		if (TextUtils.isEmpty(regId)) {

			registerInBackground();

			Log.d("RegisterActivity",
					"registerGCM - successfully registered with GCM server - regId: "
							+ regId);
		} else {
			Toast.makeText(getApplicationContext(),
					"RegId already available. RegId: " + regId,
					Toast.LENGTH_LONG).show();
		}
		return regId;
	}

	private String getRegistrationId(Context context) {
		final SharedPreferences prefs = getSharedPreferences(
				MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
		String registrationId = prefs.getString(REG_ID, "");
		if (registrationId.isEmpty()) {
			Log.i(TAG, "Registration not found.");
			return "";
		}
		int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i(TAG, "App version changed.");
			return "";
		}
		return registrationId;
	}

	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			Log.d("RegisterActivity",
					"I never expected this! Going down, going down!" + e);
			throw new RuntimeException(e);
		}
	}

	private void registerInBackground() {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcm == null) {
						gcm = GoogleCloudMessaging.getInstance(context);
					}
					regId = gcm.register(Config.GOOGLE_PROJECT_ID);
					Log.d("RegisterActivity", "registerInBackground - regId: "
							+ regId);
					msg = "Device registered, registration ID=" + regId;

					storeRegistrationId(context, regId);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
					Log.d("RegisterActivity", "Error: " + msg);
				}
				Log.d("RegisterActivity", "AsyncTask completed: " + msg);
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				Toast.makeText(getApplicationContext(),
						"Registered with GCM Server." + msg, Toast.LENGTH_LONG)
						.show();
			}
		}.execute(null, null, null);
	}

	private void storeRegistrationId(Context context, String regId) {
		final SharedPreferences prefs = getSharedPreferences(
				MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
		int appVersion = getAppVersion(context);
		Log.i(TAG, "Saving regId on app version " + appVersion);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(REG_ID, regId);
		editor.putInt(APP_VERSION, appVersion);
		editor.commit();
	}
}

MainActivity.java

GCM-RegId-Shared

package com.javapapers.android;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity {

	ShareExternalServer appUtil;
	String regId;
	AsyncTask<Void, Void, String> shareRegidTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		appUtil = new ShareExternalServer();

		regId = getIntent().getStringExtra("regId");
		Log.d("MainActivity", "regId: " + regId);

		final Context context = this;
		shareRegidTask = new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String result = appUtil.shareRegIdWithAppServer(context, regId);
				return result;
			}

			@Override
			protected void onPostExecute(String result) {
				shareRegidTask = null;
				Toast.makeText(getApplicationContext(), result,
						Toast.LENGTH_LONG).show();
			}

		};
		shareRegidTask.execute(null, null, null);
	}

}

GcmBroadcastReceiver.java

package com.javapapers.android;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		ComponentName comp = new ComponentName(context.getPackageName(),
				GCMNotificationIntentService.class.getName());
		startWakefulService(context, (intent.setComponent(comp)));
		setResultCode(Activity.RESULT_OK);
	}
}

GCMNotificationIntentService.java

This Android intent service extends the IntentService.

package com.javapapers.android;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GCMNotificationIntentService extends IntentService {

	public static final int NOTIFICATION_ID = 1;
	private NotificationManager mNotificationManager;
	NotificationCompat.Builder builder;

	public GCMNotificationIntentService() {
		super("GcmIntentService");
	}

	public static final String TAG = "GCMNotificationIntentService";

	@Override
	protected void onHandleIntent(Intent intent) {
		Bundle extras = intent.getExtras();
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

		String messageType = gcm.getMessageType(intent);

		if (!extras.isEmpty()) {
			if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
					.equals(messageType)) {
				sendNotification("Send error: " + extras.toString());
			} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
					.equals(messageType)) {
				sendNotification("Deleted messages on server: "
						+ extras.toString());
			} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
					.equals(messageType)) {

				for (int i = 0; i < 3; i++) {
					Log.i(TAG,
							"Working... " + (i + 1) + "/5 @ "
									+ SystemClock.elapsedRealtime());
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
					}

				}
				Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

				sendNotification("Message Received from Google GCM Server: "
						+ extras.get(Config.MESSAGE_KEY));
				Log.i(TAG, "Received: " + extras.toString());
			}
		}
		GcmBroadcastReceiver.completeWakefulIntent(intent);
	}

	private void sendNotification(String msg) {
		Log.d(TAG, "Preparing to send notification...: " + msg);
		mNotificationManager = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				new Intent(this, MainActivity.class), 0);

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.gcm_cloud)
				.setContentTitle("GCM Notification")
				.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
				.setContentText(msg);

		mBuilder.setContentIntent(contentIntent);
		mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
		Log.d(TAG, "Notification sent successfully.");
	}
}

Config.java

package com.javapapers.android;

public interface Config {

	// used to share GCM regId with application server - using php app server
	static final String APP_SERVER_URL = "http://192.168.1.17/gcm/gcm.php?shareRegId=1";

	// GCM server using java
	// static final String APP_SERVER_URL =
	// "http://192.168.1.17:8080/GCM-App-Server/GCMNotification?shareRegId=1";

	// Google Project Number
	static final String GOOGLE_PROJECT_ID = "512218038480";
	static final String MESSAGE_KEY = "message";

}

ShareExternalServer.java

package com.javapapers.android;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.content.Context;
import android.util.Log;

public class ShareExternalServer {

	public String shareRegIdWithAppServer(final Context context,
			final String regId) {

		String result = "";
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("regId", regId);
		try {
			URL serverUrl = null;
			try {
				serverUrl = new URL(Config.APP_SERVER_URL);
			} catch (MalformedURLException e) {
				Log.e("AppUtil", "URL Connection Error: "
						+ Config.APP_SERVER_URL, e);
				result = "Invalid URL: " + Config.APP_SERVER_URL;
			}

			StringBuilder postBody = new StringBuilder();
			Iterator<Entry<String, String>> iterator = paramsMap.entrySet()
					.iterator();

			while (iterator.hasNext()) {
				Entry<String, String> param = iterator.next();
				postBody.append(param.getKey()).append('=')
						.append(param.getValue());
				if (iterator.hasNext()) {
					postBody.append('&');
				}
			}
			String body = postBody.toString();
			byte[] bytes = body.getBytes();
			HttpURLConnection httpCon = null;
			try {
				httpCon = (HttpURLConnection) serverUrl.openConnection();
				httpCon.setDoOutput(true);
				httpCon.setUseCaches(false);
				httpCon.setFixedLengthStreamingMode(bytes.length);
				httpCon.setRequestMethod("POST");
				httpCon.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded;charset=UTF-8");
				OutputStream out = httpCon.getOutputStream();
				out.write(bytes);
				out.close();

				int status = httpCon.getResponseCode();
				if (status == 200) {
					result = "RegId shared with Application Server. RegId: "
							+ regId;
				} else {
					result = "Post Failure." + " Status: " + status;
				}
			} finally {
				if (httpCon != null) {
					httpCon.disconnect();
				}
			}

		} catch (IOException e) {
			result = "Post Failure. Error in sharing with App Server.";
			Log.e("AppUtil", "Error in sharing with App Server: " + e);
		}
		return result;
	}
}

AndroidManifest.xml

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <permission
        android:name="com.javapapers.android.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.javapapers.android.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="16" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <activity
            android:name=".RegisterActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity
            android:name="com.javapapers.android.MainActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name" >
        </activity>

        <receiver
            android:name=".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.javapapers.android" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMNotificationIntentService" />
    </application>

</manifest>

Android GCM Client Dependencies

Android GCM Client Dependencies

On sending a successful push notification to Google cloud messaging server:

GCM Push Notification Success

On successful receive of notification from GCM:

GCM-Broadcast-Notification

GCM-Push-Notification-Received

Download GCM Android Client Application

Following zip file contains the Android application eclipse project.

Checklist – Things that may go wrong:

  1. Check if you have created the ‘Server Key’ there are different types of keys available in Google credentials.
  2. Check if you are using your public-IP address instead of local-ip, in the ‘Edit Allowed IPs’ in Google credentials.
  3. Check if you are using the local-ip address instead of ‘localhost’ in connecting with the custom web application in the Android App.
  4. Check if you have given the right Google project id in the Android app.
  5. Check if you have added permission for Internet in Android manifest file.
  6. Check if you have added/logged in using your Google account in AVD settings.
  7. Google-play-service-Lib project may not be added in the Android app project dependency.
  8. If the GCM registration_id is wrong, following is the response sent from Google cloud messaging server to our web application.
    {"multicast_id":7048577678678825845,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
  9. Connection to GCM server is ok and the server has responded. If the Google API key is wrong or the IP address of the server machine is not white listed at Google GCM server. Then we will get,
    Unauthorized Error 401
  10. In this example, passed data must be a JSON array, check if the arguments are being sent in the expected format. We may get error,
    Field "data" must be a JSON array:
This Android tutorial was posted on 23/01/2014.
Ads by Google

141 comments on “Google Cloud Messaging GCM for Android and Push Notifications

  1. Hey Joe, looks like this is one of your longest tutorial.

    • Yes Priya. People are finding it difficult to setup a good GCM environment. So I have tried give a detailed step by step instructions to make it easier.

      If you spend some time and follow the tutorial, I am sure you will make this GCM thing work.

  2. Nice one. Will try this. easy to understand. Keep going

    • Sure Samraj.

      If you face any issues post in comment, lets fix it.

    • what is the way to use in miobile……plz rpl

  3. Really, A Very Useful Example. Keep it up sir. :)

  4. Great tutorial, but i have one little problem, whenever I click on send message button from web and when the internet is off in the device notification won’t come, but as soon as I turn on internet connectivity the previous message what I have sent when the connectivity was off is not coming, please help me out. Thanks.

  5. What if the client does not have a google account registered ?

    • Its required only if we are using Android Virtual Device (Emulator) to run the Client (GCM Android App).

      If its a real mobile device, then its not required.

  6. thank you for this great tutorial. but how about if I want to send data from mobile to server and that data will be forwarded to another mobile?

    • Kyle,
      Using Google GCM, two-way communication is possible. Two-way means, application-server to mobile via GCM-server and vice versa. In this tutorial, I have covered the application-server to mobile via GCM-server part only. For the other, I am planning to write another tutorial.

      It is possible to send broadcast to multiple mobiles from an application via GCM.

      • Thanks! looking forward for the other tutorial =) ..

  7. hi.. i have tried every step on the above tutorial and run the app on a real mobile not on an emulator, but every time i send message on server to mobile i get this {“multicast_id”:4968672681542797991,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1391001084908870%28678a6af9fd7ecd"}]}

    but i was not able to receive any notification on my mobile. help please

    • Carlos,

      I didn’t run this example program in mobile yet. But it should not have any issues. Let me check this in a day and get back.

  8. Hello thanks for this tutorial. i have a problem thou when i connect to the webservice in php the txt file is always empty. In the android side i saw that in lolcat the regid is empty also. Do you why this is hapenning? i just downloaded your project and change the senderId,google api key,and urls… In android side it says it shared succsessfully to server and it does but the regId is an empty string

    • Granadillo,

      Are you running in a real device or AVD?

      Do you see any exceptions in the log?

      Log.d("RegisterActivity", "GCM RegId: " + regId);

      In Android side, this line should print the GCM-RegId in log. Just for debugging purpose, copy that Reg-Id and paste it in the server-side text file which is now empty even after sharing.

      Then check what happens…

      • im running on a real device not on emulator and yes.. i already got the registration id for my device and tried to paste the regId on the text file and tried to send message in server ang got this

        {“multicast_id”:5047711451194792207,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1391063065340546%28678a6af9fd7ecd"}]}

        and i did not receive any notification on the device

        • hi i am not getting regId can you please help me..

          • Guys,

            I have made major changes now to the tutorial sample application / code. Previously I had used some deprecated API instead of GoogleCloudMessaging and also improved the error handling. Please check the latest and comment if you have any issues.

  9. I have used GoogleCloudMessaging object to register my app instead of GCMRegistrar object. Messages are sent from my server to gcm server. But from gcm server to my device (android app), not a single message/notification is received. I also tested points from checklist. Can you please help me to find out what i’m missing ?

    • Are you getting any errors. Carefully parse the application log. For sure there will be some traces.

      Previously I had used some deprecated API instead of GoogleCloudMessaging and also now improved the error handling. Please check the latest and comment if you have any issues.

  10. is your server url correct??you have used your ip address in there is it the right way to do it

    • Yes Mr. Ravooru. server url is used on application server is correct and i also have verified that message is sent to gcm server. Only thing is notifications are not received on my android device.

      • It was Network port problem. Firewall was blocking network ports 5228,29,30. 5228 is default port used by GCM. I unblocked that port to fix the issue. Thanks a lot you for the help

  11. Hi Joe:

    Not sure if this is a bad question but wanted to know can an android app be both a GCM server and GCM client. This would remove the need to have server implementation and would allow virtual P2P (App-to-App) communication.

    If this is not possible, then what could be the possible ways to achieve P2P communication without the need of hosting a server?

  12. what are the use of GCM from other normal servers

    • sorry, what are the uses of GCM from other Normal servers implementations like WAMP,LAMP

  13. Hi Joe, this is a fantastic tutorial. But I am having an issue. similar to this one.
    I have an app which shows map and button on it. I want to notify the user’s current location to another mobile, when I click on that button. (just like facebook chat. when One friend sends message to second friend, second friend gets notified)
    How do I do that? Please help!

    • Even im looking for the same exact concept of yours, if u got any idea, plz let me know, my email id is amuuudha@gmail.com. thanks in advance.

    • 1. You need to build a web application (GCM server).
      2. Android Application that will POST GCM Notification message to above Server.
      3. Now server will broadcast to all other Android apps those should receive the location (which will have broadcast intent receiver). – is the GCM Android client given in above example.

      • Hi Joe, Can you please post tutorial for that?

  14. Hi Joe,
    I urgently need to learn push notification for Android and need to create an interface which can push messages. This is my project need.

    Please let me know how to start from the beginning .using GCM.

    • Please go through the above tutorial. You may need one hour to understand and execute.

      Downloading the projects and running it can be done in minutes.

  15. hi joe,

    i tried running the android app on a real tablet. It does not return a reg-id string. Please note that have not set up the server (App server) side code yet and just testing communication flow between my app and GCS (Google Cloud Server).

    • i am trying to run the app using web apps t(servlet)
      but its troom wing exception GCMRegId.txt not found,from where configure the text file GCMRegId.txt

  16. hi joe,

    after following your tutorial line by line, everything works correctly except that i do not get a reg id. Currently, i am only implemented the android app gcs server but not the entire app gcs server app server. Could that be a reason?

    • Yes, you need the GCM Server application to send the notification to client app.

  17. Hi Joe,

    I have set all correctly as per the document, everything is fine. But, the regId is returning empty after registering. Dono, where am going wrong. Please help on this issue..

    Regards
    Ashwin Ganesh.R

    • I have made major changes now to the tutorial sample application / code. Previously I had used some deprecated API instead of GoogleCloudMessaging and also improved the error handling. Please check the latest and comment if you have any issues.

  18. You are saying us to add google play services library and using the old gcm lib in code. GCMRegistrar is not even available on google play services. What a stupid.

    • Sorry Partha, that’s my mistake.

      I was trying too many things and posted some wrong version.

      Please check the latest now and comment if you have any issues.

  19. Hi Joe,

    You haven’t started service.If the application is not running i.e exited then how notification is received.

  20. 02-23 15:29:50.677: E/Trace(1596): error opening trace file: No such file or directory (2)
    02-23 15:29:56.367: E/ActivityThread(1596): Activity com.javapapers.android.RegisterActivity has leaked IntentReceiver com.google.android.gcm.GCMBroadcastReceiver@40fb5938 that was originally registered here. Are you missing a call to unregisterReceiver()?
    02-23 15:29:56.367: E/ActivityThread(1596): android.app.IntentReceiverLeaked: Activity com.javapapers.android.RegisterActivity has leaked IntentReceiver com.google.android.gcm.GCMBroadcastReceiver@40fb5938 that was originally registered here. Are you missing a call to unregisterReceiver()?
    02-23 15:29:56.367: E/ActivityThread(1596): at android.app.LoadedApk$ReceiverDispatcher.(LoadedApk.java:792)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:593)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1111)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.app.ContextImpl.registerReceiver(ContextImpl.java:1098)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:372)
    02-23 15:29:56.367: E/ActivityThread(1596): at com.google.android.gcm.GCMRegistrar.setRetryBroadcastReceiver(GCMRegistrar.java:277)
    02-23 15:29:56.367: E/ActivityThread(1596): at com.google.android.gcm.GCMRegistrar.register(GCMRegistrar.java:203)
    02-23 15:29:56.367: E/ActivityThread(1596): at com.javapapers.android.RegisterActivity.registerGCM(RegisterActivity.java:71)
    02-23 15:29:56.367: E/ActivityThread(1596): at com.javapapers.android.RegisterActivity$1.onClick(RegisterActivity.java:40)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.view.View.performClick(View.java:4084)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.view.View$PerformClick.run(View.java:16966)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.os.Handler.handleCallback(Handler.java:615)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.os.Handler.dispatchMessage(Handler.java:92)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.os.Looper.loop(Looper.java:137)
    02-23 15:29:56.367: E/ActivityThread(1596): at android.app.ActivityThread.main(ActivityThread.java:4745)
    02-23 15:29:56.367: E/ActivityThread(1596): at java.lang.reflect.Method.invokeNative(Native Method)
    02-23 15:29:56.367: E/ActivityThread(1596): at java.lang.reflect.Method.invoke(Method.java:511)
    02-23 15:29:56.367: E/ActivityThread(1596): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    02-23 15:29:56.367: E/ActivityThread(1596): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    02-23 15:29:56.367: E/ActivityThread(1596): at dalvik.system.NativeStart.main(Native Method)

  21. {“multicast_id”:8162060780822142071,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{"error":"InvalidRegistration"}]}

    getting this error using php. have done the following 2 things in yr code:
    1. Put my API key in the gcm.php file instead of what was there.
    2. Created a file called GCMRegId.txt with my project id in it..

    Please help! Appreciate it!

    • Gregor,

      You need not create GCMRegId.txt manually. When you run the Android App (client), it will invoke the callback url in the server-side. Then the server application will create the text file with device RegId in it.

    • Can you please elaborate the issue. Are you not getting in the device side from the GCM-cloud server? or in the application server side?

      Post errors/trace if any.

  22. Hi Joe,
    I am getting the reg_id but when i am trying to post my reg_id to my application server it is giving POST failure status:400. What am i doing wrong?

    • Nilesh,

      The URL you are using to post to the GCM-server is malformed. Check if the URL is right.

      • Hi Joe,
        I am using software to make my localhost public and i am now able to share reg_id with the server. But when i send a message, I receive GCM notification stating ‘Message Received from Google GCM Server:null’.
        What could i be doing wrong?

        • ‘Message Received from Google GCM Server:null’ – this is shown in the Android App UI (Intent).

          Can you check the Android log for error messages?

          • Hi Joe,

            I have the same problem. I tried to send “asdsdad” from the form, and it shown {“multicast_id”:7879656234367994045,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1394166356544304%31e4cc17f9fd7ecd"}]}

            Then, a few seconds later, I got a GCM Notification: “Message Received from Google GCM Server:null”. When I click on that, it shown “RegId shared with Application server. RegId:Null”

            I tried to send several times, and until it shown error in the php side “{“multicast_id”:5824038452200434731,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{"error":"InvalidRegistration"}]}”
            I checked the file GCMRegId.txt, and I found that its content was deleted.

            In the LogCat, it shown:03-06 23:41:40.427: I/GCMNotificationIntentService(925): Received: Bundle[{m=asdsdad, from=1033922223757, android.support.content.wakelockid=9, collapse_key=do_not_collapse}]
            And I can see the true message “asdsdad” in the log.

          • It is working now, in your code one change is required in Config.java.
            String MESSAGE_KEY = “message”; it should be String MESSAGE_KEY = “m”; That fixed the issue for me.

          • Tony,

            Sound like music, when you say “Its working”.

            The message key should be same as in the server-side and Android client-side. With respect to GCM it has got nothing to do. :-)

  23. hi i want to implement gcm for my android appln.
    i want to use device to device messaging ….
    means one android device can send directly message to other android device … without using third party server….
    is it possible…
    if yes plse help me…..
    i have all android device id….

    • Paramvir,
      I am working on that device to device communication tutorial. Will post it in a week.

  24. Pingback: Android Multicast Notification using Google Cloud Messaging (GCM)

  25. Hi Joe,

    I successfully get the following message from my server
    {“multicast_id”:5034742404093744888,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1394109528288191%31e4cc17f9fd7ecd"}]}

    But i didn’t receive any notifications on my device. When i try to send notification from my server, my app was exited on device at the same time.

    Kindly do some needful.

    • Satheesh,

      In the Android app side, check for log messages. Once you receive the message bundle it will print log message stating that it has received message. When your app crashes it will also leave trace in log. Share all those here and lets find out.

  26. Hi,

    Thanks for the best GCM tutorial out there! I am using a server on the web and am getting an Unauthorized message when I try to send a message through the php. I’ve checked both the API key and my IP is listed in Google, I can’t seem to find the problem. Could it have something to do with that my server is not related to my ip, or do you have any ideas?

    Thanks,
    Jake

  27. Hi Joe,

    I have done this tutorial, but if I touch the notification from the status bar, the regId in GCMRegId.txt is deleted, and the content of that file is replaced by “null”, and I have to click on “register…” and “share…” buttons to make work again. And another question is how to make sound when the notification comes, since if the phone is in screen timeout state, the notification comes silently and does not turn the phone screen on. How can I fix those things? Thank you Joe!

  28. Guyz.. if you are doing everything perfectly and not getting notifications on your device..though
    you get MessageId from GCM server..
    Your incoming packets to device must be blocked by your forewall… Try using real device with its own internet connection and not the one using WiFi.
    Or try to run the same project at your home with a personal WiFi connection.. (y)

  29. Hi Joe,

    regId: APA9……….
    java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
    at java.net.Socket.connect(Socket.java:579)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:607)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
    at sun.net.www.protocol.https.HttpsClient.(HttpsClient.java:278)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:335)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1087)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
    at com.google.android.gcm.server.Sender.post(Sender.java:476)
    at com.google.android.gcm.server.Sender.post(Sender.java:455)
    at com.google.android.gcm.server.Sender.sendNoRetry(Sender.java:170)
    at com.google.android.gcm.server.Sender.send(Sender.java:121)
    at com.javapapers.java.gcm.GCMNotification.doPost(GCMNotification.java:66)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

    Can you help me?

  30. Sir,i am getting an exception in ShareExternalServer class….i.e IOException is occuring when i am trying to register the app with the web server…what could be the problem ?

    • Check the IP address of the GCM application server and see if you can reach it.

  31. can i send image one device to another device in android using wifi or dtn

  32. Hi , it’s a good tutorial , hmm , is there any other way to push a notification in android without using google cloud messaging(GCM)?. i want to create an app that will notify all user’s in android and iOS, but i don’t know where to start. Anyway TIA.

  33. Sir, thanks for the tutorial..I have a problem, My client side indicate that regid successfully send the to webserver. But icant receive regid in my webserver(it is in java).what are the possible chances for this pblm? Can u please me!!

    • At the end of the tutorial, I have given a checklist, go through that and cross check with your GCM setup.

  34. Hello

    I am facing the following issue.

    “Registered with GCM Server.Error:
    SERVICE_NOT_AVAILABLE”

    It looks like I am not able to connect eith GCM service correctly. Please provide me the solution.

    • I am facing the same issue. I am testing on a real phone without a sim card. Is this the reason?

    • Check the Internet connectivity in your device. You need Internet to connect to the Google GCM server :-)

      • Have got internet on emulator..i’ve checked that still it shows
        “Registered with GCM Server.Error:
        SERVICE_NOT_AVAILABLE”

  35. hi sir i need your help.

    android app you provide unfortunatly stop working in real device. i dont understand where the error is.

    its a mendatory for my project.. please help me.

    thank u.
    vasantha rambabu

    • Evn am having same problem.. Did u solve it?

    • This example Android app is working for me and for many others too.

      There might be something missing in your configuration. Need more detail to help you.

      Can you check the log and post the detail like exception trace.

  36. android app working fine but app server in php doent work properly…
    could you please help in this topic? please send correct solution to my mail id
    vasantharams@gmail.com

    • See, the same thing again. Can you please be specific about the error you get.

  37. hello joe..i am getting notifications..but i have 2 problems remaining.

    1.Notification can show what i typed in php using MESSAGE_KEY variable.
    but application is not understanding MESSAGE_KEY

    2.Tell me how to update PHP file for storing multiple reg id s ??

    kindly help me urgently coz i have to show my project at 31st of march…

      • 1. MESSAGE_KEY=”m” . and i see real value of m(strings i typed in php)only in notification.my activity shows ‘m’ as value of MESSAGE_KEY.

        for 2. i have uploaded php to 000webhost which is free it doesnt support jsp.so plssss.. tell me what to do with php.please tell me how to edit that php for storing reg ids in regid.txt

        plus 3. GCM forgets my device in a minute or 2.and i have to re-register after nearly 5 minutes..

        4. can i use GCM for sending alerts to more than a million devices???? tell me when u will be online..we ll sort this out.because i have to show some progress in my project on 29th of march.
        thank u joe..u r like a boon to newbies. :)

        • Using a free-hosting webhost to learn a new technology will not workout. They may not give you enough privilege and it will be always behind a strong firewall. Debugging will be an issue always.

          Why not try in your local machine. For the Google GCM server, if you are a Java guy, use the same sample I have given and it should work with only Android server key and project id change.

          If you wish to work based on PHP, you my try XAMPP to create a PHP setup in local and work based on it. This setup can be done in minutes.

          Please throw away the Internet free-hosting stuff for these kind of tutorial based learning. As I have stated in my tutorial above, Google GCM project is all about setting up the environment and configurations. Code is very simple. So, get your local environment fixed first. Once things are running and then you can see about hosting it live :-)

          • thanx joe…i get the notifications..everything is fine.but i need your guidance for next step.which is ..
            1.i want to show what i typed in server in an activity.

            for example if i send “hii” from server ..for php $message=hiii
            and in config.java file MESSAGE_KEY=”message”
            the problem is “hii” is only seen in notifications.when i try to pass that string in an activity it sees “hii” as “message” and as a result i see “message” as value of MESSAGE_KEY

            i want to show in the activity what i typed in server after clicking the notification..

            as u suggested, for multiple devices i will try java in my localhost but as i get notifications properly, i dont think firewalls are an issue .so adding multiple reg Ids to php array seems simple to me :)

          • hey joe…i did it.. all previous questions are solved ..
            i didnt know about the ‘msg’ variable in notification..
            i want an activity containing various images which is opened after respected alert is clicked.. how to..?

          • @nick halden,

            So happy that all the errors are solved and you are getting notification. To display images according to notification message requires a new tutorial. Let me try to write a new tutorial for that in the near future.

          • so happy that you are writing a tutorial for that soon…if possible plssssss upload the tutorial this week..or tell me when will u upload that?i am working for an application which will help finding missing people,criminals.. :)

  38. I am getting this on server:
    {“multicast_id”:4739377494510639849,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1395843739625862%31e4cc17f9fd7ecd"}]}

    But on an emulator wen i send msg 4m server it stops working. Evn on real device its happening the same. Also am getting the same RegID on emulator and real device.. Plz help.. I need it urgently

    • Please avoid sms language, its difficult to read.

      So the message is successfully sent by the GCM-server application and the GCM-client (Android app) is not receiving it. Is my understanding right?

      If so, when the Android app stops working, can you watch the log and report what you get?

      • Sorry for the sms language. Here is the content of logcat.

        03-26 21:55:59.980: D/RegisterActivity(10095): GCM RegId: APA91bHtGqrw3KDecjwpG1l2urQRQDy1x4WAV-fkys80kFLrCHnr5iEUh3e9lwyxtWqwfdML8g_WsCUxgjtH0AodvNsJEI6HkwIuBF19edzttT_rOC7NcZeVIoRnEiu9oawJBGF0aevB2mjykof2IbG7TCCmFtCODw
        03-26 21:56:01.520: D/RegisterActivity(10095): onClick of Share: Before starting main activity.
        03-26 21:56:01.530: D/RegisterActivity(10095): onClick of Share: After finish.
        03-26 21:56:01.540: D/MainActivity(10095): regId: APA91bHtGqrw3KDecjwpG1l2urQRQDy1x4WAV-fkys80kFLrCHnr5iEUh3e9lwyxtWqwfdML8g_WsCUxgjtH0AodvNsJEI6HkwIuBF19edzttT_rOC7NcZeVIoRnEiu9oawJBGF0aevB2mjykof2IbG7TCCmFtCODw
        03-26 21:56:14.890: W/dalvikvm(10095): Unable to resolve superclass of Lcom/javapapers/android/GcmBroadcastReceiver; (112)
        03-26 21:56:14.890: W/dalvikvm(10095): Link of class ‘Lcom/javapapers/android/GcmBroadcastReceiver;’ failed
        03-26 21:56:14.890: D/AndroidRuntime(10095): Shutting down VM
        03-26 21:56:14.890: W/dalvikvm(10095): threadid=1: thread exiting with uncaught exception (group=0xb2c54180)
        03-26 21:56:14.890: I/Process(10095): Sending signal. PID: 10095 SIG: 9
        03-26 21:56:14.890: D/AndroidRuntime(10095): procName from cmdline: com.javapapers.android
        03-26 21:56:14.890: E/AndroidRuntime(10095): in writeCrashedAppName, pkgName :com.javapapers.android
        03-26 21:56:14.890: D/AndroidRuntime(10095): file written successfully with content: com.javapapers.android StringBuffer : ;com.javapapers.android
        03-26 21:56:14.890: E/AndroidRuntime(10095): FATAL EXCEPTION: main
        03-26 21:56:14.890: E/AndroidRuntime(10095): java.lang.RuntimeException: Unable to instantiate receiver com.javapapers.android.GcmBroadcastReceiver: java.lang.ClassNotFoundException: com.javapapers.android.GcmBroadcastReceiver
        03-26 21:56:14.890: E/AndroidRuntime(10095): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2100)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1197)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at android.os.Handler.dispatchMessage(Handler.java:99)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at android.os.Looper.loop(Looper.java:137)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at android.app.ActivityThread.main(ActivityThread.java:4424)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at java.lang.reflect.Method.invokeNative(Native Method)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at java.lang.reflect.Method.invoke(Method.java:511)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at dalvik.system.NativeStart.main(Native Method)
        03-26 21:56:14.890: E/AndroidRuntime(10095): Caused by: java.lang.ClassNotFoundException: com.javapapers.android.GcmBroadcastReceiver
        03-26 21:56:14.890: E/AndroidRuntime(10095): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
        03-26 21:56:14.890: E/AndroidRuntime(10095): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2095)
        03-26 21:56:14.890: E/AndroidRuntime(10095): … 10 more

        • whenever I send message from server the app crashes and i get these errors

          • com.javapapers.android.GcmBroadcastReceiver: java.lang.ClassNotFoundException:

            i guess ..there is some mistake in importing library services.

        • The error you have is “Unable to resolve superclass of Lcom/javapapers/android/GcmBroadcastReceiver”

          The referred superclass is, WakefulBroadcastReceiver – it belongs to the jar

          C:\Program Files\Android\android-sdk\extras\android\support\v4\android-support-v4.jar

          - add this to your dependency.

          • Hi joe, I already tried this. It didn’t help. I am still having the same problem. The app just crashes.

          • here is the logcat

            03-27 22:27:34.793: D/RegisterActivity(2633): GCM RegId: APA91bHtGqrw3KDecjwpG1l2urQRQDy1x4WAV-fkys80kFLrCHnr5iEUh3e9lwyxtWqwfdML8g_WsCUxgjtH0AodvNsJEI6HkwIuBF19edzttT_rOC7NcZeVIoRnEiu9oawJBGF0aevB2mjykof2IbG7TCCmFtCODw
            03-27 22:27:40.403: D/RegisterActivity(2633): onClick of Share: Before starting main activity.
            03-27 22:27:40.423: D/RegisterActivity(2633): onClick of Share: After finish.
            03-27 22:27:40.433: D/MainActivity(2633): regId: APA91bHtGqrw3KDecjwpG1l2urQRQDy1x4WAV-fkys80kFLrCHnr5iEUh3e9lwyxtWqwfdML8g_WsCUxgjtH0AodvNsJEI6HkwIuBF19edzttT_rOC7NcZeVIoRnEiu9oawJBGF0aevB2mjykof2IbG7TCCmFtCODw
            03-27 22:28:02.323: D/RegisterActivity(2633): GCM RegId: APA91bHtGqrw3KDecjwpG1l2urQRQDy1x4WAV-fkys80kFLrCHnr5iEUh3e9lwyxtWqwfdML8g_WsCUxgjtH0AodvNsJEI6HkwIuBF19edzttT_rOC7NcZeVIoRnEiu9oawJBGF0aevB2mjykof2IbG7TCCmFtCODw
            03-27 22:28:04.093: D/RegisterActivity(2633): onClick of Share: Before starting main activity.
            03-27 22:28:04.093: D/RegisterActivity(2633): onClick of Share: After finish.
            03-27 22:28:04.103: D/MainActivity(2633): regId: APA91bHtGqrw3KDecjwpG1l2urQRQDy1x4WAV-fkys80kFLrCHnr5iEUh3e9lwyxtWqwfdML8g_WsCUxgjtH0AodvNsJEI6HkwIuBF19edzttT_rOC7NcZeVIoRnEiu9oawJBGF0aevB2mjykof2IbG7TCCmFtCODw
            03-27 22:28:18.413: D/AndroidRuntime(2633): Shutting down VM
            03-27 22:28:18.413: W/dalvikvm(2633): threadid=1: thread exiting with uncaught exception (group=0xb2cd8180)
            03-27 22:28:18.413: I/Process(2633): Sending signal. PID: 2633 SIG: 9
            03-27 22:28:18.413: D/AndroidRuntime(2633): procName from cmdline: com.javapapers.android
            03-27 22:28:18.413: E/AndroidRuntime(2633): in writeCrashedAppName, pkgName :com.javapapers.android
            03-27 22:28:18.413: D/AndroidRuntime(2633): file written successfully with content: com.javapapers.android StringBuffer : ;com.javapapers.android
            03-27 22:28:18.413: E/AndroidRuntime(2633): FATAL EXCEPTION: main
            03-27 22:28:18.413: E/AndroidRuntime(2633): java.lang.RuntimeException: Unable to instantiate receiver com.google.android.gcm.GcmBroadcastReceiver: java.lang.ClassNotFoundException: com.google.android.gcm.GcmBroadcastReceiver
            03-27 22:28:18.413: E/AndroidRuntime(2633): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2100)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1197)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at android.os.Handler.dispatchMessage(Handler.java:99)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at android.os.Looper.loop(Looper.java:137)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at android.app.ActivityThread.main(ActivityThread.java:4424)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at java.lang.reflect.Method.invokeNative(Native Method)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at java.lang.reflect.Method.invoke(Method.java:511)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:592)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at dalvik.system.NativeStart.main(Native Method)
            03-27 22:28:18.413: E/AndroidRuntime(2633): Caused by: java.lang.ClassNotFoundException: com.google.android.gcm.GcmBroadcastReceiver
            03-27 22:28:18.413: E/AndroidRuntime(2633): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
            03-27 22:28:18.413: E/AndroidRuntime(2633): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2095)
            03-27 22:28:18.413: E/AndroidRuntime(2633): … 10 more

          • Ria, now the error posted is different from the earlier one. Now android-support-v4 dependency is solved.

            Looks like google-play-services_lib is not configured as Android dependency. Refer the image in section PartB-Point3 to configure google-play-services_Lib as Android dependency.

  39. I can register with the GCM server and I can share my GCM RegID with the app server. However when I try and send a message I get the following error:

    Warning: file_get_contents(GCMRegId.txt): failed to open stream: No such file or directory in /Library/WebServer/Documents/gcm/gcm.php on line 37

    So it looks like GCMRegId.txt is not being created. Any ideas?

    Thanks

    Great tutorial by the way

    • Thanks David.

      Looks like the GCMRegId.txt file is not getting created.

      Can you manually create this file and keep it empty at the application-server root and then try?

  40. Hey! Awesome tutorial, thanks for it.

    I’m now facing a problem tho.

    The app gets gerID from GCM and it is able to send it to our server and the php server application is able to write it into the text file as supposed to.

    The problem comes when I try to send push message trough the php app.
    I get this:

    {“multicast_id”:5760807111590163335,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{"error":"MismatchSenderId"}]}

    What could be causing this?

    Thank you.

  41. Hi Joe,
    Thanks for your tutorial, very useful. And I have run successfully in my app client site, which shows “RegID shared with Application Server”. However, I have two little problem: (I am using Java)

    1. the link for the java should be
      ”xxx/GCMNotification.java?shareRegId=1″;
    instead of
      ”xxx/GCMNotification?shareRegId=1″;
    otherwise, I would get a “404 error”

    2. I have problem of the server site, actually I am little focusing about the data process of the web server. How can I get the result page (with the regID) automatically? I can only open the index.jsp page, but how to let the result shows like yours? I can’t do that, please give some advice:)

    Cheers,
    Sky

  42. how to send message from device to server..??

  43. Pingback: Android Device to Device Messaging using Google Cloud Messaging (GCM) via Http

  44. What are the problems behind “error:InvalidRegistration”??Only the incorrect reistration id?

    I tried to send messages to an android app. every time i got the same output .that is shown below:

    {“multicast_id”:9115386997854774649,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{"error":"InvalidRegistration"}]}

    I am sure that the registration id is correct. yet i don’t know why it happens so..

    • make sure that it was shared with ur app server.and make sure u allow any IPs in your google console settings

  45. hello joe,
    there is no error but..
    i see my alerts sent from server in activity.but i see first alert only even if i try to view new alerts.

    i copied my code in onresume() method but nothing happened.tell me how do i set text dynamically with respect to alerts.i have to reinstall the app again n again in order to see updated alerts….

  46. Have got internet on emulator..i’ve checked that still it shows
    “Registered with GCM Server.Error:
    SERVICE_NOT_AVAILABLE”

    • I haven’t coded server part just want to get reg_id first bt am unable to get that due to above stated error

      • make sure you have added all the permissions.and your emulator is connected to the internet.last option:try turning off ur fierewalls.

        • I just copied the above manifest file..rather copied each and every file as it is. Turning off firewall isn’t helping either

          • make sure you have steady internet connection ..try it in a real phone

  47. thank’s this tutorial is good
    i use this tutorial to make my gcm service,
    this tutorial successfully work on my android emulator but after i tray on my real device my apps cannot get the gcm notification.
    anyone can help me?

  48. thank’s this tutorial is good
    i use this tutorial to make my gcm service,
    this tutorial successfully work on my android emulator but after i tray on my real device my apps cannot get the gcm notification.
    anyone can help me?

    • Why? Didn’t you see the download link? or Do you have any issues in downloading it?

  49. When I run GCM server application, the following error occurs
    RegId required: java.io.FileNotFoundException: GCMRegId.txt (The system cannot find the file specified)
    please let me know any answer.

  50. {“multicast_id”:8339054608113437446,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{"error":"InvalidRegistration"}]}
    how to resolve this .. please help

    • make sure u have allowed all IPs.in google console account by removing every ips.and check if the text file if created or not

  51. Hello Joe, Thanks for the Tutorial. I did good as you demonstrate. My device registered on GCM Server, and can able to see regId on Logcat. But I’m unable to push notification from server. It’s throwing FileNotFoundException. Not abel to create GCMRegId.txt , Please do find me solution.

    Many Thanks.


    Regards,
    Bhanu Prakash

  52. I had implemented GCM Appliction It works fine in emulator but while comming to the Mobile device it shows GCM error even after adding google account to my phone

  53. I have a problem using my nexus 7.. What Local Ip Address should i use?

    I could not connect to my application server using Nexux 7. In the config.java what should be the com.toksis.gsmsampleclient2.app.Config#APP_SERVER_URL?

  54. Hello , After trying for a long time , I finally got the program to work!, But The Notification shows Null every time. What could be the problem?

    • You should check the key using which the message is retrieved at the Android client side. It should be same as being sent from the GCM Server side. May be, you should print the complete message in the Android log and check.

  55. Just a few tips for success in this example:
    -Remember, when you change the data in Config.java or other in this Android project, Build the project another time to apply the changes!!
    -BEWARE! IT’S A MISTAKE, YOU’LL NEED TO CORRECT THIS: Change parameter to send notificacion to GCM in PHP (in my case) app server: $message = array(“m” => $pushMessage); to —> $message = array(“message” => $pushMessage);
    -And yeah, at the first try be in localhost.

    Thank you very much for the tutorial, Joe.

  56. I have a question. In GCMNotificationIntentService.java there is the message’s handler. Well, there is a thread sleep, I’m wondering why this 5×3 seconds of wait is necessary. It’s a performance requeriment?? or a simulation of massive usage of the system???

    Commented this bucle, the response becomes immediate.

    Zach Baudrey, I think you need to correct the mistake I was talking about.

  57. I’m sorry but I’m having problems with your tutorial . . .

    I can’t seem to open GCM-App-Sever in Eclipse. After unziping I tried to import it into a new workspace but Eclipse says it’s not a project. I tried opening it directly in Eclipse but the same thing. What could I be doing wrong.

  58. I am getting following error
    RegId required: com.google.android.gcm.server.InvalidRequestException: HTTP Status Code: 401

  59. I get the following errors
    MESSAGE_KEY cannot be resolved or it is not a type
    pllllz help me

  60. Dear Joe,
    The ‘Java GCM Server Web Application’ package seems, not a complete enclipse androis project. I could not ‘import’ it as android project in eclipse.
    But ‘client’ application project is getting imported in Eclipse.

    Is anything wrong in my approach? Please guide me in loading the server application.

  61. When i select Register with Google GCM Server, the app crashes.
    This is the Error Log from Eclipse: http://pastebin.com/ubH6SZy8
    Really don’t know what’s wrong with the application, the server part works ok.

    • You have issue with dependency. Check in section-3 under “GCM Android App Prerequisite”.

  62. Registration id generated succefully in adroid device…
    But when run Java Application it gives following error.
    RegId required: com.google.android.gcm.server.InvalidRequestException: HTTP Status Code: 401

    Help plz…

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>