How to send push notifications using GCM service?

In the previous post, I discussed What is GCM? and How it is used in Android applications?. In this post, I am going to develop simple Android application to demonstrate how it can be used to send Push notifications to User device.

I would recommend you to quickly take a look at the previous post (Read: Introduction to GCM) so that you will get to know about Google Cloud Messaging service and its usage.

What is GCM?

Google Cloud Messaging is a free service from Google which helps us to send messages (Push notifications) to Users’ device. It can also be used to send message from Users’ device to GCM server.

Here is the video demo of the Application we are about to develop, watch it.

Video Demo

I believe you got to know about the application from video demo.

About Application

  • It is a simple application which asks User to register with email id upon installation in order to create Registration ID from Google Cloud Messaging server.
  • Once after creating Registration ID successfully, it takes User to ‘Home’ activity, where the User can see the message sent from GCM Web application.
  • When the sender sends message from the Web application via GCM server (Configured with GCM server to send message), message reaches User’s device as push notification
  • Upon clicking the notification from the notification bar, it takes User to “Home’ activity, there User can see the message sent from Web application via GCM server.

You can download source code from here if you don’t want to create Application from scratch, otherwise please proceed with below listings.

Steps involved in send Push notifications:

Developing the application involves two parts:

  1. GCM Server Application – Create Web application using Php to send message to User via GCM Cloud server
  2. GCM Client Application – Create Android application which receive message sent from GCM Server Web App

GCM_Overview

Prerequisite

You need to have Google Project Key, API Server Key, and GCM RegId with you in order to send and receive Message.

Steps to create Google Project Key:

Goto https://console.developers.google.com/project and then create Project.

Google_Project_Creation

Enter Project name and click create, a project will be created.

Google_Project_Creation_1

You can see Project ID, note it down as it will be used in Step 4 of GCM Client Application.

Google_Project_Creation_2

Steps to create API Server Key:

Enable Google Cloud Messaging as shown below.

Google_Project_Creation_3

Create Server Key as shown below,

Google_Project_Creation_4

Enter your public address in order to white-list a set of IP addresses as the server key is mapped to IP addresses for security purpose. (Get your public IP address by googling ‘my public ip address’ in Google) and click create.

Google_Project_Creation_5

You can see SERVER_API_KEY, note it down as it will be used in Step 2 of GCM Server Application creation.

Google_Project_Creation_6

You don’t need to worry about creating GCM RegId, as it will be created inside Android application which we will discuss in some time later.

[pglinkadssmall1]

GCM Server Application

Step 1: Create Php file

Download gcm.php content from here and put it as gcm.php under www/gcm folder.

Step 2: Update API Server Key

Update ‘API_SERVER_KEY’ in function ‘sendMessageThroughGCM’ present in gcm.php with the one you created.

Step 3: Make Dry run

Try to run the gcm.php file on the Apache server and make sure it doesn’t throw any error. If your Apache server is not supporting the functions used in gcm.php, warnings and errors will be shown accordingly on browser. Fix it and then proceed to below steps.

URL will look like: http://localhost:9000/gcm/gcm.php/

GCM Client Application

Step 1: Create Android Application Project

  • Create new android project [File >> New >> Android Application Project] with project name GCMPushNotificationExample
  • Enter package name as ‘com.prgguru.example’
  • Choose Minimum Required SDK, Target SDK and Compile with as shown in the below screen-print. If you don’t have latest SDK installed, they will not be populated in the dropdownlist, I would recommend you to update Android SDK manager with latest SDKs. Confused on choosing these options? Take a look at Minimum Required SDK – Target SDK – Compile With post.
  • Click Next button and finally click ‘Finish’ to create project

Step 2: Add library to project

Add below third party library into project’s ‘libs’ folder. You can also download it if you don’t have it with you.

1. Android Asynchronous Http Client – An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries which is used by Pinterest, Instagram etc.,. Download

Step 3: Setup Google Play Services library project

To write GCM client application, we need to use the GoogleCloudMessaging API. To use this API, we must set up the project to use the Google Play services SDK.

Take help from here to setup Google Play Service library project.

Step 4: Design Screens

We are going to have two activities:

MainActivity – Launch Screen of the Application

HomeActivity – Home Screen of the Application

Before creating the layouts, make sure below resources are added.

Add string resources to strings.xml present under /res/values folder.

strings.xml

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

    <string name="app_name">GCMPushNotificationExample</string>
    <string name="welcome_txt">GCM App</string>
    <string name="email">Email Address</string>
    <string name="login">Register Me</string>
    <string name="defaultmsg">Message sent by server will appear here.</string>
    <string name="msg_title">Message</string>
    <string name="user_title">Hello User</string>

</resources>

Add dimension resource to dimens.xml present under /res/values folder.

dimens.xml

<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

</resources>

Add color resources to colors.xml present under /res/values folder.

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#ffffff</color>
    <color name="black">#000000</color>
    <color name="bg_gradient_start">#3990CA</color>
    <color name="bg_gradient_end">#15547E</color>
    <color name="bg_button_login">#1D394C</color>
</resources>

Create bg_button_rounded.xml under /res/drawable-mdpi folder and add below code to it.

bg_button_rounded.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!-- Background color -->
    <solid
        android:color="@color/bg_button_login" >
    </solid>

    <!-- Padding -->
    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"    >
    </padding>

    <!-- Corner radius -->
    <corners
        android:radius="6dp"   >
    </corners>

</shape>

Create bg_form_rounded.xml under /res/drawable-mdpi folder and add below code to it.

bg_form_rounded.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!-- Background color -->
    <solid
        android:color="@color/white" >
    </solid>

    <!-- Padding -->
    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"    >
    </padding>

    <!-- Corner radius -->
    <corners
        android:radius="6dp"   >
    </corners>

</shape>

Create bg_gradient.xml under /res/drawable-mdpi folder and add below code to it.

bg_gradient.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:gradientRadius="750"
        android:endColor="@color/bg_gradient_end"
        android:startColor="@color/bg_gradient_start"
        android:type="radial" />
</shape>

Create two layout XMLs under /res/layout folder:

activity_main.xml

Launch Screen

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_gradient"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="40dp"
            android:text="@string/welcome_txt"
            android:textColor="@color/white"
            android:textSize="45sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/bg_form_rounded"
            android:orientation="vertical" >

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:background="@null"
                android:hint="@string/email"
                android:padding="5dp"
                android:singleLine="true" 
                android:id="@+id/email" android:textColor="@color/black"/>
        </LinearLayout>

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp"
            android:background="@drawable/bg_button_rounded"
            android:text="@string/login"
            android:textColor="@color/white" android:onClick="RegisterUser"/>
    </LinearLayout>

</RelativeLayout>

activity_home.xml

Home Screen

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_gradient"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.prgguru.example.HomeActivity" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/usertitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="40dp"
            android:text="@string/user_title"
            android:textColor="@color/white"
            android:textSize="25sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/bg_form_rounded"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/message"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:background="@null"
                android:hint="@string/defaultmsg"
                android:padding="10dp"
                android:textColor="@color/black"
                android:textSize="20dp" />
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

Step 5: ApplicationConstants.java

We are done with Layout designing, let us jump into Coding.

Create ApplicationConstants.Java under the package com.prgguru.example and fill it with below code. It has constants used across application. Make sure your updated Google_Project_Key with the one you created above.

Make sure you changed the IP address mentioned in the APP_SERVER_URL constant with your Machine/LAN IP address.

package com.prgguru.example;

public interface ApplicationConstants {

	// Php Application URL to store Reg ID created
	static final String APP_SERVER_URL = "http://192.168.2.4:9000/gcm/gcm.php?shareRegId=true";

	// Google Project Number
	static final String GOOGLE_PROJ_ID = "837715578074";
	// Message Key
	static final String MSG_KEY = "m";

}

Step 6: Utility.java

Create Utility.Java under the package com.prgguru.example and fill it with below code. It has Utility methods.

package com.prgguru.example;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Class which has Utility methods
 * 
 */
public class Utility {
    private static Pattern pattern;
    private static Matcher matcher;
    //Email Pattern
    private static final String EMAIL_PATTERN = 
            "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";

    /**
     * Validate Email with regular expression
     * 
     * @param email
     * @return true for Valid Email and false for Invalid Email
     */
    public static boolean validate(String email) {
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(email);
        return matcher.matches();
    }
}

Step 7: MainActivity.java

Create MainActivity.Java under the package com.prgguru.example and fill it with below code.

It is the launch screen activity which asks User to enter Email ID, once Email ID is submitted Application will try to register User’s device in Google Cloud Messaging server. Registration Id will be generated once the registration is successfully completed.

Registration Id will be stored in GCM Server Application (created above) as text file (GCMRegId.txt).

package com.prgguru.example;

import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class MainActivity extends Activity {
	ProgressDialog prgDialog;
	RequestParams params = new RequestParams();
	GoogleCloudMessaging gcmObj;
	Context applicationContext;
	String regId = "";

	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

	AsyncTask<Void, Void, String> createRegIdTask;

	public static final String REG_ID = "regId";
	public static final String EMAIL_ID = "eMailId";
	EditText emailET;

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

		applicationContext = getApplicationContext();
		emailET = (EditText) findViewById(R.id.email);

		prgDialog = new ProgressDialog(this);
		// Set Progress Dialog Text
		prgDialog.setMessage("Please wait...");
		// Set Cancelable as False
		prgDialog.setCancelable(false);

		SharedPreferences prefs = getSharedPreferences("UserDetails",
				Context.MODE_PRIVATE);
		String registrationId = prefs.getString(REG_ID, "");

		//When Email ID is set in Sharedpref, User will be taken to HomeActivity
		if (!TextUtils.isEmpty(registrationId)) {
			Intent i = new Intent(applicationContext, HomeActivity.class);
			i.putExtra("regId", registrationId);
			startActivity(i);
			finish();
		}
	}

	// When Register Me button is clicked
	public void RegisterUser(View view) {
		String emailID = emailET.getText().toString();

		if (!TextUtils.isEmpty(emailID) && Utility.validate(emailID)) {

			// Check if Google Play Service is installed in Device
			// Play services is needed to handle GCM stuffs
			if (checkPlayServices()) {

				// Register Device in GCM Server
				registerInBackground(emailID);
			}
		}
		// When Email is invalid
		else {
			Toast.makeText(applicationContext, "Please enter valid email",
					Toast.LENGTH_LONG).show();
		}

	}

	// AsyncTask to register Device in GCM Server
	private void registerInBackground(final String emailID) {
		new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... params) {
				String msg = "";
				try {
					if (gcmObj == null) {
						gcmObj = GoogleCloudMessaging
								.getInstance(applicationContext);
					}
					regId = gcmObj
							.register(ApplicationConstants.GOOGLE_PROJ_ID);
					msg = "Registration ID :" + regId;

				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
				}
				return msg;
			}

			@Override
			protected void onPostExecute(String msg) {
				if (!TextUtils.isEmpty(regId)) {
					// Store RegId created by GCM Server in SharedPref
					storeRegIdinSharedPref(applicationContext, regId, emailID);
					Toast.makeText(
							applicationContext,
							"Registered with GCM Server successfully.nn"
									+ msg, Toast.LENGTH_SHORT).show();
				} else { 
					Toast.makeText(
							applicationContext,
							"Reg ID Creation Failed.nnEither you haven't enabled Internet or GCM server is busy right now. Make sure you enabled Internet and try registering again after some time."
									+ msg, Toast.LENGTH_LONG).show();
				}
			}
		}.execute(null, null, null);
	}

	// Store  RegId and Email entered by User in SharedPref
	private void storeRegIdinSharedPref(Context context, String regId,
			String emailID) {
		SharedPreferences prefs = getSharedPreferences("UserDetails",
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(REG_ID, regId);
		editor.putString(EMAIL_ID, emailID);
		editor.commit();
		storeRegIdinServer();

	}

	// Share RegID with GCM Server Application (Php)
	private void storeRegIdinServer() {
		prgDialog.show();
		params.put("regId", regId);
		// Make RESTful webservice call using AsyncHttpClient object
		AsyncHttpClient client = new AsyncHttpClient();
		client.post(ApplicationConstants.APP_SERVER_URL, params,
				new AsyncHttpResponseHandler() {
					// When the response returned by REST has Http
					// response code '200'
					@Override
					public void onSuccess(String response) {
						// Hide Progress Dialog
						prgDialog.hide();
						if (prgDialog != null) {
							prgDialog.dismiss();
						}
						Toast.makeText(applicationContext,
								"Reg Id shared successfully with Web App ",
								Toast.LENGTH_LONG).show();
						Intent i = new Intent(applicationContext,
								HomeActivity.class);
						i.putExtra("regId", regId);
						startActivity(i);
						finish();
					}

					// When the response returned by REST has Http
					// response code other than '200' such as '404',
					// '500' or '403' etc
					@Override
					public void onFailure(int statusCode, Throwable error,
							String content) {
						// Hide Progress Dialog
						prgDialog.hide();
						if (prgDialog != null) {
							prgDialog.dismiss();
						}
						// When Http response code is '404'
						if (statusCode == 404) {
							Toast.makeText(applicationContext,
									"Requested resource not found",
									Toast.LENGTH_LONG).show();
						}
						// When Http response code is '500'
						else if (statusCode == 500) {
							Toast.makeText(applicationContext,
									"Something went wrong at server end",
									Toast.LENGTH_LONG).show();
						}
						// When Http response code other than 404, 500
						else {
							Toast.makeText(
									applicationContext,
									"Unexpected Error occcured! [Most common Error: Device might "
											+ "not be connected to Internet or remote server is not up and running], check for other errors as well",
									Toast.LENGTH_LONG).show();
						}
					}
				});
	}

	// Check if Google Playservices is installed in Device or not
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		// When Play services not found in device
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				// Show Error dialog to install Play services
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Toast.makeText(
						applicationContext,
						"This device doesn't support Play services, App will not work normally",
						Toast.LENGTH_LONG).show();
				finish();
			}
			return false;
		} else {
			Toast.makeText(
					applicationContext,
					"This device supports Play services, App will work normally",
					Toast.LENGTH_LONG).show();
		}
		return true;
	}

	// When Application is resumed, check for Play services support to make sure app will be running normally
	@Override
	protected void onResume() {
		super.onResume();
		checkPlayServices();
	}
}

Step 8: HomeActivity.java

Create HomeActivity.Java under the package com.prgguru.example and fill it with below code.

It is the Home screen activity which display the message sent from GCM Server Application.

package com.prgguru.example;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends Activity {
	TextView msgET, usertitleET;

	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		// Intent Message sent from Broadcast Receiver
		String str = getIntent().getStringExtra("msg");

		// Get Email ID from Shared preferences
		SharedPreferences prefs = getSharedPreferences("UserDetails",
				Context.MODE_PRIVATE);
		String eMailId = prefs.getString("eMailId", "");
		// Set Title
		usertitleET = (TextView) findViewById(R.id.usertitle);

		// Check if Google Play Service is installed in Device
		// Play services is needed to handle GCM stuffs
		if (!checkPlayServices()) {
			Toast.makeText(
					getApplicationContext(),
					"This device doesn't support Play services, App will not work normally",
					Toast.LENGTH_LONG).show();
		}

		usertitleET.setText("Hello " + eMailId + " !");
		// When Message sent from Broadcase Receiver is not empty
		if (str != null) {
			// Set the message
			msgET = (TextView) findViewById(R.id.message);
			msgET.setText(str);
		}
	}

	// Check if Google Playservices is installed in Device or not
	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(this);
		// When Play services not found in device
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				// Show Error dialog to install Play services
				GooglePlayServicesUtil.getErrorDialog(resultCode, this,
						PLAY_SERVICES_RESOLUTION_REQUEST).show();
			} else {
				Toast.makeText(
						getApplicationContext(),
						"This device doesn't support Play services, App will not work normally",
						Toast.LENGTH_LONG).show();
				finish();
			}
			return false;
		} else {
			Toast.makeText(
					getApplicationContext(),
					"This device supports Play services, App will work normally",
					Toast.LENGTH_LONG).show();
		}
		return true;
	}

	// When Application is resumed, check for Play services support to make sure
	// app will be running normally
	@Override
	protected void onResume() {
		super.onResume();
		checkPlayServices();
	}
}

Step 9: GcmBroadcastReceiver.java

Create GcmBroadcastReceiver.Java under the package com.prgguru.example and fill it with below code.

A broadcast receiver is the mechanism GCM uses to deliver messages. When message is sent through GCM Server application, it triggers the broadcast receiver’s onReceive() method, which has the responsibility of making sure that the GCM message gets handled.

A WakefulBroadcastReceiver is a special type of broadcast receiver that takes care of creating and managing a partial wake lock for your app.

package com.prgguru.example;

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);
	}
}

Step 10: GCMNotificationIntentService.java

Create GcmBroadcastReceiver.Java under the package com.prgguru.example and fill it with below code.

The intent service shown below does the actual work of handling the GCM message. This class processes the GCM message based on message type, and posts the result in a notification.

package com.prgguru.example;

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

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

public class GCMNotificationIntentService extends IntentService {
	// Sets an ID for the notification, so it can be updated
	public static final int notifyID = 9001;
	NotificationCompat.Builder builder;

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

	@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)) {
				sendNotification("Message Received from Google GCM Server:nn"
						+ extras.get(ApplicationConstants.MSG_KEY));
			}
		}
		GcmBroadcastReceiver.completeWakefulIntent(intent);
	}

	private void sendNotification(String msg) {
	        Intent resultIntent = new Intent(this, HomeActivity.class);
	        resultIntent.putExtra("msg", msg);
	        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
	                resultIntent, PendingIntent.FLAG_ONE_SHOT);

	        NotificationCompat.Builder mNotifyBuilder;
	        NotificationManager mNotificationManager;

	        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

	        mNotifyBuilder = new NotificationCompat.Builder(this)
	                .setContentTitle("Alert")
	                .setContentText("You've received new message.")
	                .setSmallIcon(R.drawable.ic_launcher);
	        // Set pending intent
	        mNotifyBuilder.setContentIntent(resultPendingIntent);

	        // Set Vibrate, Sound and Light	        
	        int defaults = 0;
	        defaults = defaults | Notification.DEFAULT_LIGHTS;
	        defaults = defaults | Notification.DEFAULT_VIBRATE;
	        defaults = defaults | Notification.DEFAULT_SOUND;

	        mNotifyBuilder.setDefaults(defaults);
	        // Set the content for Notification 
	        mNotifyBuilder.setContentText("New message from Server");
	        // Set autocancel
	        mNotifyBuilder.setAutoCancel(true);
	        // Post a notification
	        mNotificationManager.notify(notifyID, mNotifyBuilder.build());
	}
}

Demo

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.

 

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse).

Download Source Code

*apk in Android  is the installation file similar to exe in windows.

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.

Share

You are always welcome to provide your comments and feedback from comment box.

Reference

Android GCM

[pgwriteforus]

[pgfeedback]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • Clay Martin

    Very informative. Thank you.

  • Thank you.

  • Deepak

    Reg file is not created in www/gcm.. App shows “Registered with GCM Server successfully” message after entering the email but again it shows “Unexpected Error occcured! [Most common Error: Device might “+ “not be connected to Internet or remote server is not up and running], check for other errors as well”,… Please help

    • Make sure:

      1. PHP web app is running fine in your local web server
      2. IP address has been changed to your machine IP in ApplicationConstants Class.
      3. File create permission exists in local web server

      Most probably the issue is with the PHP web app.

      • saurabh

        Hey i am also getting the same error when i run the app.

        i checked the php web app when i send a message it is showing a warning

        Warning: file_get_contents(GCMRegId.txt): failed to open stream: No such file or directory in C:wampwwwgcmgcm.php on line 37

        please help me with it

  • Christopher Ifechukwude Akpala

    would like to know after, after the user registers the app on the REGISTER activity, when the user starts up the app again those it ask for registration again?

  • kláda

    Thanks, finally i configured it right after 1,5 hour 🙂
    Not simple tutorial

  • Hi Klada,

    Yeah configuring GCM is not that easy. Anyway you configured it with great effort. 🙂

  • Have you created Php web app in your local server?
    App is designed in such a way that it will store the GCM ID in the web server after successful creation of GCM ID. If GCM is not stored in local web server (mostly you might not created Php web app as I mentioned in the tutorial), App will keep on asking you to register.
    I hope you got it.

    • Christopher Ifechukwude Akpala

      don’t really get it clearly…… lets say i start the app for the first time, the Registration activity is what i see first and i hit on the Register button and i successfully register, …..now if i start up the app again would i still be presented with the Register Activity first?

      • It won’t show Register screen again if you successfully registered already. Please debug the code and see where exactly the error occurs.

  • vishal mittal

    I have run the gcm app on mobile. when I click on register, it successfully registered and gcmId text file is generated in xamp/gcm folder but when I send the msg from web server(running php file) http://localhost/gcm/gcm.php, It give me error
    Unauthorized
    Error 401

    Please provide me solution

  • Ray

    Hi, I’m having problems with that
    client.post(ApplicationConstants.APP_SERVER_URL, params,

    new AsyncHttpResponseHandler() {

    How can i fix it ?? Thanks

  • ShivamDev

    Hi,

    Can you explain the Server part please as without it, it seems to be a half baked learning.

    Thanks

  • Krasimir

    Hi, gcm.getMessageType(intent) returns Null. I check it, that means “The message type or null if the intent is not a GCM intent” but I do not understand really. What to do?

  • Krasimir

    And my other question is how to do that on real device?
    I start a local Xampp server but every time I can not access my local server (Timeouted).

    P.S. My laptop and android device are connected to the same wifi network.

  • Kaynat Quadri

    It only send message to single device who lastely registered what if we want to send notifications to multiple device

  • You need to create new Server key and project key under your account. Use them in your project to resolve this issue.

  • Use your LAN IP address, instead of localhost. Thanks.

  • Jayaram

    Successfully registered my device in GCM server. but cant send message to my device from php file.

  • What error are you getting?

  • Write Media

    I’m getting something went wrong at the server end. Http response as 500

  • Christian Martinez

    I am having trouble importing the package com.google.android.gms.gcm.GoogleCloudMessaging. Please help me resolve it.

  • daiduong

    {“multicast_id”:9162652977736392884,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1441251874219048%8cbd98e5f9fd7ecd”}]}
    sending from server success but cannot receive anything on my device ? no error shows..pls help me ? i just copy your code and edit something base on my server and number project.

  • man

    GCMRegId.txt is not created in gcm folder. application shows (Unexpected Error occcured! [Most common Error: Device might “”not be connected to Internet or remote server is not up and running], check for other errors as well”, ). reg id is genereated all works fine bt that error occures which i just stated.

  • Yiu Ming Cheung

    Thanks, it works. Just want to save the message into database, can we do this in onReceive part ? Also, if I want to pop up a Toast when the gcm message has come, how can we add this code, in onReceive or onHandle? Your advice is highly appreciated.

  • Mathieu Decaffmeyer

    For existing apps that extend a WakefulBroadcastReceiver, Google recommends migrating to GCMReceiver and GcmListenerService. To migrate:
    * In the app manifest, replace your GcmBroadcastReceiver with “com.google.android.gms.gcm.GcmReceiver”, and replace the current service declaration that extends IntentService to the new GcmListenerService
    * Remove the BroadcastReceiver implementation from your client code
    * Refactor the current IntentService service implementation to use GcmListenerService
    https://developers.google.com/cloud-messaging/android/client

  • MD AAMIR AZAM

    How can i run php file in Apche server ? we need database for that

  • MD AAMIR AZAM

    please tell me this line :

    Try to run the gcm.php file on the Apache server and make sure it doesn’t throw any error. If your Apache server is not supporting the functions used in gcm.php, warnings and errors will be shown accordingly on browser. Fix it and then proceed to below steps.

  • Brian Pauma

    Hi, I’m also having problem with the same line of code. How can this be fixed?

  • Razaq

    I manage to get this working on localhost but when I uploaded the gcm.php file to my website it doesn’t work. My website uses a shared IP not dedicated IP so it is difficult to add an IP address to the server key. Is there anyway around this.

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares