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() {
			@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 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() {
			@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 paramsMap = new HashMap();
		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> iterator = paramsMap.entrySet()
					.iterator();

			while (iterator.hasNext()) {
				Entry 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.

«

»

Comments on “Google Cloud Messaging GCM for Android and Push Notifications”

  1. Priya Patel

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

    • Joe

      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.

    • Vu Tri Chien

      Good morning sir ! Thanks for your tutorial
      I got a problem when i import the client source code in to my eclipse
      it like that:
      https://www.dropbox.com/s/hjgzn5s7zau0alo/erroe.jpg
      Is there something wrongs here, please solve it for me, thank you so much, have a nice day!

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

    • Vu Hung

      Hello, best tutorial for beginner, work perfect

      • Vu Hung

        Hello, best tutorial for beginner, work perfect

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

    • nisha

      I am getting error service not available with the above android code fordevice registration.I am not getting registration _id.

  2. Samraj

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

  3. Firoz Shaikh

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

  4. Chethan

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

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

    • Joe

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

    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?

    • Joe

      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.

  7. carlos

    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

    • Joe

      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. Amir Granadillo

    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

    • carlos

      same here =(

    • Joe

      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…

      • carlos

        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

        • user1

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

          • Joe

            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. Thanks & Awesome. I love Java Papers. Love your creative blog Joe.

    Thanks,
    Udhayakumar G K

  10. Abhijeet

    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 ?

    • Joe

      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.

  11. AASHRAI RAVOORU

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

    • Abhijeet

      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.

      • Abhijeet

        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

        • Joe

          Very HAPPY to know that the application is working!

        • anki

          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

  12. Aviral Bansal

    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?

  13. Naveen

    what are the use of GCM from other normal servers

  14. Kaustubh

    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!

    • amudha

      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.

    • Joe

      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.

  15. Babita Parida

    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.

    • Joe

      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.

  16. priyankar

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

    • sunil

      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

  17. priyankar

    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?

  18. Ashwin Ganesh

    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

    • Joe

      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.

  19. Partha

    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.

    • Joe

      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.

  20. Girish

    Hi Joe,

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

  21. vaibhav

    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)

  22. {“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!

    • Joe

      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.

  23. user1

    i am not getting regId please help

    • Joe

      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.

  24. Nilesh

    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?

    • Joe

      Nilesh,

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

      • Anonymous

        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?

        • Joe

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

          • Tony

            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.

          • Anonymous

            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.

          • Joe

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

  25. paramvir

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

  26. satheesh

    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.

    • Joe

      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.

  27. Jake

    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

    • hasan hakki

      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.

  28. Tony

    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!

  29. BhuwaneshSinha

    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)

  30. Pradeep M

    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?

  31. hitesh

    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 ?

  32. Jagdish

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

  33. keith

    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.

  34. Binu

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

  35. Ayush

    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.

    • comer

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

    • Joe

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

      • sha

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

        • DineshM

          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.

  36. vasantha

    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

    • ria

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

    • Joe

      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.

    • A

      Vasantha, edit the manifest file and provide proper package name prefixes for all activities and permissions

  37. vasantha

    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

  38. nick halden

    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…

    • Joe

      For 1. what is the error you get?

      For 2. Hope you have read my other tutorial http://javapapers.com/android/android-multicast-notification-using-google-cloud-messaging-gcm/

      I have given the code for multiple reg ids in Java. Instead of rewriting the regid.txt file everytime, you need to append the regids and second thing is the request should be appended and posted to Google GCM server.

      • nick halden

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

        • Joe

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

          • nick halden

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

          • nick halden

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

          • Joe

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

          • nick halden

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

  39. ria

    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

    • Joe

      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?

      • ria

        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

        • ria

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

          • nick halden

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

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

          • manoj

            HI were you able o solve this problem?

        • Joe

          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.

          • ria

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

          • ria

            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

          • Joe

            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.

          • Vishnu

            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.

          • Oat

            Vishnu your solve is OK, Thank you son much. I fix it a long time.

  40. David

    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

    • Joe

      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?

      • hasan hakki

        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

        • sudhakar

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

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

  42. Sky

    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

  43. Akshay

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

  44. aju

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

    • nick halden

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

      • suyash agarwal

        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. nick halden

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

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

    • sha

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

      • nick halden

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

        • sha

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

  47. Anonymous

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

    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?

  49. Please can u send me the all code on email.

  50. Kyaw Zin Htun

    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.

  51. Ankit Kumar

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

  52. nick halden

    hello joe..please tell me which steps are required to make this app in the link?i have to make the same application like this..i dont know if they used web view.or activity n fetching strings n images.. :(

    https://play.google.com/store/apps/details?id=com.alienskills.hackers.manual

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

  54. yesuraju

    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

  55. Victor

    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?

  56. Zach Baudrey

    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?

    • Joe

      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.

  57. Litzer

    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.

  58. Litzer

    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.

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

    • Hoang Yen

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

  60. Girish

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

  61. farhan

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

  62. Arun

    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.

  63. Martzy

    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.

  64. Girish

    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…

  65. Girish

    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.

  66. Ruchita

    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

  67. shambhi reddy

    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?

  68. I think you will become my best friend, this tutorial is awesome!

    • 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

  69. lsweic

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

  70. Govindu

    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?

  71. Deep Bhavsae

    The best

  72. Nagaraj N

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

  73. Sanjeev Reddy

    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.

  74. Sanjeev Reddy

    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

  75. Vikas

    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 !

  76. Sanjeev Reddy

    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

  77. Sanjeev Reddy

    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)

  78. Sanjeev Reddy

    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.

  79. Muj

    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

  80. Ramiz

    Thank you for the comprehensive tutorial.

  81. Martin from Germany

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

  82. Sanjeev Reddy

    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.

    • Pedro Oliveira

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

  83. Vikas

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

  84. Anonymous

    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.

  85. Prateek Bhuwania

    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

  86. paritosh goel

    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.

  87. Jay

    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!

  88. jay

    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

  89. Pal

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

  90. reddy

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

    • reddy

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

      • Pal

        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

        • Anonymous

          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.

  91. ravi

    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)

    • Pal

      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

  92. Amrinder

    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?

    • Pal

      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

      • john

        hai pal,

        right click the project,In properties–>java buit path->order and export-> fill the check box…
        All is well

  93. Pallab

    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?

  94. Pallab

    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?

  95. Anonymous

    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.

  96. Anonymous

    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

  97. Pallab

    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

  98. Matthew

    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.

  99. Abdellah

    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?

  100. Pallab

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

  101. manvehe

    Thank you very much for this tutorial.

  102. Maryam

    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!

  103. omkar patil

    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.

  104. Hi,

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

    Thanks

  105. 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″

  106. max

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

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

  108. Rehab

    Very nice tutorial
    is there GCM Server Application in C#?

  109. Nadia

    Hi Joe,

    After the text (in web service) is entered and the message is push. That is the error shown in the web service.
    RegId required: com.google.android.gcm.server.InvalidRequestException: HTTP Status Code: 401
    While in apps the RegId is shared in web server. Please Help.

    Thank you.

    ***Same problem with Girish
    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

    • john

      hai nadia,

      I am also face this issue but now i resolve it. create new gmail account and create new project,server key with all ip allowed,android key with YOUR SH1 FINGERPRINT -FE:F9:DD:58:37:A8:06:B2:52:15:8F:69:24:FE:72:AE:25:E9;com.javapapers.android and used your new project ID and serverkey,androidkey..It may work .. Have nice day

  110. john

    hi joe..

    while push message from server to android emulator,i cannot receive it ..android activity is closed.following issue is occur.

    *******************************************
    08-07 17:27:06.227: E/Trace(10031): error opening trace file: No such file or directory (2)
    08-07 17:27:06.278: W/dalvikvm(10031): Unable to resolve superclass of Lcom/javapapers/android/GcmBroadcastReceiver; (108)
    08-07 17:27:06.278: W/dalvikvm(10031): Link of class ‘Lcom/javapapers/android/GcmBroadcastReceiver;’ failed
    08-07 17:27:06.317: D/AndroidRuntime(10031): Shutting down VM
    08-07 17:27:06.317: W/dalvikvm(10031): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
    08-07 17:27:06.327: E/AndroidRuntime(10031): FATAL EXCEPTION: main
    08-07 17:27:06.327: E/AndroidRuntime(10031): java.lang.RuntimeException: Unable to instantiate receiver com.javapapers.android.GcmBroadcastReceiver: java.lang.ClassNotFoundException: Didn’t find class “com.javapapers.android.GcmBroadcastReceiver” on path: /data/app/com.javapapers.android-2.apk
    08-07 17:27:06.327: E/AndroidRuntime(10031): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2357)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at android.app.ActivityThread.access$1500(ActivityThread.java:141)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at android.os.Handler.dispatchMessage(Handler.java:99)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at android.os.Looper.loop(Looper.java:137)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at android.app.ActivityThread.main(ActivityThread.java:5041)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at java.lang.reflect.Method.invokeNative(Native Method)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at java.lang.reflect.Method.invoke(Method.java:511)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at dalvik.system.NativeStart.main(Native Method)
    08-07 17:27:06.327: E/AndroidRuntime(10031): Caused by: java.lang.ClassNotFoundException: Didn’t find class “com.javapapers.android.GcmBroadcastReceiver” on path: /data/app/com.javapapers.android-2.apk
    08-07 17:27:06.327: E/AndroidRuntime(10031): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    08-07 17:27:06.327: E/AndroidRuntime(10031): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2352)
    08-07 17:27:06.327: E/AndroidRuntime(10031): … 10 more

    ***********************************

    Please help me…

    • john

      hai sir,

      previous problem is solved(Activity closed when message push from server).But when i click message on emulator i got “registerId=null” Message send from server is not display.

      please help me sir..

  111. vivek

    Hie i m using gcm and it is proper working also now i want to send the data to mulitiple user/mulitiple device_ip same data to mulitiple device at a same click Plz me for this problem

  112. Tahmid

    I am implementing the server side in Netbeans since my whole project is in Netbeans.. But while deploying my project, I am getting the following error..

    “The project uses the file/folder called “gcm-server-1.0.2.jar.zip”, but this file/folder was not found.”

    I added the required jar files in the library of my project and all the import statements are just fine..

    - Problem is, where to locate the “gcm-server-1.0.2.jar.zip” file so that I can browse and add the file to my project..

    • Tahmid

      Solved.. This may have happened due to closing Netbeans while the project scanning was not finished..

  113. Mayank

    Very nice tutorial!!!

  114. Thanks for this clear efficient tutorial,
    we’re about to test the client app .zip

    Have a great day !!!

    Michaud & Enry.B.

  115. Felipe

    Fantastic job!!
    Really good tutorial, thanks Joe
    After few tricky issues I made it work (don forget open 5228, 5229 and 5230 port in your firewall and/or router)

  116. nisha

    hello sir
    I face the below error:-

    com.google.android.gcm.server.InvalidRequestException: HTTP Status Code: 401

    Please helpme

Your Comment