In recent times, Google moved from Google Cloud Messaging (GCM) to Firebase Cloud Messaging (FCM). Just like GCM, FCM is a cross-platform messaging solution that allows you to send messages. FCM is completely free and there are no limitations.

If you have followed any of my previous tutorials about GCM, I strongly recommend you migrate to Firebase today itself. In this article we learn the features of firebase cloud messaging by building a simple app. We’ll also learn how to integrate firebase to your backend, so that you can send the messages from your server.


1. Firebase Message types

Using Firebase Cloud Messaging you can send three types of messages i.e Notification Message, Data Message and message with both Notification & Data Payload.

1.1 Notification Message:

Notification messages are handled by firebase SDK itself. Typically the notification message contains title, message, icon etc., These message can be sent from firebase console UI. By sending this kind of messages, you won’t get much control over the notification. The notification will be shown automatically when the app is in background.

In order to send notification message, you need to use notification key in json data. An example of notification message is given below.

	"to": "e1w6hEbZn-8:APA91bEUIb2JewYCIiApsMu5JfI5Ak...",
	"notification": {
		"body": "Cool offers. Get them before expiring!",
		"title": "Flat 80% discount",
		"icon": "appicon"

1.2 Data Message:

Data messages has to be handled by the android app. You can add this kind of messages if you want to send some additional data along with the notification. But sending these messages through firebase console is not possible. You need to have a server side logic to send the notification using Firebase API. You need to use data key when sending this message.

An example of data message json is given below.

   "to" : "e1w6hEbZn-8:APA91bEUIb2JewYCIiApsMu5JfI5Ak...",
   "data" : {
     "name" : "LG LED TV S15",
     "product_id" : "123",
     "final_price" : "2500"

1.3 Messages with both notification and data payload:

A message can also contains both notification and data payload. When these kind of messages are sent, it will be handled in two scenarios depending upon app state (background / foreground). For these message we can use both notification and data keys.

When in the background – Apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.

When in the foreground – App receives a message object with both payloads available.

An example of notification & data payload message will be

    "to" : "e1w6hEbZn-8:APA91bEUIb2JewYCIiApsMu5JfI5Ak...",
    "notification": {
		"body": "Cool offers. Get them before expiring!",
		"title": "Flat 80% discount",
		"icon": "appicon"
    "data" : {
     "name" : "LG LED TV S15",
     "product_id" : "123",
     "final_price" : "2500"

2. Message Targeting

While sending message using firebase, you can choose the targeted audience. You can send either to a single user or to group of users using a topic name.

2.1 Sending to Single User

When a single user targeted, the firebase registration id is used to identify the device. The reg id has to be mentioned in to filed of json.

  "to": "e1w6hEbZn-8:APA91bEUIb2JewYCIiApsMu5JfI5Ak...",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",

2.2 Topic Messaging

Topic messaging is useful when segment of users targeted for messaging. For this all the users has to subscribe to firebase topic. Ex: When you want to send message to all the users who are engaged with news, you can create a topic named news and send notification to news topic.

The request format of topic messaging is given below. In the to filed you need to mention the topic name.

  "to": "/topics/news",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",

3. Integrating Firebase Cloud Messaging

I hope the above information gave you good overview of firebase features and the options they are providing. Now we’ll create a simple app that receives firebase messages from both firebase console and from the PHP code.

1. First thing you need to do is go to and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.

2. Give the package name of your project (mine is info.androidhive.firebasenotifications) in which you are going to integrate the Firebase. Here the google-services.json file will be downloaded when you press add app button.


3. Create a new project in Android Studio from File β‡’ New Project. While filling the project details, use the same package name which you gave in firebase console. In my case I am using same info.androidhive.firebasenotifications.

4. Paste the google-services.json file to your project’s app folder. This step is very important as your project won’t build without this file.

5. Now open the build.gradle located in project’s home directory and add firebase dependency.

dependencies {
        classpath ''
        classpath ''

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

6. Open app/build.gradle and add firebase messaging dependency. At the very bottom of the file, add apply plugin: ‘’

dependencies {
    compile ''

apply plugin: ''

7. Create three packages named activity, app, service and utils under your project folder. Below is the structure and files required for this project.


8. Download notification.mp3 and place it in res β‡’ raw folder. This step is optional, but if you want to play a custom notification sound when notification received.

9. Create a class named under app package. This class contains all the constant values that we use across the app.


public class Config {

    // global topic to receive app wide push notifications
    public static final String TOPIC_GLOBAL = "global";

    // broadcast receiver intent filters
    public static final String REGISTRATION_COMPLETE = "registrationComplete";
    public static final String PUSH_NOTIFICATION = "pushNotification";

    // id to handle the notification in the notification tray
    public static final int NOTIFICATION_ID = 100;
    public static final int NOTIFICATION_ID_BIG_IMAGE = 101;

    public static final String SHARED_PREF = "ah_firebase";

10. Create a class named under utils package. This class contains necessary functions required to show the message (with title, message, image and timestamp) in notification tray.

package info.androidhive.firebasenotifications.util;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.util.Patterns;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import info.androidhive.firebasenotifications.R;

 * Created by Ravi on 31/03/15.
public class NotificationUtils {

    private static String TAG = NotificationUtils.class.getSimpleName();

    private Context mContext;

    public NotificationUtils(Context mContext) {
        this.mContext = mContext;

    public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) {
        showNotificationMessage(title, message, timeStamp, intent, null);

    public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
        // Check for empty push message
        if (TextUtils.isEmpty(message))

        // notification icon
        final int icon = R.mipmap.ic_launcher;

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        final PendingIntent resultPendingIntent =

        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(

        final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");

        if (!TextUtils.isEmpty(imageUrl)) {

            if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

                Bitmap bitmap = getBitmapFromURL(imageUrl);

                if (bitmap != null) {
                    showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
                } else {
                    showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
        } else {
            showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);

    private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();


        Notification notification;
        notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))

        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Config.NOTIFICATION_ID, notification);

    private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
        NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
        Notification notification;
        notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))

        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);

     * Downloading push notification image before displaying it in
     * the notification tray
    public Bitmap getBitmapFromURL(String strURL) {
        try {
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            return null;

    // Playing notification sound
    public void playNotificationSound() {
        try {
            Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://" + mContext.getPackageName() + "/raw/notification");
            Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
        } catch (Exception e) {

     * Method checks if the app is in background or not
    public static boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;

        return isInBackground;

    // Clears notification tray messages
    public static void clearNotifications(Context context) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    public static long getTimeMilliSec(String timeStamp) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format.parse(timeStamp);
            return date.getTime();
        } catch (ParseException e) {
        return 0;

11. Create a class named under service package. This class receives the firebase registration id which will be unique to each app. This registration id is needed when you want to send message to a single device. You can send this token to your server app to send notification to devices later.

onTokenRefresh() method will be called whenever there is a change in firebase registration id.

storeRegIdInPref() stores the registration id in shared preferences.

LocalBroadcastManager – Broadcast manager broadcasts the reg id to all the activities those are listening.

package info.androidhive.firebasenotifications.service;

import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;



 * Created by Ravi Tamada on 08/08/16.
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();

    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        // Saving reg id to shared preferences

        // sending reg id to your server

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", refreshedToken);

    private void sendRegistrationToServer(final String token) {
        // sending gcm token to server
        Log.e(TAG, "sendRegistrationToServer: " + token);

    private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("regId", token);

12. Create another class named under service package. This class receives the firebase messages into onMessageReceived() method.

> When notification type message is sent, firebase automatically shows the notification when the app is in background. If the app is in foreground, handleNotification() method handles the notification message.

> When data type message is sent, handleDataMessage() method is used to handle the payload irrespective of app state (foreground / background).

> LocalBroadcastManager is used to broadcast the message to all the activities which are registered for the broadcast receiver.

package info.androidhive.firebasenotifications.service;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;


import org.json.JSONException;
import org.json.JSONObject;

import info.androidhive.firebasenotifications.activity.MainActivity;
import info.androidhive.firebasenotifications.util.NotificationUtils;

 * Created by Ravi Tamada on 08/08/16.
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    private NotificationUtils notificationUtils;

    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());

    private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            // If the app is in background, firebase itself handles the notification

    private void handleDataMessage(JSONObject json) {
        Log.e(TAG, "push json: " + json.toString());

        try {
            JSONObject data = json.getJSONObject("data");

            String title = data.getString("title");
            String message = data.getString("message");
            boolean isBackground = data.getBoolean("is_background");
            String imageUrl = data.getString("image");
            String timestamp = data.getString("timestamp");
            JSONObject payload = data.getJSONObject("payload");

            Log.e(TAG, "title: " + title);
            Log.e(TAG, "message: " + message);
            Log.e(TAG, "isBackground: " + isBackground);
            Log.e(TAG, "payload: " + payload.toString());
            Log.e(TAG, "imageUrl: " + imageUrl);
            Log.e(TAG, "timestamp: " + timestamp);

            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("message", message);

                // play notification sound
                NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
                resultIntent.putExtra("message", message);

                // check for image attachment
                if (TextUtils.isEmpty(imageUrl)) {
                    showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
                } else {
                    // image is present, show notification with image
                    showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
        } catch (JSONException e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());

     * Showing notification with text only
    private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent);

     * Showing notification with text and image
    private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
        notificationUtils = new NotificationUtils(context);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);

13. Open AndroidManifest.xml and add the two firebase services MyFirebaseMessagingService and MyFirebaseInstanceIDService.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

                <action android:name="android.intent.action.MAIN" />

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

        <!-- Firebase Notifications -->
        <service android:name=".service.MyFirebaseMessagingService">
                <action android:name="" />

        <service android:name=".service.MyFirebaseInstanceIDService">
                <action android:name="" />
        <!-- ./Firebase Notifications -->

14. Finally we need to modify our main activity to display the incoming messages on the screen. Open layout file of main activity activity_main.xml and modify the layout as below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""

        android:textSize="26dp" />

        android:layout_alignParentBottom="true" />

15. Open and do the below necessary changes. Here in onResume() method we are registering the broadcast receivers. So that this activity gets the push messages and registration id.

displayFirebaseRegId() fetches the firebase registration id from shared preferences and displays it on the screen. This is just for your references, we don’t use the reg id any where in the app.

Subscribing to Topic

When you want to subscribe to any topic, subscribeToTopic() function can be used. When a client app subscribes to a new topic name (one that does not already exist for your Firebase project), a new topic of that name is created in FCM and any client can subsequently subscribe to it.


Unsubscribing from Topic

Similarly the client can unsubscribe from a topic by calling unsubscribeFromTopic() method.

package info.androidhive.firebasenotifications.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;


import info.androidhive.firebasenotifications.R;
import info.androidhive.firebasenotifications.util.NotificationUtils;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView txtRegId, txtMessage;

    protected void onCreate(Bundle savedInstanceState) {

        txtRegId = (TextView) findViewById(;
        txtMessage = (TextView) findViewById(;

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications


                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();



    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
            txtRegId.setText("Firebase Reg Id is not received yet!");

    protected void onResume() {

        // register GCM registration complete receiver
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened

    protected void onPause() {

Now we have completed the integration of firebase cloud messaging. In order to verify it, run the project and you should see the firebase reg id on the screen. You can also find the reg id in LogCat.


4. Sending Messages from Firebase Console

Now we’ll send the first message from firebase console. Go to firebase console and click on Notifications in left menu. You will get an interface where you can type the message, select the targeting and send the message.


5. Sending Messages from PHP Backend

Sending message from firebase console is not always an optimal solution for lot of apps. Huge number of apps requires an automatic notification to user whenever there is an event, which is not possible using firebase console. To overcome this problem you need to integrate the firebase API from your backend server.

Let’s create a simple PHP project to send the messages from backend. I am assuming you are having basic knowledge of PHP and WAMP. If you are new you can get the help from this article.

5.1 Obtaining your Firebase Server API Key

Firebase provides Server API Key to identify your firebase app. To obtain your Server API Key, goto firebase console, select the project and goto settings, select Cloud Messaging tab and copy your Server key.


1. Goto your WAMP directory and create new folder named firebase inside htdocs or www.

2. Create a file named config.php and add the below code. Here we define the firebase Server API Key to send request to firebase endpoint.


// Firebase API Key
define('FIREBASE_API_KEY', 'AAAA4qJeE5A:APA91bGct--6lGrYwgBC8iz5reyx4qPUB7ByXX8MwC7Vcs8u...');

3. Create a file named push.php This class prepares and the push notification json that needs to be send to firebase.


 * @author Ravi Tamada
 * @link URL Tutorial link
class Push {

    // push message title
    private $title;
    private $message;
    private $image;
    // push message payload
    private $data;
    // flag indicating whether to show the push
    // notification or not
    // this flag will be useful when perform some opertation
    // in background when push is recevied
    private $is_background;

    function __construct() {

    public function setTitle($title) {
        $this->title = $title;

    public function setMessage($message) {
        $this->message = $message;

    public function setImage($imageUrl) {
        $this->image = $imageUrl;

    public function setPayload($data) {
        $this->data = $data;

    public function setIsBackground($is_background) {
        $this->is_background = $is_background;

    public function getPush() {
        $res = array();
        $res['data']['title'] = $this->title;
        $res['data']['is_background'] = $this->is_background;
        $res['data']['message'] = $this->message;
        $res['data']['image'] = $this->image;
        $res['data']['payload'] = $this->data;
        $res['data']['timestamp'] = date('Y-m-d G:i:s');
        return $res;


4. Create a file named firebase.php and add the below code. This class contains necessary functions to send message to firebase api by making a CURL request.


 * @author Ravi Tamada
 * @link URL Tutorial link
class Firebase {

    // sending push message to single user by firebase reg id
    public function send($to, $message) {
        $fields = array(
            'to' => $to,
            'data' => $message,
        return $this->sendPushNotification($fields);

    // Sending message to a topic by topic name
    public function sendToTopic($to, $message) {
        $fields = array(
            'to' => '/topics/' . $to,
            'data' => $message,
        return $this->sendPushNotification($fields);

    // sending push message to multiple users by firebase registration ids
    public function sendMultiple($registration_ids, $message) {
        $fields = array(
            'to' => $registration_ids,
            'data' => $message,

        return $this->sendPushNotification($fields);

    // function makes curl request to firebase servers
    private function sendPushNotification($fields) {
        require_once __DIR__ . '/config.php';

        // Set POST variables
        $url = '';

        $headers = array(
            'Authorization: key=' . FIREBASE_API_KEY,
            'Content-Type: application/json'
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));

        // Close connection

        return $result;

5. Finally create a index.php and add the below code. Here we are creating a simple UI which takes the input and send the notification to android device.

        <title>AndroidHive | Firebase Cloud Messaging</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="shortcut icon" href="//">
        <link rel="stylesheet" href="">

        <style type="text/css">
                width: 1000px;
                margin: 0 auto;
                position: relative;
                font-size: 30px;
                color: #555;
                background: #00bcd4;
                margin:10px 0px !important;
                resize: none !important;
                width: 400px;
                position: absolute;
                right: 0;
            pre, code {
                padding:10px 0px;
                white-space: pre-wrap;  
                white-space: -moz-pre-wrap; 
                white-space: -pre-wrap; 
                white-space: -o-pre-wrap; 
                word-wrap: break-word; 
                width:100%; overflow-x:auto;

        // Enabling error reporting
        ini_set('display_errors', 'On');

        require_once __DIR__ . '/firebase.php';
        require_once __DIR__ . '/push.php';

        $firebase = new Firebase();
        $push = new Push();

        // optional payload
        $payload = array();
        $payload['team'] = 'India';
        $payload['score'] = '5.6';

        // notification title
        $title = isset($_GET['title']) ? $_GET['title'] : '';
        // notification message
        $message = isset($_GET['message']) ? $_GET['message'] : '';
        // push type - single user / topic
        $push_type = isset($_GET['push_type']) ? $_GET['push_type'] : '';
        // whether to include to image or not
        $include_image = isset($_GET['include_image']) ? TRUE : FALSE;

        if ($include_image) {
        } else {

        $json = '';
        $response = '';

        if ($push_type == 'topic') {
            $json = $push->getPush();
            $response = $firebase->sendToTopic('global', $json);
        } else if ($push_type == 'individual') {
            $json = $push->getPush();
            $regId = isset($_GET['regId']) ? $_GET['regId'] : '';
            $response = $firebase->send($regId, $json);
        <div class="container">
            <div class="fl_window">
                <div><img src="" width="200" alt="Firebase"/></div>
                <?php if ($json != '') { ?>
                    <div class="json_preview">
                        <pre><?php echo json_encode($json) ?></pre>
                <?php } ?>
                <?php if ($response != '') { ?>
                    <div class="json_preview">
                        <pre><?php echo json_encode($response) ?></pre>
                <?php } ?>


            <form class="pure-form pure-form-stacked" method="get">
                    <legend>Send to Single Device</legend>

                    <label for="redId">Firebase Reg Id</label>
                    <input type="text" id="redId" name="regId" class="pure-input-1-2" placeholder="Enter firebase registration id">

                    <label for="title">Title</label>
                    <input type="text" id="title" name="title" class="pure-input-1-2" placeholder="Enter title">

                    <label for="message">Message</label>
                    <textarea class="pure-input-1-2" rows="5" name="message" id="message" placeholder="Notification message!"></textarea>

                    <label for="include_image" class="pure-checkbox">
                        <input name="include_image" id="include_image" type="checkbox"> Include image
                    <input type="hidden" name="push_type" value="individual"/>
                    <button type="submit" class="pure-button pure-button-primary btn_send">Send</button>

            <form class="pure-form pure-form-stacked" method="get">
                    <legend>Send to Topic `global`</legend>

                    <label for="title1">Title</label>
                    <input type="text" id="title1" name="title" class="pure-input-1-2" placeholder="Enter title">

                    <label for="message1">Message</label>
                    <textarea class="pure-input-1-2" name="message" id="message1" rows="5" placeholder="Notification message!"></textarea>

                    <label for="include_image1" class="pure-checkbox">
                        <input id="include_image1" name="include_image" type="checkbox"> Include image
                    <input type="hidden" name="push_type" value="topic"/>
                    <button type="submit" class="pure-button pure-button-primary btn_send">Send to Topic</button>

6. Access the project from your http://localhost/firebase url. (If your apache is running on a port, access the url using port number)


6. Demo

If you are new to PHP and facing any issue while running the above PHP project, you can access the same project here. The UI is same as explained above except few changes. You need to provide your own firebase Server API Key to test your app. Check the video to know how to use the demo page. Don’t worry about exposing your Server API Key, your data is not stored in any manner in the demo page.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • vinu

    alertDialog.setIcon((status) ? R.drawable.success : when ever the code containing “R.———“some thing like R.drawable.success is taking as error how can i overcome it.

  • rahul

    hi ravi thnx for this nice tutorial

  • DaCan

    Great tutorial. Works for me. Thanks a lot.

  • danny

    I can register via my mobile but when i send a message from the computer browser i receive nothing on my mobile. any help please?

  • Dharmsh Kuhadiya

    hi Ravi

    Great Tutorial . but when server send message to Application .
    protected void onMessage() ….not calling .. I don’t know why…. plz help

    • verstian

      have u solved this issue? if yes then plz guide

  • Dharmesh

    hi Ravi plz help . Deveice Register but not receive push notification …

    • have you run on Mobile?

      • Its working on Mobile Successfully………

        • sam

          In my case also not working on device (nexus 4). I used same code just change server url and sender id.

  • mikrosmile

    Hello Ravi. Great great tutorial. Everything is perfect. Guys download source code, create php files on your server and run. It works great on the phone rather than in emulator. But i have a wuestion. How and is it possible to make one button for sending message and it will send to all registered users? Coz when you have 100 users it is not convinient to do send message 100 times

    • Guest


      I’m kinda working on a similar app, but could you tell me how you were able to get the ip address for the ‘SERVER_URL’, coz my localhost ip address is, but in the tutorial Ravi’s changed it to (which i’m guessing is his localhost ip address).

      Basically how did u manage to connect you phone to the demo server?


  • vinod kumar

    Hi ravi i am new to android apps. i was facing a problem that the following methods are deprecated

    PowerManager.FULL_WAKE_LOCk method in wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK

    SetButton method in

    alertDialog.setButton(“OK”, new DialogInterface.OnClickListener()

    Notification notification = new Notification(icon, message, when);

    notification.setLatestEventInfo(context, title, message, intent);

    The highlighted methods are showing the methods are deprecated.i was unable to resolve these please help me out….

  • Vidhya

    Great tutorial. Was able to get this working. Thanks!

  • Thanks, but it so difficult like for me. You can try a little bit easier code

  • linto cheeran

    it’s owesome ..

  • danny

    How can the php code be modified in order to have 1 common message for a different number of registered devices and 1 submit button ?

    • kritika kapoor

      hi… did you find the answer…??? plz help if yes…

      • danny

        no not yet

        • kritika kapoor

          ok. thanks.

  • androidituts

    Android notificatication helps the user to view the notification up to date.

    To learn ANDROID from the beginning onwards


  • Michael

    Thanks for the example. It was very helpful.

  • Kris
  • Usama Sarwar

    I am getting the same prob. Have you solved it yet?

    • Uddhav

      same issue?Any luck?

      • andrei

        same here, has anyone found the solution?

        • Shrikant

          It’s not an error go to localhost/gcm_server_php you will see register devices.

  • draffo3

    For those not getting the notifications after registering successfully make sure you are using the browser API key and not the key for server apps, that worked for me, I have not tried the key for Android devices

  • xavi!

    hi am doing an app for resturant ordering my prob is that when orders r send to the server (mysql) from the app and the order is ready to serve a notification should come in app stating that order is complete when a button is clicked into the webpage (kitchen)
    how to get this notification into the android app from a server??does this code helps ??
    or any other things r reqiuerd?
    plzz hepl!

  • Ignacio

    Hi Ravi,

    Great tutorial. I’m having problems with the android app. I’m getting the following error when I try to register my name and my email to the server.
    Could you help me?


    04-04 22:10:06.538: E/AndroidRuntime(851): FATAL EXCEPTION: main

    04-04 22:10:06.538: E/AndroidRuntime(851): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gcmpush/com.example.gcmpush.MainActivity}: java.lang.UnsupportedOperationException: Device does not have package

    04-04 22:10:06.538: E/AndroidRuntime(851): at

    04-04 22:10:06.538: E/AndroidRuntime(851): at

    04-04 22:10:06.538: E/AndroidRuntime(851): at$600(

    04-04 22:10:06.538: E/AndroidRuntime(851): at$H.handleMessage(

    04-04 22:10:06.538: E/AndroidRuntime(851): at android.os.Handler.dispatchMessage(

    04-04 22:10:06.538: E/AndroidRuntime(851): at android.os.Looper.loop(

    04-04 22:10:06.538: E/AndroidRuntime(851): at

    04-04 22:10:06.538: E/AndroidRuntime(851): at java.lang.reflect.Method.invokeNative(Native Method)

    04-04 22:10:06.538: E/AndroidRuntime(851): at java.lang.reflect.Method.invoke(

    04-04 22:10:06.538: E/AndroidRuntime(851): at$

    04-04 22:10:06.538: E/AndroidRuntime(851): at

    04-04 22:10:06.538: E/AndroidRuntime(851): at dalvik.system.NativeStart.main(Native Method)

    04-04 22:10:06.538: E/AndroidRuntime(851): Caused by: java.lang.UnsupportedOperationException: Device does not have package

    • I have the same problem, anybody can help me ?

      • Dixon Cano

        al parecer falta agregar la libreria gcm.jar al proyecto.

      • Shan

        same problem for me too! Any clue?

    • Emulator

      Use an emulator which supports Google API. Create a new emulator for that.

    • Elie GAKUBA

      This error can happen if you didn’t add the gcm.jar into java build path. to do so please copy the gcm.jar to libs folder in your project. then open eclipse and navigate to the libs folder. right click the gcm.jar ->build path->configure path-> order and export. tick the gcm.jar then apply. remember to refresh the libs folder.

    • iwillhuntyou

      try to check your config.php

      define(“GOOGLE_API_KEY”, “AIzaSyALJIjDuCQo6Wp01xVwZNBsw2z7BzAGa3A”); // Place your Google API Key

      change the API key by your own key given to you.

  • Srinath

    Really a nice tutorial and it works fine πŸ™‚

  • John

    thanks .Its successfully working for me

  • Raj

    Awesome tutorial and thanks a lot for the whole explanation Ravi.

    Just had a question, how do you get ip address for the server_url? coz my wamp server has the localhost ip address, (, which doesn’t seem to work, I am able to get the device to register with the GCM server, but wit the test demo it doesn’t work, it trys 5 times and then quits.

    Any help would be much appreciated,

    Thank you πŸ™‚

    • Raj

      its ok, i found the solution, I am now able to register with my demo server, but now i don’t get a message on the phone, when i tried send one.

      Anyone know wot the issue might me?

      • Raj

        Got it fully, thanks again Ravi for the code and tutorial u’ve provided here. πŸ˜€

    • android_cro

      when you are connecting through Android to localhost, IP address isn’t 127.x.x.x but

      • Raj

        yh tired that when it wasn’t working, but i got it working now. thanks anyways

  • VDev

    Hi Ravi,

    I receive the notification, when I click on it, I receive “you are already registerd with gcm” , but if I keep the window open and send another message, the message is shown correctly. Please help

  • Fresher

    Can u please implement the server side programing in java?

  • Amol

    whats the problem with downloading…. ????????

  • HM

    Hi,Thank you for this tutoriel πŸ™‚ I wanted to add a “unregister” button in case the user want to unsubscribe so i use the method you already wrote but i want it to remove the entry from the database too,is it possible?

  • Amol

    i am getting force close error

    and i have no idea why ???

  • krishna

    i’m getting this error ……….. :(.. and which one is a gcm_registration id ?

    Error 401

    i tried, project id, and api keys (server and browser)… but still getting a problem i reached nearly but am struck with this place.. please help me..

  • Hasan

    Best tutorial ever on GCM with PHP. If you get this tutorial then you can feel lucky enough that it will save your several days of development and from lots of frustration.
    Many Many thanks.

  • kwishnu

    Incredibly helpful…I eventually got it working after going through it with a fine-toothed comb, which is the way a tutorial should be! Sometimes I don’t understand why people post such massive amounts of work for others to use, but I’m sure grateful that they do…thank you!

  • Hello Ravi,

    Its Very Nice Tutorial, Thank you.

    There is one problem, My device is registered successfully but didn’t get Push Notification.

    What can i do for that, Please suggest…..

    • Hey, I got Solution., This is Successfully working on Mobile

      • Thamilvanan Go

        Hi .i got message like From Demo server:succesfully added device .but i dint get any push notification .so i checked my gcm_users table there is no data inserted in that DB.

  • naresh


  • Syed Imran Raza

    Same problem…..

  • Anele Ivanova


    Recently I came across some great articles on your site.

    The other day, I was discussing ( my colleagues and they suggested I submit an article of my own. Your site is just perfect for what I have written!

    Would it be ok to submit the article? It is free of charge, of course!

    Let me know what you think

    Contact me at

    Anele Ivanova

  • Yan

    I got the solution for not sending message to device.
    Copy and paste the Fixed curl extensions:
    from this link

    and PHP->PHP extension-> and tick the php_curl

    Restart you wamp server.
    It’s done!!

    • Aladin

      Thank You very much !
      you’ve been so helpfull

  • namdhis

    You’re awesome! Thanks! πŸ™‚

  • Pinki

    Hello Ravi,

    This is a fantastic sample, well explained. I too have developed an App with push notifications using php server. It works well, but sometimes few device get notifications twice. I have done an array_unique before sending the reg ids, not sure what could be causing this issue. Majority of devices get once but few of them get it twice. Please thro some light on this issue.

  • Ivan

    Nice tutorial.. I have a problem on the method of ConnectionDetector.. how isConnectingToInternet return false? I have disable my wifi internet connection but still it return true. How is that possible?

    Please help.. thanks in advance.

  • jean

    nice tutorial but what if your running newer version of android sdk like 4.2 ???? help plzz i am doing this for a senior project

  • Kash

    Brilliant… Thanks

  • dashing

    When trying in my pc’s localhost it wasn’t working. But when I put the PHP script on a real server it worked like a charm =)

    • oth

      yes mainly because you will not have permissions to access your localhost from another terminal

    • Arief Abdul Aziz

      HI dashing would you please tell me how u can use on a real server to create GCM from this source code website #step by step or tutorial…because I still not working on a real server but working on a emulator android

  • Luis

    Buenas tardes, gracias por compartir tus conocimientos, Fijate que descargue el codigo y lo he probado cada cosa la he configurado como tu dices pero me da un error dice que la aplicacion tuvo que ser detenida, me gustaria que me dijeras mas o menos porque puede ser, ta agredezco tu ayuda

  • You could explain how to get the public ip and how to open ports so that was complete.

  • Thamilvanan Go

    Hi Ravi,

    Am having problem with getting push notification:

    i am getting message like From demo Server:Successfully added Device .
    but in the browser am not able to get the registerd devices it showing 0(Zero).
    so there is no insertion happend at users table.what would be the problem.

  • Pratyush

    For Push Notification, I am a server side devloper, My requirement for GCM Push Notification is to get Register Id on server side. So, Can we register on GCM on Server Side, please suggest me on this.

  • Nadeem Khan

    Thank you very much….

  • andy

    This tutorial is awesome. Thanks!!

  • Cesar

    did u get some response? im totally clueless about this

  • KashifB

    Used .Net instead of php and made it work. Very helpful example.
    Now is there an example to send a response back to the website/server from the Android app?

  • jean

    hello ravi , we tried the code , the device gets registered successfully but it still shows 0 devices registered( we are running xamp and have enabled curl) plz help

    • Victor

      Hi. I have the same issue. It seems to register the user but there is no user in Database.

      The Log shows

      :05-02 00:12:06.697: V/GCMBaseIntentService(26002): Acquiring wakelock

      as the last line, but there is no error line before.

      I have checked every line, I have tried it in two different web servers…

      I am a bit hopeless. Can anyone help us?

      • mrhungonline

        I know this issue. You must go to file config in server then put use and pass of SQL (in default. user: “root”, pass “” <– empty). hope this will help.

  • joker

    yes .. me to sir

  • rendy

    how to connecting?

  • BaiKin

    It does seem like this is, indeed, leftover from a tutorial. After some reading and testing, I’ve found that this is a key-value pair sent as an Extra in the Intent received by the onMessage(Context context, Intent, intent) method in the GCMIntentService class.

    Both the key in this array (currently, “product”) and the key in the onMessage() method on your GCMIntentService class (currently, “price”) should be the same for it to actually show a message. Note that a similar array is defined in the send_message.php file, whose key should also be the same as the others.

    If they’re not all the same, you’ll be getting “null” as the message received by your app.

  • BaiKin

    Hi Ravi,

    This is great, thanks for all your work putting this together for all of us.

    A lot of people are having problems with receiving messages after a successful registration. I also had them, and after checking WAMP’s log files, it seems it had not been properly configured to use the php_curl extension. Even after turning it on (wamp->PHP->PHP Extensions->php_curl), it still wasn’t working.

    I checked the log again, and my System, for some reason, couldn’t find the php_curl.dll, even though it was clearly there in C:/wamp/bin/php/php5.3.13/ext. I did some digging, and apparently there’s a bug involving wamp, php_curl and Windows 7 x64. I did a two things, but I don’t know if they were both necessary:

    Install Apache 2.2.9 addon version from WAMP site.
    Download a “fixed” curl extension from . The Thread-Safe version worked for me (the other one didn’t)

    Also, enable curl in your php.ini file in your php folder.

    Hope this solves some people’s problems.

  • tjvanderende

    Any idea why it keeps saying: … stopped working?: p
    Did everthing well…. like the tutorial is saying.

  • Fabse


    thank you!
    Everything work fine, but I have two question.
    If I receive a message it will be shown in the statusbar. If I click on the message it opens the app and a message comes up with “Already registered with GCM”.

    But my received message is not there. If I stay in the app and receive a message, then the message is shown in the app. How can I solve this problem, that always a received message is shown in the app and not just when I have the app open?

    The second thing is, how can I change the Textview into a Scrollview. If I change the Textview into a Scrollview I’ll get an error at this line (MainActivity!): lblMessage.append(newMessage + “n”);

    Thank you!

    • BaiKin

      When you press on the notification, it merely starts MainActivity based on the Intent passed as pendingIntent to the notification, in the method generateNotification.

      If you simply want it shown when you open the app through the notification, the following will work:

      In the method GCMIntentService.generateNotification(), look for the line

      Intent notificationIntent = new Intent(context, MainActivity.class);

      and add this line right after it:

      notificationIntent.putExtra(“message”, message);

      Now go to your MainActivity.onCreate() method. In it, look for

      messageTextView = (TextView) findViewById(;

      and add this line right after it:


      This way, you’re putting the message as an extra to the intent that starts your MainActivity when you press on your notification. Then, you’re retrieving this extra in your MainActivity class. This is probably not the best way to do it, but it should help you understand how it works.

      As for the ScrollView, it is actually a FrameLayout, not really something that could replace a TextView. You should read up on ScrollViews in the android documentation.

      • Fabse

        thank you for the fast reply. I have still a problem. The code works sometimes and sometimes it just stands one old message in the Textview.
        Do you know why?

        Thank you!

        • Fabse

          Did somebody solve this problem?
          I still have it πŸ™

          • Alessandro Universus

            I have your same problem…

          • Fabse

            Could you solve it?

  • Guest

    Hello Ravi……
    Its a great tutorial…….But I have some error….Whenever i tried to register device on server it working perfectly but after check send message.php file with registration id i have got “Unauthorized error” everytime… I have check many times but still that issue occured..

    So please help out me…

  • Piyush Gupta

    Hello Ravi……
    Its a great tutorial…….But I have some error….Whenever i tried to register device on server it working perfectly but after check send message.php file with registration id i have got “Unauthorized error” everytime… I have check many times but still that issue occured.. And also not getting a notification.

    So please help out me…

  • khaled al

    Hi mr.Ravi, thank you so much for this tutorial , but I just would to ask about how to implement the php code to send a notification to all user registered at once … any one can help please ???

    thanks in advance.

  • tjvanderende

    Man… im tired of trying it,
    How to use this to send with one form to multiple devices?
    I don’t get it to work…. its so frustrating.

    Please someone post the code here.

  • gowtham

    I too have the same Problem Please help me !

    • gowtham

      Not Got Resolved … i did mistake in register.php file … i forget to give ” <?php " Now i resolved it .. It works Fine

  • Gowtham

    It will be in Only Android 2.3.3 only ..And you can’t add your account in Emulator which is having target 17…So Better to use Google API Emulator !

  • gowtham

    Am also having the Same Error …Please help me too

  • Chandan

    Hi Ravi,

    I have a question-
    Can you tell me how to run this app on mobile device??
    There’s some problem with
    Instead of this address what address should be used??

    Please help me with this.



  • Gobinath

    Hi i din recieve the null message at the time of registration , sometime it works well but sometimes i got the error, what step i ve to taken to overcome this.

  • Tobbbe

    I get “Error=MissingRegistration” when I try to run my code in the browser. Anyone know what this means?

  • Ram

    Great tutorial. I have a doubt,When application uninstall and once again installed, the id is storing once to prevent that?

  • Did you solved this problem? I’ve the same problem…someone help me!!!

    • Charbel Sarkis

      was this solved?

  • Pankaj Kargirwar

    You are awesome! You took so much efforts to clearly explain a potentially complex topic. I could get up and running in no time. Many thanks!

  • villarino

    I already change the static final String SERVER_URL to point to my server but the app still pointed to

    How I fix this problem?


  • pablo

    Hi Ravi, great tutorial, I have modifiaed it to my needs and its, working great on my server. I have one question.
    How can I send the same message to all users at the same click of send button?
    Thanks I follow your blog allmost every day, really learning a lot.

  • pablo

    Hi Ravi, thanks a lot for your tutorial, ItΒ΄s working perfect..
    One question, how can I send one message to all users at the same time?
    thanks for your great work.

  • Vilasmati Hanjagi

    Hi Sir ,

    Very thankful for Great Tutorial.

    I am getting error like

    05-21 14:15:11.508: E/GCMRegistrar(487): internal error: retry receiver class not set yet

    Even I went through link which you gave!topic/android-gcm/riAFIyyUIR0 but I did not get actually where should I change the code . So Please do help me to solve this issue.I am new for android

  • i do all steps but i got errosr in all clases is the skd version ? i cant run the app as i got erros please help

  • Ravi, still waiting for your expert code to send push notification to multiple devices in one go.
    pl update soon

  • Steven

    Thanks for the tutorial, I haven’t tested it because I can’t create a google account. I can’t find account and sharing menu on setting in my emulator. All I can find is just account and I tried to click it multple times it done nothing. Could you help me? I’m using galaxy nexus as my device and android 4.2(API17)

    • Steven

      Oh, and when I tried running it though knowing it won’t work I got a noclassdeffounderror on Is it because I haven’t set up a google account? Or is it I picked the wrong device to use as an emulator? Please someone help me

  • ask

    Hi Ravi,
    This post is very helpful. Thank you very much. And please help for one thing. How can i send messages to over 1000 resisted ids at one time.?

  • Kaka

    Am testing the system on a real server and getting the following error: {“multicast_id”:6627181175318861228,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]} from test.php->register.php

  • Jaya Prakash

    Hi Ravi,
    Same problem arised to me. The application is registered successfully in server. But while sending any messages from server, the emulator doesn’t receive anything. i have enabled php_curl and activated google account in emulator. Still clueless why the emulator doesn’t receive anything. Please help me to solve this problem.

    Many thanks in advance.

  • Claudio Suriano

    Ravi!!! man!! it works perfect!!! I did what u say and worked really good!!! Man I have one question.. When I uninstall the app I still see the registered user. Why?

  • Claudio Suriano

    That’s because android works in another subnet.
    1) Connect your phone to WIFI.
    2) You have to execute cmd in your pc, then ipconfig, and search for the router address. IPv4: or something like that. Then you have to replace in android SERVER_URL, inside GCMIntentService, localhost by
    3) If you are executing ECLIPSE PHP to run the index.php you have to modify the file php.ini inside C:wampbinapacheapache2.2.22bin. You have to delete “;” in the line: ;extension=php_curl.dll.

    =D My english suck.. I hope this help you!

  • Claudio Suriano

    If you test in a real server this work. But, if you want a quick solution you have to… 1) Connect your phone to WIFI.
    2) You have to execute cmd in your pc, then ipconfig, and search for the router address. IPv4: or something like that. Then you have to replace localhost by in SERVER_URL, inside GCMIntentService class.

    • Anas Azeem

      It isn’t working even with this solution. I’ve tried everything I could do but no help.

  • Jaya Prakash

    i have changed api key. Will this create any problem???…

  • FranΓ§ois

    Hi Ravi,

    Thank you very much for your tutorial, it’s really helping πŸ™‚

  • Jaya Prakash

    Push notification not working in my emulator. I am newbie to android. HELP ME!!

  • Asif

    Rly Superb tutorial….Helpd lot.. Keep on going

  • Abeva H

    Hello guys how can send and get data1 and data2 from index as here..

  • Karim

    Wow, this tutorial is awesome! Just wanted to say thank you for such great work.

  • Khalid

    Hi Ravi, This is great tutorial, thank you so much.
    I have one question about sending multicast message, I am not sure if its correct or no, but do I just loop through all the registered id’s and send the message or there is other efficient way to do this πŸ™‚ ?

    I noticed in the comments several guys asking about why messages not received, in my case I did have the same issue while I am playing with code and it was because I changed the array id. So If you changed the array id (“Price”) on the php side, just make sure to match it with receiver side on the android app, otherwise you wont see the message

    $message = array(“price” => $message);

    The reciever on the andorid app.

    String message = intent.getExtras().getString(“price”);

    Thank you again

  • Poldek

    Thank you very much,

    missing one entry AndroidManifest.xml

    solves the problem “java.lang.NoClassDefFoundError:”

  • CMiklos

    Hi Ravi!

    I have tested the code in this post and it works very well.
    I want to use it in a project and hire you to make some modifications. Please contact me to talk about it. Thank you!

  • dragnovich

    According to the past Google I/O now you can use GCM bidirectionally…. can you create an other tutorial (extending this one) of how to respond from the android to the server?? maybe a practicall simple chat app.

    two links.. ( by google I/O 13 )

  • Anonymous

    Hii I am able to register myself at the server but any message sent from the server is not being displayed as a notification . The code used is exactly as yours. I get the feeling that GCMIntentBasse is not being callled. Can you please help me out

  • Thushara

    Hi Ravi ,

    Thank you soo much..Very helpful tutorial.


  • Karthik

    Hi Ravi,

    This post works nice when i use database in localhost phpmyadmin but it does not work in php remote server. Can u help me how to solve this.

    Thank You,

  • kryton

    Hi all,
    everyting works but when I send messages from server.. they don’t arrive to the smartphone.. Why?

  • ε››ηΆ­ εŒ…


    $fields = array(

    ‘registration_ids’ => $registration_ids,

    ‘data’ => $message,



    $fields = array(

    ‘registration_ids’ => $registration_ids,

    ‘data’ => array(‘message’ => $message),



    • isiah

      what fixed this codes?

  • isiah

    Thanks for the post but
    I’m getting this when using register.php {“multicast_id”:7235513441541753972,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}

    can you help me solved this error?

  • isiah

    Hey did you solved this problem yet?

  • isiah

    Hey Ravi do you already update your codes to send it to multiple devices?

  • frans.yunet

    dear ravi

    1. how to delete a registered (gcm_regid) device in GCM ? because in mysql-php (gcm_regid) is not exist..

    2. and how to re-registered deviced again ?


  • Kent

    I can’t download source code. Help me, please!

    • francois

      You juste have to put your mail and after it’s funny.
      Thanks Ravi for this tuto πŸ™‚

  • jawad ibrahim

    hi sir, I’m kind of new android developer, I’ve installed this code and it’s now working so nice; but there is one problem and i cant get how to fix it.

    The problem is that i receive the messages on “collapsible” mode , the new message overwrite the old message.

    after reading your code i saw that you send the message in a “payload” manner but still i don’t get the problem location and how to solve it. can you help me with that

  • Mickey

    It work perfectly

  • Manoj

    Hi Ravi,

    i have tried to implement the above code ,but for some reason i could not get it to work.

    when i tried to run the php file “gcm_server_php/” i am getting the following error.

    ( ! ) Warning: mysql_connect() [function.mysql-connect]: MySQL server has gone away in C:wampwwwgcm_server_phpdb_connect.php on line 19Call Stack#TimeMemoryFunctionLocation10.0004376176{main}( )..index.php:020.0009394320DB_Functions->__construct( )..index.php:9830.0012400528DB_Connect->connect( )..db_functions.php:1340.0014401144mysql_connect ( )..db_connect.php:19

    ( ! ) Warning: mysql_connect() [function.mysql-connect]: Error while reading greeting packet. PID=7876 in C:wampwwwgcm_server_phpdb_connect.php on line 19Call Stack#TimeMemoryFunctionLocation10.0004376176{main}( )..index.php:020.0009394320DB_Functions->__construct( )..index.php:9830.0012400528DB_Connect->connect( )..db_functions.php:1340.0014401144mysql_connect ( )..db_connect.php:19

    ( ! ) Warning: mysql_connect() [function.mysql-connect]: MySQL server has gone away in C:wampwwwgcm_server_phpdb_connect.php on line 19Call Stack#TimeMemoryFunctionLocation10.0004376176{main}( )..index.php:020.0009394320DB_Functions->__construct( )..index.php:9830.0012400528DB_Connect->connect( )..db_functions.php:1340.0014401144mysql_connect ( )..db_connect.php:19

    ( ! ) Fatal error: Maximum execution time of 30 seconds exceeded in C:wampwwwgcm_server_phpdb_connect.php on line 19Call Stack#TimeMemoryFunctionLocation10.0004376176{main}( )..index.php:020.0009394320DB_Functions->__construct( )..index.php:9830.0012400528DB_Connect->connect( )..db_functions.php:13

    Could u pls tell me where i went wrong.

    Thanks in advance.

  • Sonia

    hi there, i can’t solve this and it is happen in a mobile device instead of emulator. cause i am testing on mobile device but didn’t able to get the notification sent from server side. Please give me some hint on this if you know the solution. Thanks alot!

  • Rikhil Jain

    Hello Sir,

    I have implement your code on live server. It’s working pretty fine. Great !!

    My problem is that I want to send the same message to all the register user how can I do this. I am not php developer but doing this. I am an android developer so I will be a good help from your side if you help me in this.

    • Joannes A. Rommers

      Did you find an answer to this?

  • Henry

    Hi Ravi,

    Great Tutorial.

    But I found that the Classes of GCMBaseIntentService and GCMRegistrar are deprecated in below website.


  • Soubhab

    Hi Ravi

    Awesome tutorial …. based on your tutorial I am able to set up a java server running on apache Tomact and everything is working successfully …..

    Thanks a lot …

  • Soubhab

    One of the best tutorial ..

    Thanks once again ….

  • Charbel Sarkis

    I am facing the same problem. did anyone find a solution?

  • GreatCoder

    I have used Push notification code and have PHP server for pushing messages. Sometimes the messages get delivered multiple times, Everytime an app is installed and uninstalled multiple times on a device and is registered with google server many times still the push ID provided by google remains same, but canonical ID is provided by google. Google says multiple delivery issues can be solved using this canonical id. Please throw more light on this. Thanks..

  • Ricardo

    Great tutorial!!

    But i am a bit confused, this tutorial use deprecated class like GCMBaseIntentService ( )

  • malgaboy

    Have you made your idea?

  • Sargam Rajput

    I have enabled google mail on emulator, also using google api emukator. Emulator is also getting registered, but unable to receive notification. please help .

    • Hannan

      Someone please help here. As Sargam has said, I have used google API for emulator, its registered. But still do not recieve notification.

  • pradeep

    when i click on register, application is force close

    please help me

  • Banwarilal

    Me too having same issue… unable to resolve…
    Reply if anybody have resolved…..

  • vicky

    mee too receiving the same error… ” You are already registered with gcm”… have you got any solutions…

    • A mendel

      If you have already registeed your device on GCM, it sticks in the GCM server for a while even though you may have cleared the entry from the third party server.

      hope that helps,

  • nemi

    Hi Ravi,
    I would like to develop chatting application.. can u guide me to developed it, lot of info around the google, but i still cannot understand the flow of chating

  • krunal

    Thanks Great Tutorial…As Rock As Other Android Based Concept Tutorial Of Yours…

  • Amol

    i am having problems in registering device in five attempts what should i do ??? plz help

  • harsh

    java.lang.RuntimeException: An error occured while executing doInBackground()

  • harsh

    Error is: java.lang.IllegalArgumentException: invalid url: C:/wamp/www/gcm_server_php/register.php..solve this problem…it’s urgent..plz…

  • harsh

    In file what server url we have give in the path…..plz sove this probilem….

  • arun

    plz provide php code 2 send al registered moblie notification on 1 click

  • harsh

    Is it possible to get notifications form php file to android without google cloud messaging??If Please help…

  • harsh

    Hey..It is necessary to sign in google account bcoz every client have no google account(gmail)….some have yahoo,rediff account etc…so from other account like yahoo,rediff,etc..can we access this appplicaion????

  • Dopu

    Hi ! I’m French, sorry for the mistakes…

    I’ve got a problem : java.lang.NoClassDefFoundError:

    But I’ve a gcm.jar :/

    • Dopu

      I test with my galaxy S3.

  • Eric C

    Thanks, the codes work fine !!!. Just creating google account on the emulator does not work for me, need to test on a real device.

    It will be good to add date and time info to the message, how can i do this? Appreciate for your further advice!

  • Aditya

    Eric C : Did you run the codes on a real android device?

    I am trying to run on emulator and getting error at gcmregistrar.checkdevice(this)

    @Ravi : Please Help

  • Hector


    This tutorial has helped me a lot!! Thank you very much!!

    But I have a problem. I want to show a message when the screen of my MainActivity is on foreground and a notification when this screen is on background. How can I do it?

    I hope you can help me. πŸ˜‰

  • Richie Q. Grabner

    Super thx a lot. But I have a question. I read that it will be possible to send from Android Phones to server using gcm in a newer version of gcm is there any news on that and will the example be updated (or a new created)



  • Marc

    This is slightly out fo date using some Depricated stuff is there a more upto-date version that just uses GoogleCloudMessaging? The Registrar and Intent service where depricated some time ago.

  • pawan

    Hi Ravi,

    Thanks a lot Pawan

  • Amr

    I did everything as required, but every time I register from the registration screen, it goes to the main activity and a Toast appears telling me “Already registered” although the database is empty.

  • Amr

    Hi Ravi,

    I have a problem when I register and move to the Main Activity, a Toast appears to me saying: trying (attempt 1/5) to 5/5 then tells me: couldn’t register device in demo server.

    I did everything as required but still having this problem and the Wamp local server doesn’t store anything I send from the android application

  • Paula

    Hi Ravi,

    First of all thank you for this tutorial. It’s great!. I’m learning how to develop Android apps and your examples helps me a lot.

    I’m trying your code in Android Studio but I have an error: Gradle: error: package does not exist

    I don’t know how to solve it. Could you help me please? It seems like the package isn’t there.



    • Marc

      you need to ensure that you have the gcm library included in your project folder.

  • Basel

    Hey Ravi,

    Great website. I just was wondering if there is a way to send a message to all the registered users instead of everyone alone.


  • Onest

    i published my app with notification. it stops after 3 days !
    any help ? or ideas ?

  • Kath

    Hi, the app wont insert the data to the database, i’m sure i followed the instructions well.. do anyone encountered this?

    • saab

      i have also encounted this problem….and in app it shows succesful registration messages…

  • that was genius!

  • Harpreet Sardar

    i have followed your steps and finally the emulator shows up the registration form, but when i enter the details and submit i get the following message and application closes.”Unfortunetly AndroidHive GCM has Stopped” this happnes in emulator

    and the eclipse console no errors:

    [2013-07-31 15:25:44 – AndroidPushNotificationsUsingGCM] ——————————

    [2013-07-31 15:25:44 – AndroidPushNotificationsUsingGCM] Android Launch!

    [2013-07-31 15:25:44 – AndroidPushNotificationsUsingGCM] adb is running normally.

    [2013-07-31 15:25:44 – AndroidPushNotificationsUsingGCM] Performing com.androidhive.pushnotifications.RegisterActivity activity launch

    [2013-07-31 15:25:54 – AndroidPushNotificationsUsingGCM] Launching a new emulator with Virtual Device ‘test’

    [2013-07-31 15:25:58 – AndroidPushNotificationsUsingGCM] New emulator found: emulator-5554

    [2013-07-31 15:25:58 – AndroidPushNotificationsUsingGCM] Waiting for HOME (‘android.process.acore’) to be launched…

    [2013-07-31 15:27:07 – AndroidPushNotificationsUsingGCM] HOME is up on device ’emulator-5554′

    [2013-07-31 15:27:07 – AndroidPushNotificationsUsingGCM] Uploading AndroidPushNotificationsUsingGCM.apk onto device ’emulator-5554′

    [2013-07-31 15:27:07 – AndroidPushNotificationsUsingGCM] Installing AndroidPushNotificationsUsingGCM.apk…

    [2013-07-31 15:28:11 – AndroidPushNotificationsUsingGCM] Success!

    [2013-07-31 15:28:11 – AndroidPushNotificationsUsingGCM] Starting activity com.androidhive.pushnotifications.RegisterActivity on device emulator-5554

    [2013-07-31 15:28:13 – AndroidPushNotificationsUsingGCM] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.androidhive.pushnotifications/.RegisterActivity }

    i changed the URL and serID

    // give your server registration url here
    static final String SERVER_URL = “”;
    // Google project id
    static final String SENDER_ID = “906331049194”;

    also created the DB on the same server

    Please suggest:

  • Josep Escobar

    great tutorial, thanks

  • Anny Average

    Great job πŸ™‚ working superb .. Thanks

  • Jonathan

    Hi Ravi,

    This Tutorial is very good, but i’ve a Problem with receiving Push Messages with mobile internet connection. I get them only when I am in a WiFi network. Is there a possibility to get them in mobile notwork too?



  • Harpreet Sardar

    Did any one solve this problem, Please advice

  • Harpreet Sardar

    Hello Ravi,
    IS this Resolved ? Could you please help.
    Nice work Ravi. But i have a problem. Every time i get a message and “click” on it, the MainActivity is open but its blank, no text. If i leave it open and send another messahe it is displayed. Any ideas why the message show only when MainActivity is opened?

  • arief abdul aziz

    Hi ravi how to make GCM work without Localhost….I’ve try your project in Localhost already working…maybe others can also help me..please ^_^

  • Federico Boesche

    Thanks Ravi.. usefull and great tutorial!

  • Stephen Sugrue

    Hi there, Nice code works nicely when I pull down the notification bar and click the message some times it says device already registered any ideas why? also can you save the sent message on the phone?

  • arief abdul aziz

    hi ravi would you please to tell me how I can use my GCM in the real cloud example with app engine to post your php in the cloud??in emulator I still work your php

  • Glory

    Ravi, I downloaded your code and try to open with real device. The registration form is opened but when it’s done and submit the registration the app force close. can you help me with this thing???

    My android version 4.0.4
    with google linked
    (I change the server URL and project ID with my own)

    sorry for my bad english.

  • Sridhar Kulkarni

    Ultimate tutorial….. but i’m getting authentication failed. i’m new to gcm. can u please help me??

  • mrana

    Hi Ravi,
    Thx for this great website. Need a favour from you.
    Can you pls guide me about doing the same GCM stuff but using java/ee with My sql as a database instead of php?

  • Balaji

    I’m getting wakelock error while running my android app. Kindly reply to this post. Thanks advance.

  • Aditya

    Hi Ravi,

    I am getting duplicate notifications in some devices. Can you guess whats happening.

  • Gaurav Singh

    Hello, I was trying to run this application using nexus 7 tablet, it was failing at GCMRegistrar.checkDevice(this); in MainActivity class.
    Can somebody tell me how to make sure that my device supports GCM dependencies?? Please help.

  • abhay

    Is there a way to enable / disable notification from App itself by end user ?

  • Patrick

    Hi Ravi!

    Nice tutorial :). Sorry for making a comment not related to the tutorial, but I would like to know which tool are you using to design your graphics? I like it

    • No Problem. I use Adobe Photoshop and Illustrator

  • iwillhuntyou

    try to check your config.php

    define(“GOOGLE_API_KEY”, “AIzaSyALJIjDuCQo6Wp01xVwZNBsw2z7BzAGa3A”); // Place your Google API Key

    change the API key by your own key given to you.

  • yogie soesanto

    hi ravi , thanks a lot for your c2dm (old GCM) tutorial

    but now , as we know that c2dm is deprecated by google
    as we can see here

    can you make a tutorial about the new GCM

    as we can see here

    i’ve tried myself,
    using this source
    but in Android 2.2 , it shows SERVICE_NOT_AVAILABLE

    and i think C2DM can support any OS like 2.2 or higher , but new GCM just support high android version like 4.2 or higher

    but i dont know it for sure, thats why , im asking you

    maybe you or anybody who read this can share about this new GCM , thanks πŸ™‚

    • Hi Yougie, This is new GCM only

      • yogie soesanto

        if you have any moment, please take a look at here ravi “” , it says that our latest C2DM
        “will accept no new user” and “C2DM developers are strongly encouraged to move to Google Cloud Messaging (GCM)” that’s why i’m asking you for the newest tutorial thanks ravi πŸ™‚

  • ankita

    ys it did work…bt why notification is not visible..???

  • kaushik patel

    HI Ravi,
    Now Google cloud messaging library deprecated.
    gcm is being the part of the google play services so, GCMREgistrar is not working now. so this example is not live longer.

    • I didn’t see anywhere where they told that GCM is part of Google Play Services. Could you pass the link where you got the information from

      • yogie soesanto

        maybe this link will help

        it says :
        “This document tells you how to get started setting up a GCM implementation. Before you begin, make sure to set up the Google Play Services SDK. You need this SDK to use the GoogleCloudMessaging methods.”

      • kaushik patel

        You have Seen In sdk Manager (Deprecated) Google Cloud Messaging is Shown its move to the Google play services……..

        • Oh really. I’ll look into that.. Thanks for the info πŸ™‚

  • Vishal Kumar Pandey

    Hello ravi sir,

    if i don’t know php and my sql then what…plzz do it with using java and oracle/derby..

  • Rohit Behl

    How to work with SQL SERVER? any suggestion

  • Guest

    hi there, i can’t solve this and it is happen in when i register from emulator there show a error like”From GCM: error(INVALID_SENDER)” and also toast give me the same kind of error. what can i do please tell me

  • Mattia Adducchio


    first of all: Thanks a lot!

    I have a problem with the wakeLock, infact after I have receive the push notification the device wake up but after the screen don’t go off and the touch screen not work and i have to push the home button to “re-wake up” my device.

    Best regards,

  • Eaiman Shoshi


    in my previous project i have integrated GCM by following this blog. And that is working fine.

    But, in my new project, this is not working. i am getting no data in my server. the only difference between this two project is: in my previous project , all my GCM related classes were in my project’s default package. but in my new project the GCM related classes are in ‘com.gcm’ package, and i am calling them from another package’s activity. i have track that (using Log.e) the code is executed to

    // Check if regid already presents

    if (regId.equals(“”)) {

    // Registration is not present, register now with GCM

    GCMRegistrar.register(this, SENDER_ID);
    // after this nothing is happening
    } else {

    i have ‘Log.e’ in every classes and every possible places πŸ™ but they are not printing anything.

    i think i have to change in the manifest. but i don’t no what to change. can anybody help me ?

    • yogie soesanto

      hai eairman, when you use GCMRegistrar.register
      it shows that you use the old GCM , as it says in this link

      now google doesn’t provide any new registration member using old GCM , so GCMRegistrar won’t work, try to use the new GCM

    • LoungeKatt

      This may sound silly, but what context are you using? I have found that if I use the application context in the receiver, that still works. Using application context in register or within the setup calls causes it to fail. Using another activity or service context to perform setup for an activity also fails.

  • Glory

    Some code is deprecated… Ravi, can you update your source code please….

    any one can fix it???

    • Guest

      Check my comment for an updated and more efficient version of the code πŸ˜‰

      • Glory

        link or site please….

    • Steve Rodger

      Did you manage to get this project working? I hope lounge katt gets back in touch

  • Noor Fadhilah

    Hi Ravi,

    Thanks a lot.

    I want to send notifications to many users. have you try it before?

    Thank you.

  • Noor

    Hi Ravi,

    Thanks a lot.

    I want to send notifications to many users. have you try it before?

    Thank you.

  • Saad Bn Muaz

    Its greats tut.
    But now I’m using sencha framework to develop my android application, how can I get this “regId” in jacascript??

  • Moustafa Ashmawy

    Hi Ravi,
    I just would like to thank you very much, your tutorial was great and helped me alot
    Thanks again

  • Valerio

    thanks for your guide but i have a problem: when i send my push i receive Internal Server Error.
    If i comment this string “curl_setopt($ch,CURLOPT_URL,$url);” it work but obviously push doesn’t start…Android Developer says that for this error we must wait but i have this problem from about a month

    Someone can help me??thanks

  • xuandinh

    When i fill test form and the error display


    address is:

    Who can solve this error.

    Sorry my English not good. Thanks

    • arash ataafarin

      I have the same problem!

    • arash ataafarin

      If You Are Testing this Project on your real phone and you got localhost/ – Connection refused

      you should change the IP that you connect with it,use below link to solve :

  • Glory

    Whoa… Thanks….

    I’ll be wait for how to integrate this setup into an Android application:D

    Thank’s a lot πŸ˜€

  • Danny

    When I attempt to register a user, it keeps exiting the activity, reporting an error – “Unfortunately, AndroidHive GCM has stopped.” Not sure if it would be the SERVER_URL, I’ve tried your version and also my own version which is allowed in the apache http.config file yet still no luck. If you would know why I’m having problems, would help, Thanks.

  • Liron Vaizer


    thanks!!! it is a greate tutorial!

    how can i send a notification to all the users at the same time and same text?

  • Shahid Bashir

    Greate work…….thanks

  • Guest

    after test


    Error 401

    • saab

      I am also reciving this error No idea what to do.I thing xampp has some recrition

      • saab

        I cleared the problem…
        Mistake 1:
        i was using ” Key for server apps (with IP locking)” Google Api

        Mistake 2:
        By giving db user name and kepping password field blank solved it
        define(“DB_HOST”, “localhost”);
        define(“DB_USER”, “root”);
        define(“DB_PASSWORD”, “”);
        define(“DB_DATABASE”, “gcm”);

        Mistake 3:
        By Enabling Curl

        Mistake 4:
        Enable webservice if you are using xampp

  • Dan

    Hi Ravi!

    Will you update this with the google play services method? Would really appreciate it!

  • Alessandro Universus

    Hi Ravi, this is a great tutorial. It works fine, but when I transfer the app (with appropriate modifications), the device can’t install it. I try with Android 2.3, 4.0 and 4.1.2, but the outcome is always: application not installed. What can I do?

    • Increase the target SDK value in AndroidManifest.xml file

  • Alessandro Universus

    Me too, any answer?

  • Muhammad Nazeer

    when im sending 3 mesages from server is not show(3) new messages form notification bar also just show last mesage only on notification bar when click any message is not show blank screen if application is open then is show message from server why?

  • Alessandro Universus

    Hi Ravi, why when I touch the notify in the status bar the app opens but displays a blank screen without the previously received message?

    • Alessandro Universus

      there is nobody who knows how to help me? is very important

  • Pedro

    Great work!! Can you explain how to do the same thing but with the new GCM (not deprecated)?

  • yourkishore

    is there any way we can automate the user registration without name and email, just after installing the application ?

  • Nazeerahmed

    if i sencronize my mobile with gmail then install application i revirece notification from server but if i install application first then sencronize with gmail i never receive notification also regId not insert in ph server why? any idea??

  • Pobo

    Hi, I have a little question which im a bit confuse of. The 3rd party server will only required the gcm_regid in order to send a notification(message) to the gcm server, is that correct? The name and email fields are just for extra information, am I right?

  • Candy Wijaya

    Thanks a lot, it WORKS !!
    but if I want to send 1 message to all of the user, what should I do?

    • bharath

      hey not working for me

  • adhadimas91

    Nice work Ravi. But i have a problem. Every time i get a message and “click” on it, the MainActivity is open but its blank, no text. If i leave it open and send another messahe it is displayed. Any ideas why the message show only when MainActivity is opened?

  • usman khan

    hey, thanks for the good tutorial, but i have not been able to connect to “Demo Server”, after so many attempts. Any solution you can suggest.


  • adhadimas91

    ravi please respond Nice work Ravi. But i have a problem. Every time i get a message and “click” on it, the MainActivity is open but its blank, no text. If i leave it open and send another message it is displayed. Any ideas why the message show only when MainActivity is opened?. i try and change into normal intent but it is not work ..please

  • Nagendra

    Great Tutorial Ravi Thanks


  • siddhu

    problem with adding google account showing security error

  • Daan Dawud

    Fantastic dude!

  • Anas Azeem

    As everyone is struggling, I am also unable to receive notifications on the device (be it an emulator or a real device), despite of successful registration.

  • semi

    thank you very match

  • Deepak Singh

    Hi ravi,

    Code is worked for me thanks. I need your help to convert this php code into java code.

    This is requested to you, Pl help me and also guide me push information through web services as news feed.

    Your help will be appreciated.

    Deepak singh

    • Rajnish

      try google sample projects for gcm that includes a servlet implementation for server side.

  • siddhesh morye

    Hi Ravi ,

    I have made few changes in GCMIntentService page( generateNotification method). I used below code to show notification counter in my notificatios. It works fine for me ex . “You have 2 notifications” but when i clicked on notification , notification counter can not be reset. if you send another notification then that counter will be added in last notification counter .ex . “You have 3 notifications” . Do you have any solution for that ?

    static int count;
    static int i=0;
    count ++;
    notification.number +=i;

  • pknjinjesto

    Hi,i can’t connect to the database when i type locahost/gcm_server_php/test.php it says”Curl failed: couldn’t connect to host” and i can’t register on settings/Account&sync with emulator,please help

    • You have to enable curl in wamp. Check the video I had shown it.

      • Eeid

        I have a problem in posting params to the server it says:
        Failed to register on attempt #1,2,3,4,5: Post Failed with error code 403

  • Pedro Aguayo

    The best tutorial I found about Push notifications on android. Congratulations and thank you:)

  • Larry Lo

    what is the minimum required version of php to support such OO design ?

  • Omar

    Thanks Ravi for tutorial, my project needs to inform user(field engineer) in site immediately with comments added in database by dispatcher(officer or coordinator) or jobs added for him in database, also vice versa dispatcher informed with added files in database by field engineer. So what is the best solution for that, RSS feeds with service runs automatically every period of time or GCM service (and if it last one , how i do that )

    • Kaylee

      hi are you able to do the tut shown above? do you mind helping me out?

      • omar

        i’m trying this, but eclipse has some problems now , so i’ll try and see what happen?

        • Kaylee

          have you manage to run this app smoothly if yes, please help me out! thank you!

  • Omar

    another question, does everyone uses GCM service needs gmail account ?

  • Kaylee

    hi i follow the codes and i’ve enabled the curl but when i open the browser
    http://localhost/gcm_server_php/test.php. it shoes me a blank page. what do i need to do?
    there’s also quite a number of error in my esclipse code after i copy the code provided. what should i do ? please advice! please help ! thanks!

    • Omar

      first try the project and itself and if it works integrate it into your work, second, what are errors you have in eclipse, and the main page of server side is index.php

  • Omar

    Thanks Ravi, it works for me and send message to field engineer, just when coordinator adds a new comment into database.but not integrate the code in my project yet and also the data not inserted into database, so i’ll try to solve this and write what i do , may help others.

  • Omar

    $db = new DB_Functions();


    $users = $db->getAllUsers();

    if ($users != false)

    $no_of_users = mysql_num_rows($users);


    $no_of_users = 0;

    if ($no_of_users > 0) {

    while ($row = mysql_fetch_array($users)) {





    $gcm = new GCM();

    $registatoin_ids = array($regId);

    $message = array(“price” => $acc_comment);

    $result = $gcm->send_notification($registatoin_ids, $message);

    this code in ‘AddAcceptanceComment.php’ file to insert data from form to db and in same time send push notification to field engineer that new comment added to him ( i tried it on single user registred, and i think there will be problems with multiusers registred).

  • Matteo Valenza

    Hi, great tutorial, i used this for all my app, i want to thank you so much for your good work, the best i can found in the net. i have one question about the handling of the notification, i want to parse the notification and not show it at the end user, i try to use abortbroadcast() like for the smsBroadcast receiver but the notification show up in the notification panel like before. Do you have an advice to solve my problem ? Thank you and sorry for my bad english πŸ™‚ Ciao!

    • Matteo Valenza

      i already reply to my question, if i comment this line:

      generateNotification(context, message);

      in the class, the notification will not go in the notification panel.

      Sorry for my silly question πŸ™‚

  • Steve Rodger

    Hello. I have tried to combine your tutorial with the above tutorial but I am having no luck getting it to work. One i finally got google play services imported and working I have 0 luck getting the project working with a locally hosted server. Could you possibly post a working example using the lastest non depricated play services?

  • Pravin Patil

    Hi Ravi,

    I’m facing one issue regarding “test.php”(Page not found error). This file is not mentioned in given tutorial.
    One thing want to make clear, I’m using XAMP instead of WAMP.

    Please help me out.

    Thanks a lot.

    • Omar

      index.php is the main page to test the tutorial not test.php

  • arash ataafarin

    If You Are Testing this Project on your real phone and you got localhost/ – Connection refused

    you should change the IP that you connect with it,use below link to solve :

  • Sahil Mehta

    Hi Ravi,
    I have implemented your entire tutorial step by step. Instead of wamp, I used a 3rd party web server 000webhost to make my server. My app doesnt seem to deliver the push notifications though. My device registers with the web server(coz the i can see the database filled), it also recieves a registration ID from GCM, but when I type in my message and press send, it doesnt come to my device. Could you please help me. Ive been trying to figure out this problem since the past 3 weeks.

    • Omar

      make sure that android app has internet, GCM can delay sending notification till app become online

      • eugenevdm

        Carefully also examine Logcat. The code has very detailed logging which will indicate if the message is at least reaching your device.

  • Omar

    this is my implementation of this tutorial to send GCM notification once coordinator add comment to database.



    //Grab the acceptance comment data from POST



    //Attached file info
    $attachedfile=str_replace(‘ ‘,’_’,trim($_FILES[‘attachedfile’][‘name’]));






    if(!empty($acc_comment) && !empty($jobid)){




    //if (empty($route)) $route=$sitename;

    //connect to database


    // or die(mysqli_connect_error());

    //Insert data acceptance comment into database

    //$query=”INSERT INTO acceptance VALUES(0,$jobid,NOW(),’$acc_comment’,’$newfilename’)”;


    // or die(mysqli_error($dbc));

    $db = new DB_Functions();

    //it’s function that has the same statement above to insert new comment to DB


    //these variables for save values needed to save in table gcm_users (emp_id and regId, and id is autoincrement).



    //$query=”SELECT * FROM gcm_users”;

    //$users = mysql_query($con,$query);

    //function has same statement above to get all users of gcm_users table and we can get exact user using emp_id that can be extracted by job_id variable, so we send to specific user that concerned to comment by extracting it using ‘job_id’ variable from table jobs.

    if ($users != false)

    $no_of_users = mysqli_num_rows($users);


    $no_of_users = 0;

    if ($no_of_users > 0) {

    while ($row = mysqli_fetch_array($users)) {






    $gcm = new GCM();

    $registatoin_ids = array($regId);

    $message = array(“NewData” => $acc_comment);


    $result = $gcm->send_notification($registatoin_ids, $message);

    //echo ‘ID: ‘.$ID.’EMP_ID: ‘.$empid.’ and Registration ID: ‘.$regId.”;

    //echo $ID.”;

    //echo $result.”;

    //echo $insertAcc.”;


    //confirm adding acceptance comment

    echo ‘acceptance comment added’;






    echo ‘Please enter all of the information to add new acceptance comment.’;



  • Omar

    this function to get regId of specific user based on emp_id field, so i send notification to concerned user with job and comment


    //To get employee ID by job_id

    public function getGCMuser($job_id){
    require_once (‘config.php’);

    $con=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE) or die(mysqli_error());

    $result=mysqli_query($con,”SELECT emp_id from jobs WHERE job_id= “.$job_id);




    $query=”SELECT gcm_regid FROM gcm_users WHERE emp_id=”.$empId;




    return $regId[“gcm_regid”];


  • faiz

    Hi . how to handle the click event on a particular notification .

  • AndrΓ©s Mauma

    Gracias por el aporte, me funciono muy bien

  • Diego

    excellent tutorial, I would like to know how to keep the push on a SQLITE database

  • I have few questions Ravi Sir.
    1. How to detect and remove / manipulate canonical ids.
    2. How to detect which id is failing to reach GCM server.
    3. Why do ‘Null’ data(s) is sent automatically in Database always ? I need to delete it manually sometimes.
    4. Do device ‘registration id’ remain permanent or it changes with time ? If so then how can it be resolved if Person A among 1000 user’s id changes and it’s hard to detect which device reg id changed.

    I just like your tutorial very much, it’s really really facinating.


  • surajit

    thank u very are a genius.

  • Hi. Could you please update the tutorial to use the new GoogleCloudMessaging API?

    Thank you.

    • Yeah, I started preparing.

      • eugenevdm

        I have great interest to see this beautiful demo converted to the new API.

  • Tasos

    Hello Ravi, so nice project! I have a problem though. I have followed your steps and I’m sending register requests successfully but nothing is stored in database, while the app says “Already registered with GCM”. Any idea to solve this issue?
    Thank you in advance.

    • eugenevdm

      If nothing is stored in the database most likely your PHP server is not working or the URL is incorrect. Logcat will display the URL it’s posting to. See if the URL can be copied/pasted in your browser.

  • FiL0

    Hi Ravi,
    Thanks for the great guide.
    Quick question. How do you handle the GCM without using Curl, so that it can work on google servers?

  • jy

    for u this example i only can register
    but i can not send msg from server to phone

    • 0_ll_0

      same for me

  • Good

    Nice app but i have a problem


  • AndroidMan

    Hello Ravi! First of all you make a very good work! Congratulations and thank you! To others, why does not work the registration? Just because you use a free hosting server, if you put all of the php scripts to a VPS or to any reliable hosting, it should be working! But I use WAMP on my WinXp and tested on a real Android phone with v2.3.7 and a Samsung Tab 2 with v4.0.4. It is worked perfect all of my devices, I get all GCM messages. But I have a question: How to implement to store the user country on my server instead of “name” ? I dont want to store email or name i just want to store the android phone user’s country name (i dont want to use geolocation) when it’s registered on my server. Is it possible? Thanks.

    • Hi,

      Thank for your valuable feedback. To get the country may be you can follow this

      • AndroidMan

        Thank you for that link, i read it some days ago, but i have problem with that code. Can you help, how to put the string to database instead of the ‘name’? What is return in this case? This is the working code:

        ———————- CODe STARTS HERE ——-

        public static String getUserCountry(Context context) {
        try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) {
        return simCountry.toLowerCase(Locale.US);
        else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
        String networkCountry = tm.getNetworkCountryIso();
        if (networkCountry != null && networkCountry.length() == 2) {
        return networkCountry.toLowerCase(Locale.US);
        catch (Exception e) { }
        return null;

        ———————- End Of Code ———-

        Thank you for your reply.

        • AndroidMan

          Hello Ravi!
          Did you find any solution for this? I know there is a lot of question about your code and I know you are too busy for this, but please tell me how to put from the above code the country string instead of name (or email), /i dont want to use the name or email/
          thanks again.

  • Omar

    Thanks Ravi, great tutorials. I wonder if you can post a tutorial about the reverse operation, i mean send message from device to server and to another device that has the same android app registered to same server.

    • Yeah, I am working on it.

      • Omar

        Thanks, waiting for that….

  • nishal

    hi Ravi….
    I have complate registration with GCM and entry for database but write msg adn click send but dose’t show msg in emulator…..
    so, plese help me dear bro….
    i wait for ur ans….

    • Aguirre

      Try using a real device. It might not work on emulator because Google Play Services is not installed at emulator by default.

  • king

    Thanks Ravi, great tutorials.

    Can i use python (similar like u index.php) to send push notification to android device?
    waiting for u reply….

  • nishal

    hi ravi how it’s send same msg for multiple user..??
    plz replay me….

    • Omar

      //function has same statement above to get all users of gcm_users table and we can get exact user using emp_id that can be extracted by job_id variable, so we send to specific user that concerned to comment by extracting it using ‘job_id’ variable from table jobs.

      // get the message in some variable and assign $message to it.

      // put all regIds in array variable and push it to $registatoin_ids


      if ($users != false)

      $no_of_users = mysqli_num_rows($users);


      $no_of_users = 0;

      if ($no_of_users > 0) {

      while ($row = mysqli_fetch_array($users)) {






      $gcm = new GCM();

      $registatoin_ids = array($regId);

      $message = array(“NewData” => $acc_comment);


      $result = $gcm->send_notification($registatoin_ids, $message);

      //echo ‘ID: ‘.$ID.’EMP_ID: ‘.$empid.’ and Registration ID: ‘.$regId.’

      • nishal

        i have not understand code please send me full php fiel….

        • Omar

          //get result set table gcm_users, so you have all registered users.
          //check if it returns data or not
          if ($users != false)
          //number of users returned
          $no_of_users = mysqli_num_rows($users);


          $no_of_users = 0;
          //check that there are returned users
          if ($no_of_users > 0) {
          // loop in result set to get every row.
          while ($row = mysqli_fetch_array($users)) {





          //create object from GCM class.
          $gcm = new GCM();
          //create array with ids
          $registatoin_ids = array($regId);
          //create message variable with what you want to notify with.
          $message = array(“NewData” => $acc_comment);
          //just for debug.
          //send message to device.
          $result = $gcm->send_notification($registatoin_ids, $message);
          //for debug
          //echo ‘ID: ‘.$ID.’EMP_ID: ‘.$empid.’ and Registration ID: ‘.$regId.’

          • Valetto Pereira

            Still cant understand Can u give a detailed explaination where to use this

  • You should not use this PHP code for your backend since its prone to SQL injections! You should use pdo and prepared statements for the calls in db_functions.php or at least do a mysql(i)_real_escape, otherwise your backend might very easily get exploited.

    But thanks for getting me started with GCM.

  • Kiko Rico

    hy guys,, can show full code to broadcast msg for all users register ???? can shared … thx u guys….

    • Joannes A. Rommers

      Have you find a solutions for this?

  • Dev

    Hi Ravi..great job…can you pls tell me how to make it using oracle database and servlet or jsp as server side implementation ??

    • Khushboo Mehta

      Any updates on this question

  • geka

    Hi Ravi, fantastic post!
    I’m working on a project where the user of my application can get a notification when there are updates on the database server and then download for the updated database to the application. but I don’t know how to do that. Is this post the right answer for my question? If it yes, I bit confuse about your post, why the user have to register to the server manually? can we do it automatically? so everyone has the application installed on their phone will automatically registered to the server. I don’t know much about android, I’m very very new here. Maybe anyone here can help me, many thanks for any advice..

  • Anilton Fernandes

    Please, help me with this issues on

    PowerManager.WakeLock wakeLock;

    they are erros of eclipse, processing this file, or this project

    • eugenevdm

      What are the errors that you are getting? You say “they are eclipse errors”. What do you mean?

  • Marc

    Hi I implemented this a few months back and i remember getting it to work ive come back to it now to enable a feature and found that it no longer works im getting a generic 500 error when i try to instantiate the gcm PHP class.

    Anyone else getting this or found a way of getting around it?

  • Guest

    thnaks a lots……….

  • Tapan Desai

    Hey, thanks for the amazing tutorial, however many are saying that its deprecated now, can you please update the tutorial?

    • Guest

      Its not depricrated its just changed a little in the google tutorial to reflect the new API console Ive managed to get it working using his code and it works fine.

      • Vaibhav

        Can you please upload the changes we need to make in this code to make it work with new API console? As in previous version we add GCM jar in lib folder but with the new API console we need to add Google play dependency in the project. Please tell us the changes in this version.

        We will be thankful to you.

      • FYP Project

        Hi! Can you refer me to the changes you’ve made? Seems that I couldn’t run the original codes in my Android client. Might be due to this too.

  • Fabse

    I have the somae Problem, could anybody fix it?

  • Ali

    In this project has been modified so that many users receive messages sent from databases

    But I can not find a solution in order canceled the registration page that asks me to name and Emily

    I hope to help me in this problem

    Thank you

  • Vaibhav

    I think this Method is deprecated as Google api console now modified to Google cloud console. Android developer site also providing different implementation method for GCM which is not very clear for me.
    Can you please upload the changes we have to made in this code to make it work with new Google cloud console?
    What changes we need to make in this code to make it work with new API console? As in previous version we add GCM jar in lib folder but with the new API console we need to add Google play dependency in the project. Please tell us the changes in this version.
    We will be thankful to you.

    • Smit Patel

      but for the server?

      • Vaibhav

        sorry.. can you please explain what you are trying to say. i am not clear with your question

        • Smit Patel

          as you said that the method for the client side gcm deprecated i agree with you and i also developed the code successfully but i don’t have idea about server side coding

          • Vaibhav

            Ravi also provide with his code for GCM Server side implementation. I think there is no changes in that code. the method at client side is changed only so you can follow server side code from the above link. Can you please tell us the changes you made to your client side to use it as updated method

          • Smit Patel

            I have used the google play service lib fo the client side and for server side i have read that right now we are using http method for Xmpp method and port no. 5235 is used so i am asking you for the server code which using the xmpp code.

          • Vaibhav

            How to use this lib on client side for GCM? When I added Google play services lib in my project for client side and removed gcm.jar I got error on GCM methods. and if i added gcm.jar to my project then there is no need to add Google play service lib dependency in project. Please help me i an confused with this new implementation process.

          • Smit Patel

            you have to remove the gcm.jar and all the method that are you using for the gcm and go to the this link this will help you to develop the client side latest gcm

  • nishal

    How to store all send msg and display in list view with date..??

  • youssef

    * 12-12 16:16:50.520: E/AndroidHive GCM(1875): Failed to register on attempt Post failed with error code 403

  • Bikash

    Could anyone tell me Why it is showing gcm(sender error) ………

  • Fatih Onur

    Hi Ravi, First of all thank you for your great tutorials. I have a simple question for you. I hope you can answer that. I like your diagrams in your tutorial.
    What tool do you use to draw them? Thanks

    • Adobe Photoshop & Illustrator

      • Fatih Onur

        Thanks for your answer….

  • Sam

    Hi Ravi, I’ve downloaded the code and i changed all the necessary fields but everytime i press the register button, the app stops and force closed

    • Hope2Help

      Can you post the error response from logcat?

  • Daryl

    First of all, thanks Ravi to share this example, I did tried the tutorial, it works very fine to register new user, until on PHP side, i try to send message to notification on my Phone(not simulator), i couldn’t receive the notification, can you advise where should i check for this?

    • lakhwinder singh

      some things happen to me

    • Hope2Help

      You may have the wrong API Key for your server. In the tutorial, the Google Developer Console shows an API Key for BROWSERS and NOT ‘API key for Android’.

      Create a new key at APIs & Auth > Credentials > Create New Key. From there you can create a key for a server, browser, android or iOS.

      A lot of tutorials say to use a Key for browsers, but my notifications still wouldn’t send. If that’s the case, then I suggest using a Key for Servers.

      If you’re still having problems I suggest making a new file ‘test.php’ or whatever, and using the content here:

      Once you fill out the proper variables and navigate to the page you can see if you’re getting a Unauthorized 401 error (in which case there’s still something wrong with your API key).

  • Guest


    Error 401

    • Hope2Help

      Make sure that you’re using the BROWSER API KEY and NOT the Android API Key. If the Browser API key also doesn’t work for you then I suggest creating a new IP key. After fiddling with my server and google console, I found that the IP key (Key for Server Applications) worked for me

  • lakhwinder singh

    @ravi tamada all things are set up as you describe, but it does not receive the messages and push notifications as you shown in the video , will you please help me..Thanks any way for this great post.

  • Ninjahitam

    Does this apps will auto run when the user reboot or restart their android phone ?

  • klevisndoka

    Thanks for the GCM guide.

  • Sonu Raj

    I am getting this error and app is crashing πŸ™

    java.lang.NoClassDefFoundError: at com.cloudexample.MainActivity.onCreate(

    com.cloudexample is my package

    • crash007

      U need to import gcm lib in the libs folder of ur project…it works fine after that

  • Ashok prakash

    Awesome work!! I haven’t tried the code yet…! But still this is one damn work :)! Great sir!!!

    • Hello team,My device registered on server,But Notification is not coming to device when i send from server.Can any one help me please.. ?

  • Vivek

    Hi thanks for your tutorial. I am receiving {“multicast_id”:4699879074237634152,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1389262772392050%a5f0f84bf9fd7ecd”}]}. But the message is not received in emulator.

  • malith wimalarathna

    Great work!! work perfectly… thankxxx for the good tutorial

    • Hello team,My device registered on server,But Notification is not coming to device when i send from server.Can any one help me please ?


      Can you please help me

      i am getting this error while testing the above code.

      02-03 20:44:45.273: E/URL(8008): >

      02-03 20:44:50.328: E/GCM Android Example(8008): Failed to register on
      attempt Post failed with error code 403.

  • Ivan


    It works very fine to register new user, until on PHP side, i try to
    send message to notification on my Phone, i couldn’t
    receive the notification, can you advise where should i check for this?

    • Ivan

      Somebody can send a working code (google_play_services) to me on I will be very grateful!

    • Vivek Ravi

      This is may be n/w problem.

      • Ivan

        I found a cause of error – json_encode didn’t work (on my vps server). When it works everything works normally!
        There was a question – “deprecated” – as it is long possible to use the gcm.jar technology. Now not to write a code on “google_play_services”.

    • Israel

      Ivan can you send me your code please, I can’t make it work. My email is

      • Ivan

        My code completely such as here at the author. Anything else isn’t present.

    • nasznjoka

      if the notification does not even show on the notification drawer then the issue is the permission on your manifest file it should be like this

      make sure you replace the whole “com.androidhive.pushnotifications” to your own package in case you’re using it on your project

  • Ivan

    Somebody can send me a working code (google_play_services) on I will be very grateful!

    • FYP Project

      Hi! Have you gotten a working code for google play services? Seems that I couldn’t run using the old Cloud messaging now.

  • Vivek Ravi

    Did you get solution for this problem?

  • hidden forever

    How to get API key??

  • Ivan

    If the user deletes the app from phone – how to remove its record from base on the server?

  • Israel

    When I register someone in test.php I get this error: {“multicast_id”:8712728284673680880,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]} Is it normal in test.php??

    • Israel

      Is there any way to run it on a mobile?

    • Ivan

      For me doesn’t work on shared hosting. Works on vps.

  • Namdev Londhe

    This is the great tutorial. When I send the message to the perticular device from my server it will send to the device means device does not recognize it or server not send I have confusion in between them.I have used same code as auther has given.

    Please help me for this. I will thank full to you all.

  • mitsus

    great tutorial! But when an update to Google Play Service?

    Thanks a lot


    I have hosted the php files on my serve.
    When testing with test.php
    I am getting this

    What is the problem?

  • TomChen

    Your source code is very clean!!! Tutorial makes me understand the way GCM works and the implementation of GCM. Thanks a lot!

    • Hello team,My device registered on server,But Notification is not coming to device when i send from server.Can any one help me please ? ?

  • Amit Gahlot

    can somebody help me in understanding gcm and notification how it wrk

  • Prashasya Choudhary

    Code works fine on client side….it says it has registered with server….
    However no entry is made on the server database….It says 0 registered users. and so no option is there to send push notification…

  • sushant

    i friends please help me out… after running test.php when i try to submit its giving me this error-


  • azerto00

    This client method seems Depreciated according to Google Demo code ( Am I wrong ?

    @sushant : InvalidRegistration suggest you made a mistake with google API access

  • Shubham Singh

    i dot get the “api key” in the “api access” did any run into sam issue

    • Shubham Singh

      i think now we have create the api key by

    • AP

      Try with the older version of google api.Create a new project and try.The same screen shot is being displayed whatever is shown in the tutorial.

      • Shubham Singh

        i am using the old api below the simple api line in get links to create api keys there is no auto generated key.
        i created the api key by using the links below

  • AP

    Great tutorial

    • Shubham Singh

      are you able to run the app

      • AP

        yes πŸ™‚ ..with no trouble at all..just have to replace the API key and the project id..

        • SRINATH



          Can you please help me

          i am getting this error while testing the above code.

          02-03 20:44:45.273: E/URL(8008): >

          02-03 20:44:50.328: E/GCM Android Example(8008): Failed to register on
          attempt Post failed with error code 403.

      • AP

        why don’t you try downloading the code directly and import it in eclipse and just change the server url and the project id unader android .. And under php juss need to chng the api key..

        • Shubham Singh

          i did, app starts on the device and “trying to register” happens for 5 times but it doesnt registers. and test.php returns multicast that many people have commented

  • Shubham Singh

    @ravi8x:disqus please update the code as gcm.jar is depreciated

  • nasznjoka

    The new message when comes it doesn’t open when you click it. How to do that?

  • zheguo wo

    great tutorial.
    when i send message from server, device doesn’t receive it.


    Error 401

    how to do ?
    please help me.

    • 4droid_Learner

      You need to get a browser key from !! An API Key will not work!

  • 4droid_Learner

    Hey guys! I wanna send the notification using only PHP and not HTML. How do I achieve this? The way I tried was just putting the gcm_regid, and message as parameters to $gcm->send_notification($registration_ids,$msg) but I keep getting an error saying:-
    Field “data” must be a JSON array: [“You Have A Notification!”]

    Where “You Have A Notification!” is my msg!! Please help!! Thanks!

  • mano

    Hi guys…..can anyone explain the issue i got…

    I tested php code in client side….if i click submit query button in test.php…i got this error..”Fatal error: Call to undefined function curl_init() in C:xampphtdocsgcm_server_phpGCM.php on line 41″……but data is inserted in table correctly……can u tell me why this error comes in client side……

    • sri

      replaceing PHP_CURL.dll with this php_curl-5.4.3-VC9-x64 has resolved this issue.

      • Aung Tun Kyaw

        Where is PHP_CURL.dll ? I have the same problem.

      • Rakesh

        not solved by using this

  • sri

    Hi, while trying to register with GCM with sender id, API key and email, it is giving error connection refused.Failed to register on attempt localhost/ – Connection refused

    can any body help me please it is very urgent.

    • asaf

      Hello, i had same prablom.

      i solved it by changhing “SERVER_URL” that in the CommonUtilities to:


  • sri

    i have placed PHP file under WAMPWWWGCM_SERVER_FILES*.php

  • sweety

    please help for the issue.. :”mysql_connect(): Access denied for user” and also multicast error:- “{“multicast_id”:8233467473398662356,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}” occurs when test.php is executed.. This problem is with many users here.. please give the solution

  • sam

    i implemented gcm in my app but i cant get gcm reg id

    I got this error:

    02-02 04:06:52.450: E/AndroidRuntime(21440): java.lang.RuntimeException: Unable to start activity ComponentInfo{pcom.example.informee/pcom.example.informee.RegisterUser}: java.lang.IllegalStateException: No receiver allowed to receive

  • chris

    where is “” being used in your sample

    • Mahdi Kenji

      this is my problem too. did you solve it?

      • Laurens Hoogendijk

        GCMIntentService is part of the GCM package (included in libs folder) READ DAMNIT

  • Steven Okerosi

    Thanks so very much

  • nehal

    i’m trying to register user on gcm but it is always giving message “already registered with gcm”, i.e the regid is not returned.. please help…

    • srinath

      Can you please help me

      i am getting this error while testing the above code.

      02-03 20:44:45.273: E/URL(8008): >

      02-03 20:44:50.328: E/GCM Android Example(8008): Failed to register on
      attempt Post failed with error code 403.

    • nasznjoka

      it means you succssfully registered that device

    • Sumit

      Uninstall the app and clear data , then reinstall it , you will get new regId.

  • sam

    how can i display the messages in list view?

    • ria

      did u get any solution?

  • Amir

    i try this code
    but i cant genereate notification when app is stop
    can anyone help me

    • srinath


      Can you please help me

      i am getting this error while testing the above code.

      02-03 20:44:45.273: E/URL(8008): >

      02-03 20:44:50.328: E/GCM Android Example(8008): Failed to register on
      attempt Post failed with error code 403.

  • Bharthi Kannan

    when ever i send msg its not showing in device whats prob any1 help ?

  • Egilang Akbar Rizkyan

    hello, please help me. i didnt receive any message when i try to send message (from gcm_server_php) to the this app. i use same code, i just change the “server_url” , “sender_id” and API key on config.php. i ve tried to use API key for browser, for android and for server, but all of it didnt work. please help me what should i do? or please send me a work code to thanks a lot!

  • Ronak Thacker

    just edit this file then all code working fine….

    NOTE :

    curl is php extension , Enable this extension for php open configuration file php.ini(C:wampinapacheApache2.2.17in) and search for php_curl.dll , and remove semicolon (;) before extension=php_curl.dll line and restart wamp server.

    • Nik Muhammad Amin Nik Muhammad

      i tried you way but seems not working

  • Vanraj

    I Could’t Register dont know whats the matter

  • SengHyun lee

    First of all, Thank you very much Ravi!
    But I have a question. I want to push the message to all users in my server together.(not individual)
    How can I modify PHP code? (Anyone knows?)

  • anil patel

    how to send message more then 1000 from php server?(send_message.php)

  • Bimal chawla

    hllo, please tell me where to convert in php_ini file. i am using ubuntu so not able to find this file. Please give solution asap. thanks.

    • Anubhav

      whereis php5
      in terminal u will get the php location edit the php.ini which exist in apacahe2 folder
      there can be many php.ini so edit only the file reside in the apache2

    • Anubhav

      Another way

      open www folder make any test.php file

      paste the code below

      open the file in browser like



      here u will get full info of the php installed in ur ubuntu
      also from here u can directly get the php.ini file path just CTRL+F on the browser window and search the text php.ini

      Cheer πŸ™‚

      • moataz

        hey plz can you send me test.php to ( i downloaded code but nothing sent to my email thanks πŸ™‚

  • ramabu Mahopo

    Hi Ravi
    Well I must say most of your tutorials are actually very helpful.I do have a question though about push notifications, I have used your code to test PN but it only sends to an individual device so I would like to know how do I send one message to multiple devices that have my app installed? and this also includes some clarity on user notifications i.e how to use collapse_key,Notification key. Anyone who has ideas or point me to the right direction.

    Thanks again!!!

  • sqlsql

    Please let know the SQL query statement

    7 and 8, and the bottom of the source where in?

    Email me the answer

  • anubhav

    Hi Ravi here is a question for you
    What this GCM.jar in inside the libs folder actually i am a c++ programmer little bit unhealthy with this jar and packages πŸ™‚

  • Ritesh

    Hi, I got one problem, as you know GCM is now in Google Play Services. So While implementing the client sideI got error on main Activity on like “GCMRegistrar.—-” , Since we dont have google cloud messaging services available on sdk manager 22.3 , How to adjust this implementation with new google play.

  • Vasudev Vyas

    Hi there was a problem to register while put code in local server.but right now i put you code live on web server but i didnt get any push notification.. plz help…. adv. Thank you

    • Vlado Mihaylov

      Hi, seems i have the same problem, see the post above. Please tell me where is your external server, is it paid or free?

    • bunny

      im getting same problem did u solve ur prblm if yes plz send me solution

    • bunny

      just edit GCM.php .delete space before . apk key…
      and use server key from google….it’ll work..

      • Aung Tun Kyaw

        I can’t found any .apk key in GCM.php. Please, tell me line number. I have the same problem, too.

      • Vasudev Vyas

        Thanx its done.

  • Vlado Mihaylov

    Hello, the emulator registers on GCM and i recieve the message “Demo server:successfully added the device”, however when i browse http://localhost/gcm_server_php/ and refresh several times it still says “No users registered yet” What may be the reason for not storing a successfully registered user in the database? Thank you for your time, please anyone answer!

    • Gyani

      Check if you have access rights to the MySQL in your AMP stack.

  • Mahdi Kenji

    my apps works correctly, but I can’t understand when “GCMIntentService” is called. and I can’t develope this on my app.

    • Joven

      GCMIntentService will be called by GCMBroadcastReceiver when the app receives GCM events (constructor, onRegister,onMessage,onError and onRecoverableError).

      • Mahdi Kenji

        mmm, I see we register GCMBroadcastReceiver on manifest but never define that in code. so is GCMBroadcastReceiver somthing on google serverside that wont need to define in app?

        • Joven

          No need to update the code if we register GCMBroadcastReceiver on the manifest. Also you can register the GCMBroadcastReceiver from the code using Context.registerReceiver().

          We register broadcastreceiver in our application to make it listen from the broadcasts or intents sent by the android system or by other application.

  • Nikhil Raj

    Hello Ravi,
    I worked on your code. After successful run I got Toast notification and message stating that my device is successfully registered. But when I send messages through the php page I didn’t get any push notifications. Please help me if you find any solution

    I worked on both server key and browser app key and compiled and run on 4.2.2 Google Apis virtual device

  • Ritesh Agrawal

    Hello Ravi,

    I worked on your code. After successful run I got Toast notification and message stating that my device is successfully registered. But when I send messages through the php page I didn’t get any push notifications. Please help me if you find any solution

    • daragon

      Hello good sir i face the same problem have you found any solution regarding this? thank you

  • bill

    Hi, Thanks your code is working perfectly for me. just want to send notification to multiple devices at once. Please help.

    • karpaga prasanna

      hey how the server gets registered he didnt uploaded test.php file which i saw in tutorial video

    • neo

      please if he reply to you tell me… this is my email address

  • karpaga prasanna

    guys i’ve a serious doubt…. In the server side program i saw test.php file to get device registered. I saw this in the video.. but its not available in the website any one pls help

    • sri

      Hi Prasanna, download the code and it has test.php file.

      • moataz

        plz can you send it to ( cuz i downloaded the code but i got nothing πŸ™‚

  • vishnu

    Hello, the emulator registers on GCM and i recieve the message “Demo server:successfully added the device”and then it displays “trying attempt(1/5)to register on deviceon demo server”and loop continues till 5/5, however when i browse http://localhost/gcm_server_php/ and refresh several times it still says “No users registered yet” What may be the reason for not storing a successfully registered user in the database? Thank you for your time, please anyone answer!

    • ranjith

      me to have the same problem please help

      • ranjith

        Hi its cleared by creating a database given in this example just copy the code and paste it in sql it works

        • vishnu

          thank you…

    • des

      i also have a same problem, still no users regietered, can anybody help me? thanks

  • HQ

    me too not able to get the message on device

  • dev

    where is code for GCMBroadcastReciever..i m also not getting any message on device due to not calling of this reciever in manifest..i guess..

    • yo

      I use “Key for browser applications” and phone get message .You can try.

  • Jorge Vidal

    ( ! ) SCREAM: Error suppression ignored for( ! ) Fatal error: Call to undefined function curl_init() in C:wampwwwAppNotificaGCM.php on line 41Call Stack#TimeMemoryFunctionLocation10.0007144672{main}( )..register.php:020.0492174336GCM->send_notification( )..register.php:26 help please……!!!

  • Pankaj Kumar

    if anyone can help me with this error: Failed to register Post failed with error code 500 .

    • Naceur Amir

      Have you found a solution for this problem i am in your case please help
      email :

      • arash ataafarin

        you should find ip address of your real device.and replace with

  • sumit

    hello ravi, i saw ur posting it’s very helpful for me to be new in gcm. I am getting some error in my code for gcm based project. I am creating one project on homesecurity so in that i have three button on,off,Home on(i.e. when the person comes to his house). When i press off button then the status of alarm should be register on the given url and so on for rest two off them. But when i click on the button the value is being posted on that specified url but after pressing any of the button my screen becomes blank. So, help me out of this problem…

  • Mohammed alhammouri

    Hi , I am want to make chat app after I knew the basics of sending and reciving messages ,I want to upload the files on server .Does the server needs security or the company that rent me the server give the security for daatbase ….?

  • Luis

    Thank’s androidhive for all the information that you give us, has been very helpful

  • sri

    I am having issue with push notifications.I followed instructions as mentioned. My device is registered with GCM and can see the record in the database however when send push notification from server, not able to receive on the device. Any advise would be greatly appreciated.

    • Gyani

      Have I am facing the same problem, Did you get any solution yet??

      let me know at

      • sri

        i did not get any solution. have posted in stackoverflow too…

      • Gyani

        I have isolated the problem to this: I borrowed sender Id and API key of one of my friends project. I things started working. So if everything works without an error, but still you don’t receive any message , its probably a problem with how you set up the GCM server .

    • sat

      i also got the same problem to solve this i removed the ip restriction in the service API at google developer console. hope it will help you

    • bapu

      you have to take Browser key instead of server or other key as Google Api Keyalso change in sdk api_key file also.all the best

      • riverspart

        It woks! Thank you so much πŸ™‚

  • raghave

    Hi,, I have launched server and Android hive App on emulator but when its starts its throws error “unfortunately Android Hive has stopped ” and when we click OK it come Out , anybody has faced this issue ??

  • ecki kawy

    Hello, this is very nice, but i have problem, in permission is set “GET_ACCOUNTS” , why every time on every device ( already logged in google ) need to enter name and email, can it be cleanded? And how to to that? Please, if anyone have answer, please help me…

  • Mahdi


    Is it possible to use this feature for chatting?

  • DomenicoButtafarro

    Hi friend i have installed all SDK but not have Google Cloud Messaging for Android Library why?

  • Guest

    Hi, I got response {“multicast_id”:7517463785442759525,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1395306753800798%978fee92f9fd7ecd”}]} But not message received.
    Please Help

  • raghav

    Hii ,

    When i install apk on the Emulator , it is not asking for user registration screen directly it si going to scrreen with hardcoded disply in it , and it is not getting register in the server and no reply to mobile emulator as welll.

    Can anybody mail me working code @ it would be great.


  • dev

    is it working for anyone ?? pls help..registration done from gcm..getting saved in local server not sending message to emulator..i have propely followed all steps..created google account,generated browser key is not showing “null” as message after next line of “successfully added device!” …(pls help yaar..kisi ka chal rha h h kya) ??

    • i am facing the same prob πŸ™‚ did you found and solution bro ?

    • ghost188

      Same problem bro if u did solve it can you explain how pls

  • Prashasya Choudhary

    I am unable to receive messages on my device. Although it was working fine in January.I have thoroughly checked, code is fine….IS there any change in GCM service.

    • Sumit

      google is on update so might happen … You didnt got the mail from google???

      • 3Arpit Sharma

        same issue I face previously i configure that and working fine but when confgure in new machine its not work …is it really issue of google..please sent me copy of your mail on my id

  • Pooja

    Please fix PHP Code. I m not receiving Notification in ANdroid Device. πŸ™

    • andrew

      same with here, everything is okay except sending messages from server to gcm>client.
      hoping for your immediate solution.

    • Abdullah

      guys, I had same error. but it worked when I changed to Server Key (using server IP address) instead of using Browser Key.

  • Denisot

    I register device, send token to the backend. About 1 hour I get pushes, but after this time, the server receives a response like this:
    results: [3]
    0: {
    error: “NotRegistered”

    Any idea?

  • NIshal

    Hey dear frd…
    i have send push msg but my devices is not receive notification…
    please give me any solution.

  • you are some kind of god! thanks so much!! πŸ˜€

  • NIshal

    Hey dear frd…
    i have send push msg but my devices is not receive notification…
    please give me any solution.

    help me frd…..

    • saipavan rapolu

      hi nishal,
      iam facing the same problem…do u find any solution pls reply to my mail id:

      • Mohamed Ismail

        iam facing the same problem…do u find any solution pls reply me

        • IrsHaD

          same problem …. can u help me plz

  • Tejashree Kulkarni

    Hey Ravi
    Your Tutorial is good but application is not running on my device and also on emulator please give me solution on this . Due to this i am not able to understand what is error in my code.

    • Nishal

      Run on Google Inc. emulator….
      Best of luck….

  • Nishal

    how to delete msg particulate devices..??
    I am get all msg for database and display in list view after delete msg for particulate devices how to possible..??

  • Ajit Kumar

    Hi, How do I use the same in my existing phone gap project (html5) for android

  • heyyy, i have not able to show the Google cloud library in sdk manager pls help me……..

  • ria

    hey whenever am getting message its show null.. y am i not getting the original msg?

  • Jay Shankar Prasad

    not satisfied with the solve… its not working.

  • i am able to run this application really it’s excellent program to real time…..

  • nantha

    i done setup perfectly..but i didn’t get any message ..when i send from website..

    successfully stored my data’s on server..
    guide me if any mistakes

  • sam

    It did not return null.So where I need to pay attention to? It can not receive messages.

  • ahammed hafees

    Thnx Ravi;
    This code is perfect
    “every thing was working properly still no notification” this was my issue
    i was testing the app in a intranet(WIFI) every thing is smooth but NO NOTIFICATION,then i tried with gprs(2G or 3G) it worked…….Guys try this, may be it can help

    • mohdkhalilsabba

      add permission:

      in your manifest

  • sam

    It can operate in the physical, but the virtual machine can not receive the message. So, Why?

  • Sukhjit

    my program successfully registered my device on the server but was unable to send push notification to device. I found the bug that we need to use server key instead of browser key or api key.

    • Deepak Kanyan

      i also facing

    • kiranjit

      server key is needed

  • mohammed razi

    Cannot resolve GCMregistrar… what to do? pls help…

  • mohammed razi

    how to import;


      • Walox

        add the file gcm.jar to the folder libs of your android project, then click right on the project Build Path -> Configure build path -> add jar, select the gcm.jar and click okey okey

  • Deepak Kanyan

    device successfully registered

    But Message Not reciving on Device

    • Vishal Graak Ror

      message kahan se ayega photo to tna teje ki marriage vali laga rakhi

      • ali

        pobondo ekau koba ni ha?

  • Vany Hosen

    authentication failed for gingerbread. Successfully in ICS but doesn’t receive any push notification. Please Help..

  • Masterwix

    Hello. I can send html into the message? Or an image?
    And if i touch the notification the device show me a screen with the message ” this device is already registered”
    How i can redirect to a new screen?

  • Guest


    when i start the test.php (write data) got the resualt InvalidRegistration

    BTW the data save on MySQL perfectly.
    please help

    • ibrahim disouki

      where is this file test.php??

  • yuval

    Thanks for Source.
    How to send message to all the users?
    How to unregister one user?

    • Masterwix

      Hello. You need to change the php code.
      Im looking for sending links or images to the push message. Thanks

  • ibrahim disouki

    i can’t understand this?
    and where i write it?

    and call the following lines code in private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() presents
    // Waking up mobile if it is sleeping

    // new message code here

    // Releasing wake lock

  • Fer

    HI! first off! thanks for sharing, great tutorial!. I would like to know if this can be accomplished without using google’s servers. I’m building a small app that shouldn’t be connected to the internet at all times and still get notifications from my own server/db.

    Push notifications within a local network? is that even possible at the time?
    (I’m using the laravel framework to implement all my serverside code, I just thought I’d mention it just in case)

  • ishwari

    I have followed every step from this tutorial and also went through the comments and quires,but still not able to get notification on device(or emulator) even though proper register id has got.From server message is also sent successfully to gcm server.but from gcm server no notification received.Please can any one tell me all possible things which have gone wrong..waiting

    • sushant singh

      have you installed google android messaging?? I am able to run it on both device as well as emulator

  • sushant singh

    Thanks for code..I used your code it works perfect..But i think I am missing something thats always a same text print on screen..(Trying to register for demo device)..But when look in database there are 5 entries for that single register. Please Let me know what I am lacking.


    • sushant singh

      Now I am able to run it on emulator as well as device thanks.

    • Nitesh Upadhyay

      Hi Sushant how you solved the problem,I am also facing the same issue..It just says Trying to register device on demo server but not connecting..What am I doing wrong.?

  • Mohamed Ismail

    I have done what you said in php and android.
    If i register from mobile its getting saved in server and if i send notification from php im not getting it received. i have generated the api key through server key

    please help me

    • IrsHaD

      same here help !

  • Jevon

    Thanks for the code.. I am android newbie here.. May i know why is it keep telling me there is not compatible target were found when i try to run the app?

  • Prashant Kumar Katariya

    Hi, I am trying to make screen for broadcast notification in Index.php but I am not getting it how to do it, can anybody help me out…

  • Jyothi Dadi

    device successfully registered
    But Message Not receiving on Device

    can anyone please tell me

    • Bhupendra

      do not place any ip address while registering on Google API console.

      you will get
      Any IP allowed

      in place of ip address and that will work , and if you are going to setup on WAMP then you have to remove comment from the php configuration file for a dll file.

    • azad

      Go to your php.ini file and remove the ; mark from the beginning
      of the following line:


  • AGuismo

    For anyone who is having trouble receiving push notifications there is two importants things:
    1. Check that you created an api server key.
    2. When you create the server key you have to give the ip address in CIDR notation (check on wikipidia CIDR) so you have to give the netmask (for example: x.x.x./0 and not x.x.x.x).

  • Jyothi Dadi

    Hi I checked your post then also i am not receiving messages

  • dhinesh5152

    great great great great great…. working perfectly….

  • lesiaki

    its give me a blank result

  • Nguyα»…n Đình ThαΊ£o

    Thanks very much! I have error : Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in . Please help me! Thanks

  • Elprogramador Incansable

    i don’s see those libraries anywhere… so just can’t do this. I think the “Google Cloud Messagin Library for android” has gone OBSOLETE. so I just can’t follow the tutorial. Now, I’ve read now you have to use the GooglePlay Library to use GCM, but methods have completely changed. So once again, I can’t follow the tutorial :(((((

  • Joombla

    Things are deprecated in this tutorial. I hope Ravi can fix this. Thank you for this site Ravi πŸ™‚

  • Asuej28

    Β‘Excelent tutorial and Resources! Everything is working ok, I only have 3 minor issues:

    1- When I use 3G or 4G to register to my custom server, a occurs, the android project has set the following uses-permission; “android.permission.INTERNET”, “android.permission.ACCESS_NETWORK_STATE”. What might be the problem?

    2- How to avoid the notification if the main activity is on foreground and the message is already on the screen?

    3- How can I remove the notification from the notifications screen and the top screen, when the app is on foreground or pass from background to foreground? This only occur when you select the notification from the notifications screen.

    I hope you can help me with this questions. Thanks in advance. Cheers!

  • Duy Tran

    It working fine. Thx so much. So, I have a problem with M.O.J.O device:
    + It working with wifi network, but can not register with ethernet (COM LAN network)
    Plz help me check it. Thx

  • Mamro Kirill

    This is the old method. Google has changed the code in the direction of simplification.


      Any tutorial link to the new method ?

  • Rakesh

    during php execution it generates following errors

    Fatal error:
    Call to undefined function curl_init() in C:wampwwwgcm_server_phpGCM.php on
    line 31

    • Naz

      I had a similar issue, turns out it randomly fixed itself after I enabled php_curl and php_mysql under PHP Extensions from the taskbar icon of WAMP, and ensure WAMP restarted correctly took a few attempts and about 10 mins for some reason…

  • dsp

    Great tutorial ! Thanks .
    I have developed an IM and been able to send and receive messages from devices.
    Now notification is being generated for every message,but i dont want to show notification if the message is from the same person whom we are chatting with currently.
    Can anyone help me with this

  • Ravi Ranjan Singh

    Good tutorial. Very helpful πŸ™‚

  • vishal gadhiya

    any one help me??
    how to push device to device notification?

  • Virender

    Hi ravi sir

    can we send a push notification from android device to server???

    Please reply

  • Nishu

    Hi,, I have launched server and Android hive App on emulator but when its starts its throws error “unfortunately Android Hive has stopped ” and when we click OK it come Out , anybody has faced this issue ??

    • BalintFarago

      Newbies? This is an advanced tutorial. If your are a newbie forget GCM.

  • Naz

    Thanks Ravi, these tutorials are a great help for us newbies! πŸ™‚

  • Prash

    Hi, do you know any way to unregister the device from the GCM server? Thanks

  • akhila


    I am getting an error. failed to connect to / (port 80): connect failed: ETIMEDOUT (Connection timed out)

    Can someone help me out?

    • arash ataafarin

      you should find ip address of your machine if it is a real device

  • Alex

    Here is a mistake. `Project number` will used as the GCM sender ID

  • Guest

    The code you have on this page have many errors. I am trying to download the code, but it asks to subscribe. I try to subscribe but never get the verification email. Is there any other way to download the code.

  • Rakan

    Im trying to send a notification from the php , but i recieve nothing on my android application … any help ?

  • Thank you very much for providing such a complete, professional and outstanding code. It worked right the first time.

    Just one small thing, Google has changed a few things on its end, now the project ID, or sender ID in your code is called Project Number.

    You should update this tutorial and its screenshots according to the updated interface of Google APIs. Also, subscribing to AndriodHive from my own domains didn’t work, had to subscribe it via my Yahoo! account, look into this as well.

  • Amar Raj

    First of all Thank you very much its very good tutorial. but while using
    and put the submit query it shows
    Deprecated: mysql_connect(): The mysql extension is
    deprecated and will be removed in the future: use mysqli or PDO instead
    in C:wampwwwgcm_server_phpdb_connect.php on line 19
    and down side I got error


    • Vaishali Bhujbal

      Did you create table for database.i got this error due to database was not created.After creating database it worked …

    • Guest

      Hi all,
      I got same error
      {“multicast_id”:5840351441091337667,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]} on submission of form in POST method

      … I created users table in my local host. Why this error is coming ? Please help me..

      Also I need how the PUSH notification is working. Because I don’t know how android mobile applications reacts to this. I am more comfortable to php web applications.

  • Manoj Tiwari

    Hi ,

    Your article is good.I want to send notification to 20 lakh users which is exist in my MYSQL server with GCM registration key. which thing i will do? my all request serve properly.

    currently i am facing a problem when i am sending Push message to all users using PHP.
    message is not deliver to all(20 lakh) users. ????

  • akhil

    php scripts are running perfectly but after installation of app i an getting an error ” From GCM:error(INVALID_SENDER) “

    • Rainer Schleevoigt

      In this case your device token is wrong or your project number

  • J

    Any idea why it always comes up to the registration screen, and if I enter info it says “already registered”? And when notifications come in, I get a status bar update but it never shows me the message on the screen, or any options to unregister.

    I did update the PHP code to use mysqli* functions.

  • Riya Dashoriya

    Well! Thanks a lot for this code. It really helped me to learn a lot!
    Buttt! When I am trying to run the apk on a real device using the same network and ip address of pc, I am not able to store any value in the database (using XAMPP). Kindly help me!

  • Vineel Sadineni

    Everything is good,but when i click on “send” button (from .php page) I’m not able to receive any message!!Please help

  • arash ataafarin

    Finally I Solved the problem of not sending notification to device!
    After you are sure that using correct keys(server key,project number), change line 6 of index.php to this :

    and line 19 of “GCM.php” to this :
    $url = ‘’;

    Ravi please correct these lines.

    • Taha

      which line do you mean ?
      line 19 is blank

      • Taha

        ok i changed it to : $url = ‘’;

        and i deleted this (url: “send_message.php”,)
        is that true ?

        • arash ataafarin

          you should change line 19 of GCM.php to $url = ‘’;

      • RB

        you have to create a server key in order to recieve messages. P.S. a SERVER KEY is required.

  • arun

    Is deprecated now?

  • abhinav


    Thankyou for the wonderful tutorial….

    When I am trying to register via myserver/gcm_server_php/test.php with the three input values, then the– myserver/gcm_server_php/register.php says

    but the values are added in the server database.

    and When I am trying to register with my android phone with name and email address…then after clicking on Register button……It says ——>

    Trying (attempt 1/5) to register device on Demo Server
    Trying (attempt 2/5) to register device on Demo Server ……………………..
    Trying (attempt 5/5) to register device on Demo Server..

    No value save to my online server database.
    Please help…

    • Vaishali Bhujbal


      I got same error – {“multicast_id”:6156241302573131157,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}

      Solution – I forgot to created table table in server database.After creating database its working very well πŸ™‚

      Create table –

      CREATE TABLE IF NOT EXISTS `gcm_users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `gcm_regid` text,
      `name` varchar(50) NOT NULL,
      `email` varchar(255) NOT NULL,
      `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)

      • moataz

        hey plz can you send me test.php to ( i downloaded it but nothing sent in my email

      • Amit Yadav

        I got same Error as moataz..Plz help me

  • Alberto Gaudicos Jr

    do you have updated tutorial about this? GCM is not located anymore at GCM but in Google Play Services already…

    • jrla

      In android SDK Manager click Obsolote and GCM will Apear

  • Alberto Gaudicos Jr

    i can’t locate GCMBaseIntentService and GCMRegistrar, i import google play services rather than GCM because it says deprecated and it already added at google play services. I need the updated tutorial, please update..

  • jigar

    Hii Ravi Tamada… This is a very nice tutorial for newbies and it has worked on my app properly… just want to tell you that few steps are not specified in this tutorial… i would like you to specify them… like Whitelisting the server ip address, deploying the api key. etc… please also specify this steps..

    Thanks for the tutorial

  • TB

    On most devices this code has been working perfectly, but for some reason on one device I tested on it gave me a message:
    “From GCM: error(AUTHENTICATION_FAILED)” and it doesn’t register the device on the database. I looked up the problem in Google’s GCM class and it seems to have something to do with an incorrect password for a google account on the device, which doesn’t make any sense because on all my other devices I can type anything into the “Email” field when registering on the home screen and it still registers fine.

    Anyone else get this error?

  • ShivamDev

    Can we have the same working with Java as I’m not comfortable with PHP.


    • Sathish

      I also need explanation in java..

  • Guest

    Tried example.getting error –


    How can i resolve this?There are many post regarding this but its not solved yet.please tell me anyone

    • Edu ECR

      Hi, I got the same error a few days ago. It seems that the reg_id has to be made in the client side. If you try to prove adding an user only in the server side you will obtain this error.

      So, this error is not important. Everything is OK. Later, if you implement the client side, you could check that the process works properly.

  • Ram

    sir, i’m using WAMP server. and my device is registered successfully and also added to my server. but i’m unable to get the push messages from server to my device.
    i had removed ; also from “php.ini” file .
    and havn’t given any server address while generating API key. and tried to fix it a lot.. but i con’t. plz help me to fix it sir..

    • Ashu

      Hey I am facing same prob let me know if you have got any solution.

      • ashu

        I got the solution, I was creating android key in google console instead of browser key.. Possibly you are doing the same

    • Shubham Singh

      did you got it working?

  • ROPK

    sir, where is the GCM Registration ID from? it can be generated myself or it must be generated by Google?

    • It comes from Google once the device registered with GCM.

  • Hoang

    Thank you very much. Very clear and easy to understand. Work as first run. Just a comment about change project_number

    • I am glad that you got succeeded in the first attempt.

  • Gelli Ravi Kumar

    Hi, Appreciated the tutorial, I have been prepared the setup and every thing went fine. Only one concern is that when I do register from the emulator, I didn’t see any message in the next activity as your device is registered. I have given server_url, and tried both browser key and server key in server side php code, database tables also prepared but no data is populated when I do register in the emulator. But I’m not sure why I couldn’t see the message in the screen after the registration step. Can any one suggest me in this regard.

    • Gelli Ravi Kumar

      Finally, with some changes in the manifest file I achieved this. The registered device ID, name, email are stored in the database, and displayed in index.php too. But, when I enter a message and do click send button, my emulator is not receiving any notification. I’m not able to figure out how to resolve this ?

      • leonidas

        i have the same problem as you , did u manage to fix it ?

        • Gelli Ravi Kumar

          I have connected two real android mobiles such as 4.2.2 and 2.3.3 to the development IDE. From my PhP server, the push notifications are going well only to 4.2.2. but not for 2.3.3. Similarly two emulators of the same kind such as 4.2.2 and 2.3.3 are connected and tried to send notifications. But the emulators couldn’t received them. I’m not aware of why these all happening in a discriminatory way. I’m still try to figure out the technological edge of this problem, may be some expert like the author of the article in this field can give us better understanding.

          • leonidas

            it doesn’t work for me too in both emulator and real device , still wondering where is the problem , may the author help us.

  • dev

    Thanx Ravi..its working after so many attempts over some months…finally its working.
    1)Use server key
    2)attach gcm.jar from extras->google folder
    3)run config.php,db_connect.php and register.php before index.php page
    4)sign-in with your genuine google account in settings->Account&Sync in emulator.
    Once again
    Thanx Ravi.. πŸ™‚

    • Gelli Ravi Kumar

      Hay dev, Good to hear that it is working nice. I’ve followed exactly all the above steps, and even I have also been attempted once with a Server Key and a Browser Key. My app is nicely working for Android 4.* series but come to the Android 2.* and 3.*, the push notification are not at all transferred. Can you share us your experience while facing problems, also on which android real phones, have you been tried out for successful push notifications.

    • You are welcome Dev. I am glad you solved it finally.

    • You are welcome Dev. I am glad you solved it.

      Cheers πŸ™‚

  • kszere

    Can you update to the current time tutorial (new)?

  • Jarobe Bernardo

    i’m new in android and im trying to do this tutorial. when i go to localhost/phpmyadmin the webpage is not available. how can i know if my localhost running on port number ?

    • dev

      go tu your httpd.config file in wamp folder…n write “Allow from your ip address” and “Allow from localhost::1” in the tag n hen restart all the services…then u can see wamp home page opens with ur ip address

      • Jarobe Bernardo

        thank you for your reply. i’m currently developing a mobile shopping app. and i’m looking forward if you can help me please. πŸ™‚

  • An

    Hi Ravi, How Do I remove GCM Registration ID when I registered on device, I want to register more time on one device (to test). Thanks.

  • Shubham Singh

    it works well on local host but not on a 3rd party server. I am able to register my device on the that server but unable to send messages from it to registered devices anyone facing the same problem.

    • An

      I think you have issue with url field in sendPushNotification(id) function.
      In this tutorial is url: “send_message”,
      Please debug network request when you click Send button.
      If you use chrome, F12 select network, you will see the request when click send button.

      • Shubham Singh

        thanks buddy for a quick reply. i am not sure how to see the request as you suggested but i am getting a response message as “Curl failed: Failed to connect to 2a00:1450:4001:c02::5f: Network is unreachable”

    • Abin

      you need to replace
      $url = ‘’; with
      $url = ‘’;
      ok.. try this

      • Shubham Singh

        thanks buddy that worked

  • Hardik Amal

    on localhost it works perfectly but on personal server user gets registered 5 times and mainactivity shows could not register on demo server…also notification thing is not working on personal server but working on localhost…… plz help…… Thanks

    • Shubham Singh

      facing same issue

    • Shubham Singh

      try abin’s solution it worked

  • Sachin Chandra

    Hi all,
    I am getting the below error in my local host.

    {“multicast_id”:5840351441091337667,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]} on submission of form in POST method

    … I created users table in my local host under gcm DB. Why this error is coming ? Please help me..

    Also I need how the PUSH notification is working. Because I don’t know how android mobile applications reacts to this. I am more comfortable to php web applications.

  • Guest

    hey plz anybody can send test.php to ( , i downloded code but nothin sent to my email

  • Ashu

    Dear Ravi, I tried all things of yours message is also coming but no notifications sound and no vibration happens. Phone is vibrating if any other notification comes but not on ur app. Please guide me for this

  • Dario Mirkovski

    Dear All,

    I had the same error of having problems with the notifications on the phone. However, I managed to fix in adding the following line in GCM.php:

    line 25: (Just above the $headers = array(‘Authorization: key=’…)

    Additionally, remember to use Public API access, when defining Credentials at Google Dev Console.

    At of course,at the end, thank to the Author for this marvelous tutorial. Loved it…

    • Thanks Dario for your tip for others πŸ™‚

      • moataz

        thx ravi for your tutorial , i have an error, i clicked on register button the application has stopped and when i checked the error in LogCat thats gave me :

        and error for : GCMRegistrar.checkDevice(this); in MAINACTIVITY

    • Ashu

      Hi Dario I tried what u said but still not sound is coming on my Phone when notification comes and even its now showing also in notification area. Do u have any idea.

      • Do you have any error in LogCat related to sound.

      • Dario Mirkovski

        Well, i guess GCMIntentService uses methods which are already depreciated. Do some research and see. For the notifications, please use the following web site to check if the GCM thing is working and if you set the proper values.

        Insert the Project Code and the API KEY. If everything works, you should get an null message. Otherwise, check the tutorial and set the things i’ve mentioned.

  • MDO

    may god bless you for this great work
    works fine
    just for notice
    every one should replace the server url with its own server ip !! how??
    firstly you should get your machine ip from your cmd:
    go to your cmd -> type “ipconfig”
    then copy the IPV4 adress
    for instance
    then you should know the wamp server port in order to connect to register.php page
    usually the wamp server port is 80
    but in my case i changed to 8080
    so the server url is going to be like this:
    good luck πŸ˜‰

  • bhishm

    sir , my device is registering on demo server but data is not saving on the server database….the total server side work is not working…plz help. thanks.

    • Sarini Tharindya

      I think your database connection is not working..are you changed config.php??

      • bhishm

        Thanx for replying Sarini. Yes i changed my all database detail in config.php but still my data is not going to my server database. Plz help??

        • Sarini Tharindya

          I think Your problem base on Your IP address. check it.

  • Kenito

    I setup this project and it worked at first attempt. Thanks!

    • Rojin George


      this message shows when i run test.php

  • hahahaha

    Alright you sh*t faces, listen up! ADD A SERVER KEY WITH THE IP ADDRESS OF !!

  • adhadimas91

    i have question.

    do gcm need to run add background services?

    so if my phone restart and application does not open yet, it possible retrieve push notification.

    sorry for my bad english

  • ruby

    hi everyone..
    sorry for my broken english… i have few question…

    1. at sdk manager..
    it didnt show gcm unless i click obsolete.. then it will show gcm… its ok??? and my gcm installation are successful

    2. i’ve stuck at avd manager… i can install it but when i try to register my email at ‘account & sync’ it show exchange email… how can i settle it?? because it show “setup could not finish. This server required security features your phone does not support”.. what should i fill in server???

    • Sarini Tharindya

      create another AVD and Try it.

  • Sarini Tharindya

    sir.. my app is working..but if Isend msg from server to device.msg not coming to device. can you help me??

    • ruby

      Hi sarini… can you teach me how to register email on emulator? Do you have to register on exchange email?

      • Sarini Tharindya

        please search in google “how to register email on emulator” and follw 4 th link from to Top. πŸ˜‰

    • Sarini Tharindya

      i sloved it.. i changed my api key as browser api key. thank lot.. very good tutorial. without any error..

      • FM

        i have the same problem can u explain further

        • Sarini Tharindya

          I think you use android key as your api key.. you should create browser key(not android key) in exsiting project , that means which is you used before to generate android key and again create browser key and used it.. πŸ™‚

          • FM

            Do you mean i have to use a browser key as my google api ?

          • Sarini Tharindya

            yep.. πŸ™‚

          • FM

            i tried that it didn’t work. trust me.

          • Guest

            Without details I can’t say any Thing. but i can sent my working project if u like.

          • FM

            that will be great.

          • Jolson

            yes it works on browser key πŸ™‚

      • Venkat Ramarao Potlapalli

        Could you explain it properly please ? i didnt get it

  • Ganesh Jha

    Hello, can anyone help me how can i use cloud’s pop messages on my android device as a command to perform some action .for eg i want to put my phone on vibration mode through that pop message ..? how can i do that..much needed help asap..!! plz


    Hai Ravi..can we run this on real devices? I tried now but i am not getting the notification.please help me .

  • Shubham Singh

    @ravi8x:disqus hi ravi, i noticed that in this tutorial and another tutorial( android-login-and-registration-with-php-mysql-and-sqlite) you use diffrent approaches to send data from device to server(registration) why so

  • Archana K C

    Hi Ravi, i followed the same steps in both android as well a php, its working fine!! i am getting Notification message also.
    But i face one major problem in displaying the message. when application is closed i receive the notification message but when i drag it, the contents will not be displayed. i am getting a blank page. How to get that particular activity when click of notification message.If that view is opened and a new message is sent then it will be shown on that view.

    Kindly someone please let me know the solution….

  • Neeraj Gupta

    I am not getting Notification in My Android Device. Is there any setting in PHP. I changed only in config file username,password,database name and API KEY. that it.

  • Anti Apps

    I am not getting notification in My Android Device.

    I Changed config.php file(PHP) and

    – config.php (Username,Password,Database & Google API Key)

    – (Server URL,Sender ID)

    I am run application in android device and register with NAME & EMAIL. After getting message “From Demo Server : successfully added device!”

    After this message i m go to the database n check table – One row inserted in table with same name and email (It means php connection working very well).

    I am trying to send notification to registered user but not getting notification.

    Please help me.

    • Saad Sheikh

      Same Problem with me..

      • Ashutosh Tiwari

        Any sol ?

    • ap

      same problem with me…

    • ravindra

      My device is not registered with demo server .How can do this….

    • Nathan

      I don’t know if you guys are still having this problem, but it might be an issue with the API key? Make sure you have the right one, and that you have it set the API Access to ‘Any referer allowed’

    • SK Resat

      m2 pls help …..

  • nikolay edison

    first of all thank you for this tutorial that saved my life.
    What if i want to send a message from my device to another registered device?
    Thanks in advance.

  • munam

    anyone have this project in running condition.please can u sebd it to me…i tried but there is alot of errors in it..please if someone have gv it to me

    • saad sheikh

      This is working properly dear..

  • Guest

    Thanks for sharing Ravi Tamada very useful one.I got a following error:

    Failed to register on attempt Post failed with error code 500

    Will you Suggest me to Clear the bug.Thanks in advance

    • Velmurugan Mariyappan

      Hi Sarath,
      i also have same issue in this app(my local server works fine but globally did not,)i tried three days but i cant..please help me..ASAP

      • sarath kumar

        Make sure your “server_url” path in coding.And what is source of internet Proxy or Mobile data???

        • Velmurugan Mariyappan

          Thanks Sarath..

  • Guest

    Displays Error as Could not register Device at Demo server.Please help me to solve the issue @ravi8x:disqus.Thanks in advance

  • Joannes A. Rommers

    If I would like to have one field at the top on the server side that takes a message and sends this to all registered users what should I add or alter? Thanks in advanced. PS very nice tutorial.

  • Pradeep

    Everythign goes fine for me ,But push notification alone not working ? Can any one help me ?? I am trying with my hosting and in real device.

    • pradeep

      I got it πŸ™‚ thanks for this great tutorial πŸ™‚

      • AMOL

        hii plz tell me solution

        • IrsHaD


    • hitesh

      Everything is fine but push notification not working can you please help me,

  • ap

    I am trying since 2-3 days… everything is working without any errors… .but m not getting push notifications. Where could be error ?

    • sarath kumar

      Are you using proxy for internet connection??Proxy does not support push notification.Install gcm test,PushNotificationTester app to check its compability.Congrats

      • ravindra

        My device is not registered with Demo server…..plz help how can to solve this problem

        • sarath kumar

          did you get senderId and Browser API-key ??

  • yogendra G

    Bro wonderful tutorial.Loved it !!. I Almost sat whole to make it work some how and i got few errors like Unauthorized error 401.

    Solution i found was:
    Before generating server key: google for “what is my ip: and give tht ip and local ip address which ever your are getting on command prompt for “ipconfig” command.

    Which made me to get all messages from sent from my local xampp

  • Narendra Kumar

    Hi bro.. I think this url is not working. “” . So, only i am not getting notification. help me

    • Darknoe Bizarosu

      Is your local IP? You must use your IP

  • Very nice tutorial. Too bad it breaks on Android Studio with the new GoogleCloudMessaging and the obsolescence of GCMBaseIntentService. Have you got an update tutorial taking advantage of that? I found little connections between the new library and the old solution you were so kind to offer a tutorial for.

  • Hmatyi

    Hi! Your tutorial is very nice! πŸ˜€
    Everything works well, but i have a question: how can i send a message to all registered users?
    Sorry for my bad english!

    • fernando

      I use a while in php , selecting all the registered ones

      • Alberto

        Hi, how do you use the while? or where?

    • Hendi

      give me a download link of your project, a project I can not send a notification to the client

  • Ved Pawar

    Hi,Thanks for a nice tutorial.I want to know how can I send the user to different activities on notification click. Can I need to take some tag in the push notification message by which I can differentiate the message or any better option is there.

  • sarath kumar

    thanks it works…but it delivers only internet connection is present in mobile,I want to hold the notification when in offline and after delivers the message when internet connect available..Is it possible???Thanks in advance to everyone

  • karlos

    hi!i am having problem to import in android studio, is it compatible??

  • Ram

    hi i am new to android programming i am trying to follow your tutorial but now the GUI of the Google APIs Console page changed when compared to the images so facing problem. any help in this regard

  • Abubaker

    hi i am new in android i am trying to run following toturial but when i click on register button from my device a blank white page pop up and no device register in database please help me

    • Lord Thomas

      Same problem here , successful registration to GCM but blank page and nothing written in DB. If i add everything by myself in DB den ok it can send message to device. What’s wrong?

      • joe

        I suspect it may be your
        SERVER_URL = “ folder name)/register.php”;

        I am using xampp localhost. so i just stuck with the default setting for SERVER_URL and it worked!

      • Loki

        You could use your ip adress for the SERVER_URL string as your ip/gcm/register.db..That’s all. I run it successfully on the Genymotion emulator!

  • Alain Bonnefoy

    I tried to add several informations in the message I send vis send_notification($id,$msg), like that: $msg = array ( “siteName” => $_GET[“pushsitename”], “message” => $_GET[“pushmsg”], “webSite” => $_GET[“pushwebsite”], “date” => $_GET[“pushdate”]); But strangely when I call extras.getString(“message”) for example, the message is empty whereas other fileds are ok. Is there any limitation in the number of value pairs to send?

    • Alain Bonnefoy

      I found the problem; I don’t know where the problem is exactly but any string containing character with accent is not transfered.

  • Abdul Rahman Majeed

    I have set the respond time in database and want to get result from GCM at that time, how can i implement this ???

  • Pham Anh

    i got an error “INVALID_SENDER” but i have entered correctly my project id. It is: focus-electeron-752. May you check for me?

    • Hi, got the same issue

      On your developer dashboard you should find something like project id:focus-electeron-752 and project name: xxxxxxxxxx(JUST NUMBERS)

      enter the project name because that one is the project id but google didnt notice they wrote them incorrectly

  • Laxman Singh

    This is very nice tutorial all is working well i wanted to know that how to display gcm response
    and how to deal with canonical ids for the multiple registration of same device .

    • Ravindra

      Can you explain how gcm device registered in demo server..??

  • soRai

    Hi at! I’ve got a lot of registration ID’s in my MYSQL Database. The Problem what i now have is, that we have TO MUCH “Not Registered” Datasets in our Database. Cause the user deinstalled our app or something else.

    So how can i “grab” the $result and delete them in one step?

    Could you please help me?

  • Jon Morris

    This is a great tutorial, excellent job. Works as followed, however; can you explain why the Registration Layout continues to load even after device has been registered? I have compared to several and reworked in different versions with no luck.

    Maybe you can explain why the app is asking for Username and Email even after registered.

    Thanks so much for your work, very helpful.

  • Akshay Thakare

    I still don’t understand how the GCM registration id is being saved by the app?

    • Pham Anh

      You must open the template by eclipse or android studio then edit the activity files

  • Pham Anh

    How to send notification to a group of users or all user?

  • pofos

    hello. your example work good. but there are 2 problems. when my phone receive the message and i tap at it on the notify center it opens a blank screen. that means all the messages received when the app is not opening wont be saved. second, after i successfully registered my phone to server and close the app then open again, it will be the register screen @.@ (however it still can reeceive message). please help me. my current knowledge does not enable me to solve this πŸ™

  • Usman Maqsood

    What is the purpose of this string “DISPLAY_MESSAGE_ACTION” and how does it serve it?

  • Максим Π“ΡƒΡ€ΠΎΠ²

    Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:wampwwwgcm_server_phpdb_connect.php on line 19

  • hasan

    You have not given code for test.php ?

  • Loki

    I can register and pass all the info in the database. However when I send a message,the push notification thing is not going to my genymotion emulator(it has google play services):(.

    • Loki

      Fixed!! I used the wrong API key!! Thank you my friend. May God bless you!!

  • volpesfuggente

    Hi, thank you very much for this tutorial.
    I have followed your guide for the development of a PUSH service in my app. But if the app is closed (or killed) the push notifications cannot be received. You can I fix this?

  • NhΓ’m VΕ©

    πŸ™‚ Thank ravi for amazing tutorial. But i have a question, how to receive message when force stop app. Waiting for your cmt!

    • TuanAnh

      Them 1 service chay an o duoi.

      • NhΓ’m VΕ©

        Cam on goi y cua b nhe. y ban co phai dung 1 service ben ngoai nhu kieu alarmmanager de nhan msg cua gcm a

  • hasan

    you have attached wrong project to download section.

  • Mainak Devsinha

    thank Ravi for amazing tutorial, but how to show push notification badge count on app icon in android programmatically

  • Guest

    Hello, Thanks for this amazing tutorial, it saved me two years ago.
    But now I try to build the same project, I can register and all, but I cannot receive push notifications, it worked before with this same code, now it doesn’t !!!! anyone with the same problem ?

    • duke cyger

      Maybe U need to Update your GCM library or Change the Key.

  • Alex

    Thank’s for the useful tutorial but I still continue to have some issues!
    Can you provide an example on how myServer can push notifies to registered devices?
    Thank’s in advance

  • Ron

    I can see a lot of question regarding this wonderful tutorial, no question in that.. but i can’t find any answers for those question. It would be great if Mr. Ravi or anyone could help us out with our question to make this tutorial more awesome.

  • waseem ahmad

    how TO Start New Activity ..On CLick Of Notification

    please Answer

    I Started …New Activity
    But Aftr Some Time
    App Is Like started And Main Page Is Opened

  • Stefan

    Hi Ravi, how do I write the PHP code so I can setup a page to send push notifications to multiple registered devices from one text box?

    Your help is very much appreciated.

    Thank You,

  • Rendi Arcanggi

    Hi Ravi. Thank you for the tutorial. I would like to ask you how do I modify the display device one at a time using the button next and prev. if i click next then automatically send a message to the next device.
    Thank you.

  • Manav Patadia

    Great tutorial!!!! thank you πŸ™‚ working fine on eclipse but libraries are not supported in android studio…

  • Fabse

    I have a problem. Every time i get a message and “click” on it, the
    MainActivity is open but its blank, no text. If i leave it open and send
    another message it is displayed. Any ideas why the message show only
    when MainActivity is opened? i try and change into normal intent but
    it is not work..

  • Ercan

    Hello, when i try to send message to device after send button i can’t see on device. what can be problem ?

  • Sunny

    Thanks Android-hive For Great Tutorials.
    Could You Please Make some tutorial on SIP protocol .
    Thanks in advance

  • Hauke Schrills

    Hello , thanks for this tut., I have only one question.: How can I send a Message from my App to the Server?

  • Ronak

    Excellent tutorial. Thanks.

  • Gon Her

    What if we need to send a notice to 10,000 devices?

  • Edwin

    @Ravi Tamada, the only problem i see is that usually even a new app would have 1000+ users and sending notifications to each user is not really efficient..

  • yoon

    Thanks. You are genius

  • Rehan

    Hey Ravi.. First I would like to thank you for providing such helpful and detailed tutorials πŸ™‚ However this tutorial seems to be a bit outdated as Android now uses the Google Play Services for configuring GCM client. Can you please provide us an updated tutorial

  • Gerer Reger

    how can we send gcm message in one click to all the users the code in php does provide option to send message to all users but it has to be done one by one , for each user individually how can we do the same for all users in onclick button

  • zia

    how to by pass registration form if device already registered.
    or redirect to new activity

  • Pankaj Chauhan

    Sir, I want to know is it important to use 3rd-party application server? Can we use GCM without it?

  • Fernando Ybus

    Thank you again!

    • IrsHaD

      is it working’in ??

    • Alika Demon

      wroking and how??

  • azmigiga

    Hi, I have registered my userid and email. I check a gcm_users table and all information is there … gcm_recid,name,email, and date. Successful registration

    Then I run gcm_server_php/index.php from a browser. I keyed in a message and click send button.
    However, my device not getting a message sent. Can some help… what is my problem here. Note I have api key, sender id, url already and been keyed in accordingly.

    • IrsHaD

      same here ?? any solution..

    • Alika Demon

      same here, help plz???

    • Devendra Kumar Singh

      same here please help, what is the problem ???

    • Shovon

      ( No reply from anyone? ) Hi, Could you fix it/make it working?

    • akshay

      I’m facing the same problem.. please answer

  • Fernando Ybus

    I am getting
    Error 401
    on the php and I the php scripts are not saving the data on the DB.
    Can you help?

    • Fernando Ybus

      I got the wrong API. I was using an old one for the Google Maps

  • Ali Arasteh

    That seems really good, but the problem is that GCM needs at least one google account already set on devices below android v 4. many of my users are having old android versions and they do not have google account. is there any alternative?

  • IrsHaD

    registered to GCM but unable to get push notifications ?? @ravi

    • Alika Demon

      i have same problem device added successfully, but can’t get push notification. Heelp men. I’m using emulator API 4.4.2

      • IrsHaD

        @Alika – may be itz the API key I guess causing error !!

        i am using server key n u ?? can u tell me how u are creating API key.. mine also not working πŸ™

        • Alika Demon

          @IrsHaD tried many ways but still no result..
          I used both server key and browse key, but not working…

        • Alika Demon

          If you find the method plz tell me!!

    • Vikas Mittal

      You have to use the Server key – just for testing purpose leave the IP address blank – it will work.

      Later on you might want to insert your IP address where you have hosted the PHP files – that will resolve the issue as well

  • Richard Lagsit
  • sanjay

    Hello. I am having a problem.

    Parse error: in E:wampwwwpush_notificationdb_functions.php on line 3

    I cannot find the problem. Please help me.//

  • Android_Rocks

    Nice Tutorial but one problem i have fetch.
    how to open specific activity .

    my gcm perfect work but by default one activity open.when push notification on my phone come.

    i want to open categories wise activity.

  • Hari krishna

    Hi I have a problem with the above implementation,that is Registration gets expired in 7 days, again i need to reinstall the app when this problem occurs. Can u please tell me how to overcome it from the above code.

  • is deprecated any help ??

  • BabySpook

    GCMRegistrar deprecated. What to do?

  • Matt

    Error:(13, 30) error: package does not exist

  • Mamro Kirill

    This method Deprecated

  • jJ

    please i need private help!
    I am ready to pay u for this! please mail me

  • Firas Salman IΔ±llΔ±lΔ±l

    Hey Mr.ravi Can you provide me with tutorial to (Multicast push notification )

  • Danny

    Ravi, Want to send same Notification to multiple IDs how can do it, can u plz help me??

  • pp

    This is very useful example. Thanks bro…!!! πŸ™‚

  • heilwigkenner

    It is crashing… please help

  • zezo

    Error:(8, 5) uses-sdk:minSdkVersion 8 cannot be smaller than version 9 declared in library

    • zezo

      fix it , i got new error

      Error:(14, 39) error: cannot find symbol class GCMBaseIntentService

      • zezo

        ok its work now but i dont know how πŸ˜€ anyway thank u and i love u πŸ˜€

        • JD

          How does it work? I had the same error

      • KC

        hi, just wanna ask how you were able to fix it?

  • H!s1


    Amazing Tutorial Ravi πŸ™‚
    How can we do the same in Android Studio… And gcm package is obsolete now, what to do ?

  • Virginia

    Hi! Please i need your help, anyone know which one is the max allowed length for a message? Tnx

  • Hello Mr Ravi, I am learning about GCM from your tutorial

    In server side coding I am getting error like this in db_functions.php

    Screen Shot

    Warning: mysqli_query() expects at least 2 parameters, 1 given in C:wampwwwgcm_server_phpdb_functions.php on line 48

    Can you Solve this PLZ

  • DarkLord

    does this work if other user is offline?

  • Safaa Frewan

    PHP 4.x has been dropped , so all mysql functions must be rewritten in mysqli or PDO, I’m trying to do that but some errors still appear !
    Can you help us to rewrite it please ?

  • jj

    please answer this question!
    why did you store data in localhost even though google cloud provides storage facility!??????

  • Umesh Pol

    Hi, Thank you for sharing. I want to add profile photo as well with the registration form. Can you let me know best way to do this, because by using above code if i send image file in string format, it is not working.

  • Guest

    So the summary is, we cannot send message to the device with this code (I tried, no luck) And this code is not for latest google play. Correct me if I am wrong.

  • Shovon

    Unfortunately I have tried this example. I could not manage to send push to the device.
    And each time I click register on the android device, it registers for 4 times on the server.
    What should I do? Thank you.

    • kapil

      hey do you running sample code of GCM notification?

  • Hari Babu

    I am trying this exaple.i found a are using
    PROPERTY_ON_SERVER_EXPIRATION_TIME = “onServerExpirationTime”;
    first time when i rigistered It was not inseted into database but updataed into shared prefs.

    when i am trying to register again you are already registered message is coming.
    the insrt call back nad saving in shared prefs are not synchronized i hink.

    No wi could not know when the time expires, and there is no option to unregistered even if i want to use this in a real project the unregistered code is very important!

    how much time I need to wait for next trial?
    how could i unrigister the user after the temporaray service broken for the user?

  • Shovon


    Is there anyone here who managed to work with this example?

    I could not make it working — my luck! I see this,

    The for loop is running for 5 times in
    and it is registering the app 5 times in my server!

    And then I still cannot send data to the Android! Please help, anyone?

  • kapil

    03-15 15:51:50.548 21848-21848/com.example.sachdeva.testgcm V/GCMBaseIntentServiceοΉ• Acquiring wakelock
    hey code get stuck