Google Cloud Messaging GCM for Android and Push Notifications

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 added on 23/01/2014.

previous post: Interpreter Design Pattern

next post: State Design Pattern

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

    • Hi,

      I want to Send current location from my Device to Application Server as a response to the Request made by Application Server.

      Example :
      Consider a Passenger waiting for a Driver
      1. Passenger Requests to Application Server from its app,
      2. Application Server Requests the Driver on its app,
      3. Driver’s Location is Sent to Application Server.

      What I figured out through GCM is we can Send / Recieve Messages to GCM. I just Want to know How we can send Location Through GCM.

    • Hello, best tutorial for beginner, work perfect

      • Hello, best tutorial for beginner, work perfect

        you should edit : ‘$message=array(“m”=>utf8_encode($pushMessage)); ‘ in php file to send special character

  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 =) ..

      • application-server to mobile via GCM-server. Is this how many chatting android applications work ? For example ePenPal?

  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

        • I have same problem, means here is no error getting in logcat. and i also have verified that message is sent to gcm server. But not getting any notofication on my device, I had already test on emulator and on real device. I have followed the all step from scretch to end but not getting notification. Pls help, i am trying this by last week. Thnks

  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.

      • where shall i create GCMRegId.txt dis file manually

        • i am using it with java and getting an error as RegId required: java.io.FileNotFoundException: GCMRegId.txt (No such file or directory)

    • 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

    • HEY ADMIN WHERE ARE YOU?? PLEASE ANSWER THİS QUESTION. IT IS IMPORTANT FOR YOU. BECAUSE YOU CAN. IF YOU CAN YOU JUST DO IT OKEY.

  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”

        • The problem is emulator does not have proper Time Set and it also doesnt have SIM, so google cant register it. Those who are facing SERVICE_NOT_AVAILABLE, try running your app on real phone with a SIM. It will work fine.

  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.

          • HI were you able o solve this problem?

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

          • After hours of research, I fixed the issue as follows:

            In my case I had to go to Properties->Java Build Path->Order and Export and tick the check box Android Private Libraries, then cleaned the project and worked fine.

  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?

      • I have some problem but I cant. I created GCMRegId.txt on my route file, GCMRegId.txt with gcm.php on the same file. And I write my message and I click send but its turning error, like this :

        ( ! ) Warning: file_get_contents(GCMRegId.txt): failed to open stream: No such file or directory in C:\wamp\www\gcmnew\gcm.php on line 41
        Call Stack
        # Time Memory Function Location
        1 0.0039 263920 {main}( ) ..\gcm.php:0
        2 0.0039 264792 file_get_contents ( ) ..\gcm.php:41
        Curl failed: Failed connect to android.googleapis.com:443; No error

        • Hi me too getting same error Please let me know the solution this is bit argent If any know the solution please mail me .

  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.

      • Thank you I too got same issue and solved with uninstall and reinstall

  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

      • How can I make sure that it is shared with my app server? Im using MAMP and in the config.java file, i enter the url as my ip address and then gcm/gcm.php?shareRegId=1 which is the path to the file. Still I get the same error as mentioned above. The url to the server is correct, as when i try to connect to other php files from the same ip address, they work perfectly fine.

        I am uses php implementation for the server.

        Sorry, if my question is too trivial. I am a total newbie to android development. Your help would be most appreciated.

  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

      • where can i check if the text file is 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.

    • I think you should you GCM Php with Wamp. This way is the best way, I tried GCM-App-Server but I failed,so I used php and it worked. But I have a problem. My mobile doesn’t recieve any notification and now I’m trying to solve it :(

  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…

  63. Hello Dear jeo,
    I have successfully register regId and send message and
    get follwing output
    “[ messageId=0:1397796580428924%31e4cc17f9fd7ecd ] ”

    But i could not receive message in emulator…
    I am getting following “error log”
    “connectionClose : no XMPPConnection – That’s strange!”
    Please help.

  64. I got this error:

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

    Please help.. I am sure that i have provide correct project id and api key

  65. hi, i got this error after pushing the notification “HTTP Status 404 – /GCM-App-Server/GCMNotification”.any one tell me what might be the reason?

    • I have a problem. The browser print a success message like this:

      {“multicast_id”:8189873987530733318,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1398683521253498%26b29929f9fd7ecd"}]}

      but my smartphone don’t recieve any notification

  66. Thank you for the great tutorial.

    I have three things to mention, one has already been posted:

    1st:
    I used the php-server code and therefore i had to change the “message” to “m” in config.java (android app), otherwise I also received the notification “Message Received from Google GCM Server:null”

    2nd:
    After the first push notification via the webserver it seems that the content in the “GCMRegId.txt” is replaced with the value “null”
    I fixed it that way, that after the first app-share request (which is successfull) i commented the following code snippet “out”.

    /*
    if(!empty($_GET["shareRegId"])) {
    $gcmRegID = $_POST["regId"];
    file_put_contents(“GCMRegId.txt”,$gcmRegID);
    echo “Ok!”;
    exit;
    }
    */

    3rd:
    in the php server code I replaced the line

    with

    because otherwise in the URL bar it will look like that gcm.php/gcm.php/?push=1 after to requests, but with the replacement the url keeps the same.

    last i have to mention, that in my app i receive every message correctly, but when i click at the notification i always get the message “RegId: null”, but everything is working fine :-)

  67. Hi Joe,

    This is very good tutorial. Its really helped me in developing.I am developing MDM server for android devices. I have one question: Is there any way server to android device communication by using java apart from GCM?

  68. Thanks a lot. GCM is perfectly working for me. Nice post. It is really useful for the beginners who works on GCM

  69. HI , I have worked on this example but it is giving me RegID shared with application server.RegID is Null.
    and i have given static final String APP_SERVER_URL = “http://10.0.0.4:9999/Hello”; where i have created tomcat server. I’m little confused.what should i give to APP_SERVER_URL .I’m directly getting second screen without asking the registration screen.can you pls help i have tried for six hours.

  70. Uploading Integrationapp.apk onto device ’192.168.56.101:5555′
    Integrationapp] Installing Integrationapp.apk…
    Integrationapp] Success!
    Starting activity com.sanjeev.integrationapp.MainActivity on device 192.168.56.101:5555

    Why i’m i getting this in console ?
    And when i click on addcontact in settings menu i am unable to get google account i am getting corporate and email i don’t see google account. firstly what should i setup should i go with server or client setup
    from my server side i can see following image
    http://javapapers.com/wp-content/uploads/2014/01/GCM-Server-Application.png
    but i am unable to get the regid how can i do that

  71. Hey Joe,
    for the web server in php,I don’t want that send button(send push notification via gcm). I want to send a message with fixed text and not as a user input. for example, I want to send a message saying “Enter your email-id and password” to the android application. Can you tell me the code, I’m new to php.
    Thank you !

  72. I am unable to see the registration screen in my emulator it is directly going to activity and it is giving me RegID Is NULL what should i do now can you please tell me where i’m wrong? Waiting for your reply

  73. HI I am getting

    java.lang.NoClassDefFoundError: com.google.android.gms.gcm.GoogleCloudMessaging com.sanjeev.integrationapp.RegisterActivity.registerGCM(RegisterActivity.java:79)
    com.sanjeev.integrationapp.RegisterActivity$1.onClick(RegisterActivity.java:46)
    at android.view.View.performClick(View.java:4084)
    android.view.View$PerformClick.run(View.java:16966).os.Handler.handleCallback(Handler.java:615)
    android.os.Handler.dispatchMessage(Handler.java:92) android.os.Looper.loop(Looper.java:137)
    android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)

  74. Hi Jeo,
    My app crashes with an error java.lang.NoClassDefFoundError

    com.google.android.gms.gcm.GoogleCloudMessaging

    com.sanju.cloudmessaging.RegisterActivity.registerGCM(RegisterActivity.java:79)

    com.sanju.cloudmessaging.RegisterActivity$1.onClick(RegisterActivity.java:46)

    at this line GoogleCloudMessaging.getInstance(this);

    I have been trying from two days your not replying me .reply me waiting for your reply.

  75. Hello Mr.Joe
    I got
    {“multicast_id”:7234398735162395694,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1400457734943812%c65c9a21f9fd7ecd"}]}
    but I did not receive the notification in the mobile

  76. Thank you for the comprehensive tutorial.

  77. Pingback: Google Cloud Messaging GCM CCS with XMPP

  78. Thx for this helpful tutorial! Helped me a lot :-)

  79. HI Jeo,
    I am sanjeev have been asking you about my errors from last week you didn’t reply me.Finally I solved my errors now i can send and receive the messages and thanks for your tutorial.I have learned some thing new about GCM.Thanks for your GCM Example.

    • Hi,sanjeev. I’m having the same problem as you. Can you tell me how you fixed it? Thank you in advance.

  80. hey Joe, i am getting error 401 while hitting send button in the gcm.php
    please help me to resolve it

  81. Pingback: Google Cloud Messaging GCM for Android and Push Notifications - appgong

  82. Hi Joe,
    first of all thanks for the blog.
    we are trying to implement push notification service for ADF mobile. and used your server side code to send notification to android device. We are able to receive the notification alert(alert sound with client app) but message is null. We are not able to receive message. could you please suggest where we might did wrong?
    here is my onMessage() method implementation(Invoked when a Push Notification arrives)

    public void onMessage(Event event) {
    //Parsing the payload JSON string
    JSONBeanSerializationHelper jsonHelper = new JSONBeanSerializationHelper();
    try {
    PayloadServiceResponse serviceResponse =
    (PayloadServiceResponse)jsonHelper.fromJSON(PayloadServiceResponse.class, event.getPayload());

    Map session = (Map)AdfmfJavaUtilities.evaluateELExpression(“#{applicationScope}”);

    String newMsg = serviceResponse.getCustomMessage();
    session.put(“pNewMessage”, newMsg);

    } catch (Exception e) {
    e.printStackTrace();

    }
    }

    we are using #{applicationScope.pNewMessage} in our UI to show the notification message, but we are only receiving notification alert(alert sound) but not message. Please suggest.

  83. I am running it on my mobile and sending all the swear words one by one from the net. Everything is working perfectly fine. Thank You Joe.

    There was a minor typo in the code in the config.java file I suppose due to which the message received was ‘null’ earlier. But it has been corrected in the comments.

    static final String MESSAGE_KEY = “m”;

    Once again, hats off for Joe. :D

  84. good afternoon sir,i have written my server side code as per the specification told, but when i try to create an object of server class (Sender sender = new Sender(google_server_key)to send message to gcm from server to gcm , the execution stops at this line,means there is no exception , no error, the executions just remains there, it is not moving to next line of code. please help me.i have also provided with the correct google server key in the sender constructor.

  85. I am having a problem registration in GCM saying SERVICE_NOT_AVAILABLE, until I found this, I copy the code provided in here and it’s working really just fine now. Great!

  86. hello joe
    this blog is really awesome.
    i m getting some issue.
    i have followed all your instruction carefully.
    my query is what should i write in config.java in APP_SERVER_URL variable, as my php is in localhost and i know my ip is 127.0.0.1 , but it not working when i browse thru android emulator

    also where do i get regid? and where do i put it?

    also gcmregid.txt was not created auto, so i created empty file manually in gcm folder near gcm.php file .

    in congig.java do we have to use project id or project number in google_project_id variable??

    i will be relly glad if u reply all my issue and solve it

    thanks dear

  87. Hey Joe
    I follow this tutorial. I write my server part using java in Netbeans. I set the APP_SERVER_URL = “http://10.0.2.2:8084/GCMServer/GCMNotification”;
    I set the ip as loopback address and delete “?shareRegId=1″ from url.

    Now my problem is when i click on Register with Google GCM Server it shows me the Regid:jshjkjcc….. and when i click on Share GCM-RegId with App Server it goes to the main activity ans shows me the message RegId shared with Application Server. RegId:jshjkjcc…..

    Now when i write something on GCM Server and click on Send Push Notification via GCM it shows me the error “RegId required: java.io.FileNotFoundException: GCMRegId.txt (The system cannot find the file specified)”
    What is wrong with my code….please reply me….it is urgent!!!

  88. I got this error while running gcm-server code please help me out.

    • RegId required: java.io.FileNotFoundException: GCMRegId.txt (The system cannot find the file specified)

      • Create a file with the name GCMRegId.txt in c:\folder\GCMRegId.txt and the change the path in GCM Server app as c:/folder/GCMRegId.txt

        • Thanq.I have another question. While sending 250 characters of data push mesg shows only single line(i.e 30 to 40 char). How can i Display total data in mesg atleast 150 characters.

  89. This code is working fine, i appreciate the effort. Mysteriously i ran into a problem with this script. Whenever u minimize or stop (onstop or ondestroy) after closing network access, strange toast message coming repeatedly, its irritating. I re-read entire code, but nowhere i see this toast code.

    Toast Error: “Failed to Load Database, Please Restart Application”

    Toast messages is appearing only after exiting the app + network failure (No internet access)

    can u help me please, i want to remove that code or atleast, want to know its source code (to edit)

    • Hello Ravi
      I follow this tutorial but it does not working for me. Can you please help me. When I click on “Send Push Notification via GCM” it shows me the following output
      [ messageId=0:1403074150101397%31e4cc17f9fd7ecd ] and does not show any notification on AVD. Please help me

  90. Hello joe,

    I am new in android i just follow your tutorial and run it on emulator it is working fine when i click on notification it will display activity_main.xml view and display a toast of registration id : null why so? rest of the things are working fine nice job. Do you provide any advance training course regarding android?

    • Hello Amrinder
      I follow this tutorial but it does not working for me. Can you please help me. When I click on “Send Push Notification via GCM” it shows me the following output
      [ messageId=0:1403074150101397%31e4cc17f9fd7ecd ] and does not show any notification on AVD. Please help me

  91. Pingback: Android Chat with Google GCM XMPP

  92. Hello Sir!
    Please help me. When I click on “Send Push Notification via GCM” it shows me the following output
    [ messageId=0:1403074150101397%31e4cc17f9fd7ecd ]. It does not show the output like
    {“multicast_id”:7048577678678825845,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{"error":"InvalidRegistration"}]}
    Please tell me what is the issue?

  93. Hello Sir!
    Please help me. When I click on “Send Push Notification via GCM” it shows me the following output
    [ messageId=0:1403074150101397%31e4cc17f9fd7ecd ]. It does not show the output like
    {“multicast_id”:4968672681542797991,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1391001084908870%28678a6af9fd7ecd"}]}
    Please tell me what is the issue?

  94. While sending 250 characters of data push mesg shows only single line(i.e 30 to 40 char). How can i Display total data in mesg atleast 150 characters.

  95. While sending 250 characters of data push mesg shows only single line(i.e 30 to 40 char). How can i Display total data in mesg atleast 150 characters. Please help me

  96. Hello Sir!
    Now I am getting the output {“multicast_id”:5163471844000799180,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{"message_id":"0:1403507025702682%31e4cc17f9fd7ecd"}]}
    but not getting any notification on AVD or real device

  97. First off, thank you for this tutorial. So far I’m getting all of it. Very helpful!
    However, I did run into an issue…
    I go to gcm.php and then send a push back to the registered phone. Your code calls the php file with a forward slash “gcm.php/?push=1″ With that I receive a 404 error (using nginx).
    OK, it must be that slash. Right? So I changed it to “gcm.php?push=1″ No 404, but now the page just come up blank; not even a failure message.
    Any tips?
    Note: Server IP / API Key / Project ID / GCMRegId.txt have been triple check for correctness.

  98. Hello, Thank you for this great tutorial, it’s the best on the net.
    my problem is everything is good i send the message i got the the notification o my phone but the not the message that i’ve written. just the notification with the title “Message Received from Google” when i click on it it gives me the Toast “RegId shared with application server RegId null” where can i find the message?

  99. Is it necessary to unblock port no. 5228-5230 for this application.

  100. Hi Joe!
    Thank you for this tutorial which helps me a lot!

    But I have some problem with the project.

    I tried the php server, but I didn’t receive the reg id in the GCMRegId file from the Android application.
    I have the 401 error.

    Even if I copied the reg id from the logcat and pasted it in the GCMRegId file, the 401 error persists.

    I forgot to tell you that I use a real device, an Android tablet.

    I don’t know how I can do to solve these issues.

    Thank you for helping me!

    • Hi,

      I found my problem.
      In Google developer console, I put the ipv6 for the “edit allowed ip”!

      Thank you very much for this tutorial!!

  101. hello sir.can u explain in detail about the app_server_url in case of php implementation.
    Secondly using my localhost ip address i am not recieving data sent by application to the server.
    Its showing
    post failure:Error in sharing..
    Any help will be highly appreciated.

  102. Hi,

    Really appreciate you for this tutorial. But can we get the tutorial in Java as I’m not versed with PHP.

    Thanks

  103. Thanks for this great tut brother…

    Some notes:
    - Its not Project ID use Project Number
    - Change MESSAGE_KEY = “message” to MESSAGE_KEY = “m”
    - change action=”gcm.php/?push=1″ to change action=”gcm.php?push=1″

  104. I got this error while running gcm-server code please help me out.
    can please help me to fix !

  105. Very nice tutorial Sir. I am also the author of my programming blog but this blog give us a lo information. Salute you Sir.

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>