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.

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk:
  • 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

    • AbelardoLG

      Hi dashing,

      Please, check the Allow,Deny directives. You should be sure what ips have written there.

      If “Deny localhost” | “Allow (real_server_ip)” | “Deny” are present, you should fix them.


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

      • AbelardoLG

        Hi Hannan,

        Have you checked permissions on server side? Apache (or another web server) HTTPD configuration file should contain the emulator IP in order to get permission.



  • 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


          • ani

            generate new key

    • 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

    • ani

      Guys the problem is with the key.. please generate new key and try works fine πŸ™‚
      thanks ravi πŸ™‚

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

      • ani

        Please try to generate new key and make corresponding changes and try πŸ™‚ works πŸ™‚

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

      • Shovon

        Yes, I used sample code but changed the server-key api-key

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

    • check your api key in config.php i solved this problem.

  • kapil

    03-15 15:51:50.548 21848-21848/com.example.sachdeva.testgcm V/GCMBaseIntentServiceοΉ• Acquiring wakelock
    hey code get stuck

  • Nisha

    Hi Ravi, Thank you very much for this tutorial:) I have one query about server url like What should be the server url? It got working only when I go the system settings->network -> pick the ip address and paste it in server url. But I wants to know what if other user registers with this network address? I am connecting to internet via wifi hotspot of my real device. So registration is successful on this perticular device. And as soon as I try to register from my other device (having its own internet) registration fails:( I don’t understand whether I am giving wrong server url. Please help me to resolve this doubt.

    • If you want to communicate between the devices locally, all the devices should be on the same wifi network. If you want to test it from other devices, you can host the services on a server. So that any device can work using its own internet.

      Try hosting your services on the server as mentioned in the below article

      • Nisha

        Thanks a lot Ravi. But to send a push notification say update is available, I must have to host services on a server right? because all my users would have their own internet. Please correct if I am wrong, actually I dont have much network programming knowledge. Please guide.

  • Vishal gadhiya

    hi ,
    My question is,if same user login in two different devices and 3rd user send notification on your device of that user then both user received that notification or any one?

  • jj

    please answer this question!
    why did you store data in localhost even though google cloud provides storage facility!??????

  • Jahanvi

    Whenever i try to register i only got – trying attempt to register & at last couldn’t register. Please Provide me solution.

  • Safaa Frewan

    The message doesn’t appear on android screen ! where is the problem !

  • Mohamed Arif

    hey.. I coudn’t get this code working in latest android studio. So I tried the same project in Eclipse, Its working now. However this is working only if tried from AVD but when i try from my mobile I get the same error as others!! Any idea why this wont work in real device?

    • Mohamed Arif

      Update: I got it worked.. I replaced the SERVER_URL with my laptop’s IP address and voila, it worked without any problem!!

  • SatishKumar Gollapudi

    Hi Ravi,i am new to android.Thanks a lot for your great tutorial . I got output in serverside upto no users registered yet. after that i strucked, i am unable to find test.php . where can I get test.php please share it to me on

  • Muhammad riaz

    yr ravi avd py chalta ha but mobile py kesy chlaty hain and server ki traf se koy notification b nai aa rha plz sir tell me

    • Momina Nisar

      run in mobile by giving the server url as http://your ip address(of device on which serveris installed)/GCM/register.php and check your server log files and the API Key also

  • Guest

    hey ravi i didn’t make is opening and im writing an email.opening androidhive xml but thats trying on my hosting.when i try on emulat giving GCMRegistrar code error.i added an email for emular but thats not working help ? i added u on facebook ty…
    All ideas welcome.

  • AgorApps Apps

    hi! I hope you can help me, I followed this tutorial and works fine but when I click register button, a toast tell me “Already registered with GCM” and I don’t have any users registered into BD neither into index.php, what is the problem?? thank for your work!

  • Am

    hii,,can anyone help..well it is a repeated question..but i m also going on with same prob. of not getting notification on my emulator..infact i m doing every thing right..using new browser api key,correct project id..and every thing works well but only when i register my device which easily get registered but after sending msg from gcm server does not get notification msg on my emulator….pls help….

  • mojtaba

    Hi Ravi .
    Thank you for your knowledge sharing .
    Dear Ravi i followed your tutorial and another tutorials of other Blogs same as (
    i create push notification with GCM and Parse .
    But always I had a specific problem πŸ™ .
    I have 2 mobile . One of them always is OKay with GCM,parse , ….
    But another one always DOES NOT display notification :
    server say to me :

    now i know does not execute onMessage method in GCMBaseIntentService So i cant see notification .!!!

    But WHY in only one device i have problem ?

    I searched a lot as many days . I cant still find a solution to solve it .

    Thanks .

    • check your api key or try on another hosting.api key will be in ” ” be carry

      • mojtaba

        Thanks for your answer.
        api key will be in ” ” :
        Do you mean this line code?
        Parse.initialize(this, “c99YjlXvIkzdAY7pjmc3JokR89EenG711sqj****”, “fQWH2qrDMGylMfrfJTLrYJQtJ******kF7JXie”);
        “try on another hosting.”
        I bought a Linux host for 1 year.
        Should i change my host ?

        Can i change any configuration of my host to resolve this problem ?

        • not in full project and find config.php you will find at there.look the APΔ° key = ” ” ; write here.

  • Sourabh Rustagi

    Just one advice to all. Make sure that curl is install on your php server

    sudo apt-get install php5-curl

    sudo service apache2 restart

  • Guest

    hey sir i have a problem like this.
    im connecting my server.and im doing all.i wrote email-name and i can see on my index.php.but i opened my app again openin still e-mail adress i want to open activity_main ?

  • Rajiv Gupta

    hi ravi, when i am importing this project on Android studio , getting error like —Error:Could not normalize path for file ‘C:UserstranCTL1AndroidStudioProjectsAndroidPushNotificationsUsingGCMappbuildintermediatesmockable-Google Inc.:Google APIs:8.jar’.

    The filename, directory name, or volume label syntax is incorrect

    and also getting error in php web services

  • gaurav singla

    how i can show a push notification in fragment

  • Bambang Riswanto

    Thanks ravi tamada, it works

  • Ravi hello i added this project in my app.But i got a problem about checking user.i added a button and that button opening registering and seeing notifications.xml i can send message on server everythink okey but im closing app and deleting on RAM.after im starting again app.then i clicking that button opening again ? i want to if user saved on sql – open directly notifications.xml but user seeing again register.xml πŸ™ how can i solve this?

  • gun

    hi Ravi where is layout of activity_main.xml, because textview for lblMessage not detected, please helidp…. Im new to android…thanks

  • NItesh Kumar

    my android device is registred but in browserr cannot send the notification into my device .. i can use both android mobile and blue strack but no change same problem face me.

    • Sandeep Gupta

      solve the issue, in config.php check define(“GOOGLE_API_KEY”, “AIPLPLSPLSb3r8RaXaHwTNwCRxSz2PPPPP-tccFnlo”); should not be blank, use your API key

  • Sandeep Gupta

    i send the message from PHP server to mobile but didn’t receive any notification to the mobile. what to do ?

    • Sandeep Gupta

      solve the issue, in config.php API key was missing.

  • Ankit Varia

    What if the app is uninstalled from the phone ?

  • RevHacker

    GCMRegisterar is deprecated, what to do?

  • jj

    Hello sir,

    I made a for Loop to send the message to all IDs…
    for 1st device the message remains as orginal!
    for 2nd device the message is recieved as (price->message)
    for 3rd device the message is recieved as (price->price->message) and So ON!
    please HELP!! URGENTTTTT πŸ™

  • Deni Firdaus Waruwu

    Hi Ravi Tamada, I try to use this code but it’s not working, but there is no error message also.
    I only get message from Toast function that said ‘Already registered with GCM’ in a blank view.

    Can you help me please?

  • zero

    Please help as Android app is working it is registered in demo server but in server it is not showing any devices.

  • rokon

    when i am sending a message from server. No notification will be send to the device. please help me.

  • Frank Lin

    Excuse me,can you show me how to multicast notification for many devices at the same time?

  • infotech

    Dear Sir I get the following problem

  • infotech

    dear sir i get the error .
    registration is done successfully but when we send the message from server to device or emulator, than message will not come .and in the beaning as your video show the null after registration , i am not getting that null value also. so please help me .

    Please revert me. ASAP i am in trouble…

  • despiyado

    successful working.I congratulate you are.

  • Ajay Parashar

    i configure same as it is. but i am not getting null when device is connected from server . and i am unable to send mess from server to device. please help me .

    • Ranjith Kumar

      Hello Ajay Parashar,

      If you are using XAMPP means then your need to enable this extension=php_curl.dll. To enable curl follow below steps..

      Step 1:

      Browse and open the following 3 files

      C:Program Filesxamppapachebinphp.ini
      C:Program Filesxamppphpphp.ini
      C:Program Filesxamppphpphp4php.ini

      Step 2:

      Uncomment the following line in your php.ini file by removing the semicolon (;).


      After that it will look something like something below-


      Step 3:

      Restart your Apache server.

      • Ajay Parashar

        Hello Ranjith Kumar,

        I am using wamp server. and i enable extension=php_curl.dll. I done all the step which you describe in your post. but i am unable to get the message from server. and now i am get the one error line like below

        E/GCMRegistrar(1677): internal error: retry receiver class not set yet.

        Please help me.

        • Ranjith Kumar

          Hello Ajay

          You can try with xampp, then it will works fine

          • Aditya Hari Kishan

            Hi Ranjith I am facing same issue in XAMPP server can you help me in fixing it

  • Priti RΓ€Ε₯Δ₯ΓΈΓ°

    error in logcat of error 404 >

    log message displat -> internal error: retry receiver class not set yet

    How can i solve this please help me out?

    • Gaurav Sharma

      change your url to http://“your ip address”/gcm_server_php/register.php

  • Ranjith Kumar

    Hi Ravi, Awesome tutorial for push notification in android. I have doubt while creating multicast push notification. In my application i need to send one message to multiple gcm regid but i cant figure it out.

    How to solve this ?…

  • Krishan

    Just now i tried it is saying service is not available.

  • Sanjiv

    Hi Sire,it’ s Awesome tutorial for push notification in android. I have trouble while creating multicast push notification. In my application i need to send one message to multiple gcm regid but i cant figure it out.

    • gaganpreet singh

      m also stuck with same problem . please help me too…

  • i run this example but i got this error can any one help for solve this i put the server code in my live server.
    its register sucessfully but when i tried to send message to register person its got the error
    Curl failed: Failed to connect to 2607:f8b0:4000:80b::200a: Network is unreachable

    • chand becse

      U don’t generating the apk with ip address.just try to without any ip addres (it’s empty).

      • static final String SERVER_URL = “”;
        // Google project id
        static final String SENDER_ID = “163235273017”;

        i put this code but nt get the push notification.

  • Sanjiv

    how can i use one push notification form for multi android device.

  • Pranav Mittal

    hi i am getting “Curl failed: Failed to connect to 2607:f8b0:4000:80a::200a: Network is unreachable” when send message from server to device.

  • Kenny


    Amazing Amazing Amazing,

    Greetings from South Africa πŸ™‚

    I have been developing for over 10 years mainly LAMP projects, and its time to move on.

    Android the logical step for me.

    I have been working through all your tutorials and everything you do makes perfect sense, all your tutorials are first class and a great resource for beginners and advanced users alike.

    with a little tweaking it is easy to extend on your base tutorials and add them together to make a perfect app.

    Once again thanks for all your efforts they are really apreacieated


    • Thanks Kenny.

      I am glad my tutorials helped you a lot πŸ™‚

      • jeeva

        really nice tutorial,here every thing working fine for me,but i didn’t get notification,
        Kindly do the need full.

  • rahul kumar


    Dear sir

    Thats really nice, but i have a problem could you plz tell me how can i use this in codeigniter mvc framework.

  • Prasanna Davu

    Hi Ravi I Like Your utorials Very Well Its Very Usefull For us,I requested you to do the Artical on Tracking System using MySql and PHP

  • xyz

    how to link my previous code with dis push notification??

  • Mahdi Kenji

    i’ts not work on api 9 why?

  • jerom

    the GCm part works really well, but we have a problem with the registration part, when

    1) when we do not use app for few days it would ask to register again

    2) if we use apps like to clean master to free memory it will again ask for registration, how can we prevent this

    • Josh Holiday

      Just save that the device is registered in the APP in a shared preference

  • Mannu

    Hi Ravi, Its a great article.
    I like your interest in sharing your knowledge. I have seen that the GCM library is deprecated and google imposing to have it through cloud service. So, is it possible for you to help me to upgrade your solution to consume latest api.


  • Momina Nisar

    Thanks a lot for this awesome tutorial.This is awesome and is working nice.
    I want to check through GCM that if the server data is changed and then send notification to the android app.Can you please help me in this respect.

  • Kumar

    nice explanation

  • Danial Habibi

    Hi Ravi in this tutorial u only send one push to one device..what if we want to push notification to all device that has been registered?should we just use loop the send function at the php server or there’s another appropriate way to do this? Thx

    • gaganpreet singh

      hi @danialhabibi:disqus, sir …. Have u done it ??? single notification to all the registered devices at once ????????????? please help me. even i am unable to do it

  • Devendra Mahajan

    Sir plz help me i follow all those steps but not receive any notification.n code is run successfully.

  • Devendra Mahajan

    plz help me i want this code.if any buddy run this proper way then plz send me code
    my mail is

  • Gaurav Sharma

    “Receiver not registered” i am getting this error anybody can help me ??

  • Hi, I’ve been able to set up the server side, and app, but when I try to send a message I don’t receive anything.

    • Alika Demon

      try with real device smratphones.

      • Trevor Hanes

        I have, I’m testing it on a live server and Samsung Galaxy Note and S4

        • gaganpreet singh

          make sure u r using correct server API key in config.php

  • Pranjal

    where to add the .jar file

    • Ashik Rahman

      lib folder of your project file location.

  • Akee aggarwal

    not receiving notification if app is closed or not running.

    • Alika Demon

      lasy ass πŸ˜€

  • Saurabh Baranwal

    can i get php coding in java..

  • Anita ChΓ‘vez

    Hi, I have an error on this line:


    Please somebody help me.

    06-11 17:04:04.180: E/AndroidRuntime(1725): FATAL EXCEPTION: main

    06-11 17:04:04.180: E/AndroidRuntime(1725): Process: com.androidhive.pushnotifications, PID: 1725

    06-11 17:04:04.180: E/AndroidRuntime(1725): java.lang.NoClassDefFoundError:

    06-11 17:04:04.180: E/AndroidRuntime(1725): at com.androidhive.pushnotifications.MainActivity.onCreate(

    06-11 17:04:04.180: E/AndroidRuntime(1725): at

    06-11 17:04:04.180: E/AndroidRuntime(1725): at

    06-11 17:04:04.180: E/AndroidRuntime(1725): at

    06-11 17:04:04.180: E/AndroidRuntime(1725): at

    06-11 17:04:04.180: E/AndroidRuntime(1725): at$800(

    06-11 17:04:04.180: E/AndroidRuntime(1725): at$H.handleMessage(

    06-11 17:04:04.180: E/AndroidRuntime(1725): at android.os.Handler.dispatchMessage(

    06-11 17:04:04.180: E/AndroidRuntime(1725): at android.os.Looper.loop(

    06-11 17:04:04.180: E/AndroidRuntime(1725): at

    06-11 17:04:04.180: E/AndroidRuntime(1725): at java.lang.reflect.Method.invokeNative(Native Method)

    06-11 17:04:04.180: E/AndroidRuntime(1725): at java.lang.reflect.Method.invoke(

    06-11 17:04:04.180: E/AndroidRuntime(1725): at$

    06-11 17:04:04.180: E/AndroidRuntime(1725): at

    06-11 17:04:04.180: E/AndroidRuntime(1725): at dalvik.system.NativeStart.main(Native Method)

  • Trallallero

    Thanks for the tutorial but I have some problems.

    I tried to use the key for server applications, for android applications and for browser applications and I always get a success message like

    but I never receive a message on the device. What could be the reason ? My sender id and api key are ok.

  • parakh singhal

    on impleming this code,,i get a msg in my phone for successful registration but on server it’s still showing no devices registered yet..actually my database is showing empty gcm_users..i don’t know why?

    • gaganpreet singh

      actually the url u have given in may b wrong. give it according to th proper path where is stored

  • latiful anwar

    Dear Ravi
    I have followed this tutorials and result is ok, but i want to send notification with device (not with index.php or send_message.php ) can you explain this? thank you from Indonesia.

  • Nagesh Chinna

    can anyone tell where can i find the notification messages received???

  • Can you make this tutorial with Android Studio

  • Anuja

    can you tell in which class of android call send_message.php to get notification in android

  • Fabian


    I followed the tutorial. But I’m locked in one place and do not see how to solve the problem. I can not add anything to the database and do not understand why.

    Can you help me?

    Thank You.

    • apurva

      hey did you find solution? I am stuck at same thing.

    • Jay Aegis

      can you show us your code.?

  • Vij

    Everything working fine. emulator doesn’t receive the notification which was sent fro localhost. so can you please help me… @ravi8x:disqus …

    • gaganpreet singh

      u hve to login to playstore in emulator

  • Moses Mwongela

    I updated @RaviTamada’s project to the latest GCM API. Find the source code of the android application and gcm php server at

  • saish neugi

    Hello Ravi Tamada, your android code seems to work perfectly. But there is some issue with your curl script. It gives an error in the console saying “Error 411 (Length Required)!!1”. Do you or anyone here in this discussion active have any idea about this.?

  • apurva

    @ravi8x:disqus I am getting invalid registartion error agin and again and not able to register device. please help me out.

  • Rajeev Sharma

    I configured androidhive push notifications android client and on php server. I am getting GCM Push

    messages Notification in Android Notification area but when i click on android notification area

    message does not show in androidhive push notification app instead it says device already registered.

    Also if I want to include Notifications in another app how it is done so messages open properly in that app. Both the app will run or first one can be uninstalled as all code of register id push message will be included in second app.

  • Huy HΓ³m Hỉnh

    I changed package of GCMIntentService and it didn’t work. How can I re-config it? Tks!

  • Karishma

    I think you should update this tutorial to accommodate changes to GCM framework i.e GDMRegistrar() is no longer available. InstanceID should be used now which is fairly easy but just to maintain the validity of this article as its quite thorough and I like that you included server side impl as that is exactly what I was looking for. Will post once I actually start working on GCM. Thanks! πŸ™‚

    • Yes, everything is deprecated. I’ll update this article after couple of articles.

      • Moses Mwongela

        Hello Ravi Tamada, I have updated this tutorial to the latest API. please check it here >>

        • Thank You Moses. This is very useful πŸ™‚

        • Guilherme Schumacher

          No, it`s not… Still using mysql instead of mysqli…

  • Piyush Sharma

    Hello everyone.. I’m facing a problem here
    Whenever i try to register the app stops. And i get a notification that Unfortunately, Androidhive gcm stopped. Help me out here

    • Check the LogCat for errors.

      • gaganpreet singh

        sir kindly tell me how can i send the same message to all the registered devices . Really need to know …

    • Moses Mwongela

      Here is a corrected app.. >>

      • Andro

        Sorry but i never ever seen such a UNCLEAN and UGLY code. Don’t post links full of bugs, please!

      • Andro

        Beware, the here mentioned “corrected app” registers twice. Take time and remove those bugs, please.

  • Jaye

    I have a question. If you log out, do you need to unregister regId? Does signing back again with the same account needs to register a new regId or the old regId will be fine?

    • Andro

      Log out? What do you mean? You quit the app, thats not a logout action. Build your own unregister action (Settings or button click) to remove from GCM and from php backend.

  • gaganpreet singh

    please help me . i want to get notification at once to all the device id those are registered with gcm

  • Hi have update the code with new api changes check here

  • Akshobhya Aksho

    hi everyone there are quite a lots of bugs for the current users as Android is not supporting for that GCMRegister.rar import and also its hard for the developers of android studio to implement please need help badly

    • gaganpreet singh

      no, there are no bugs as such. This project is easily imported in Eclipse IDE . and there are just 2 changes to be done in android code in file . ie. sender ID and registration url. Nothing else. and there are few things to be changed in just one single php file – config.php . ie. server name, user name, password, databasename, api key. It perfectly works.

      • Akshobhya Aksho

        HI I’m not that greatly exposed to the ecllipse IDE but i started learning in android studio and in that the packages that are being imported in this program ( are not working they have been deprecated πŸ™

  • Chethan Sreenivasa

    First I appreciate Ravi For sharing his knowledge…

    When the I run the PHP file using wamp in browser http://localhost/gcm_server_php/….. I am getting the error like…1.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
    2. Warning: mysql_connect(): in C:wampwwwgcm_server_phpdb_connect.php on line 19
    3. Deprecated: mysql_select_db(): 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 21

    Pls help out to solve this………

    • asdebugger

      error_reporting(E_STRICT) put that code after <?php
      mysql_ function deprecated in php 5.x(forgot) above

  • Lahiru Ruwan

    {“multicast_id”:5104103577689627894,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]} I got this error any one can help to solve this..

    • Vicky Bagaskoro

      i got same problem, are you have know the problem?

  • Alvarro

    Thank you so much, if you guys want to make it work you have to spend hours, but it really work! and i’m just a newby πŸ™‚

  • Flavio Maruf;
    notification.setLatestEventInfo(context, title, message, intent);

    Cannot resolve method -> setLatestEventInfo.

    Full error: Error:(104, 21) error: cannot find symbol method setLatestEventInfo(Context,String,String,PendingIntent)

    • Lakshay Saini

      Same error man!! so irritating! πŸ™ plus i have this error also! πŸ˜›
      lblMessage = (TextView) findViewById(;
      Error:(70, 50) error: cannot find symbol variable lblMessage

  • Mithun S

    Application getting forcefully closed.. what to do?

  • Libyan Joey

    what changes that i should make in php files except changing (username , password and database name) in config file ?

  • pranesh

    can new user receive the all past pushed notifications?

  • loe


    Is the $json=array() necessary? What is it’s use?

  • Nak

    C2DM will not available after 20th Oct’15. So can you update your post with new Cloud Messaging example.

  • Pushpender Bhandari

    can you please provide the tutorials for sending Device to Device push notification?

  • Shubham Tile

    hello sir i will follow above all step but there was an problem when i register from device then register succussfully bu when i sen message from php file then cannot recive message or notification to mobile…

  • Josee Naava

    error {“multicast_id”:9021751049721869446,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]} como lo solucionoΒΏ

  • Lakshay Saini

    Hi, Thanks a lot for this tutorial! i have a small freaking error. πŸ˜›
    whats the or R.drawable.success, etc.. It says cannot resolve symbol R..
    can anyone help? thanks!

    • is id of a TextView
      R.drawable.success – you can find this image in downloaded source code folder.

      • Lakshay Saini

        fixed that.. now i have these errors
        on this

        lblMessage = (TextView) findViewById(;
        Error:(70, 50) error: cannot find symbol variable lblMessage

        aand another one on GCMIntentService

        notification.setLatestEventInfo(context, title, message, intent);
        Error:(108, 21) error: cannot find symbol method setLatestEventInfo(Context,String,String,PendingIntent)

        • Yogesh

          I think u are working on sdk version 23 … that,s why this error occurs … you can try it by changing sdk version to 22

  • Josee Naava

    I got this error any one can help to solve this..

    • Rizwan Zahid

      check the db that if you are getting the correct device id on registration.
      beccause this error says you dont have the correct device id in your database.

  • Carlos

    I try to download the code but I
    can’t subscribe 😐

  • amit basliyal

    hey nice tutorial but i want sent big pic style this type notification
    please suggest some mathod in your code

  • Abhigyan sen

    Thanks for the post πŸ™‚ , can you please update the post with new Google Cloud Messaging?

  • Android Example

    hey friends you can download the code frome here ………..

  • ratt

    the code is working fine ,my device is registered to the server but when i try to send message from the server it never sends to the device,,i mean after pressing send button at the simple admin panel no action is done

    • Ravneet

      same here

  • Harshal Pathak

    This code is working fine but notification is not getting generated when app is closed

  • Dimas Andrianto Setiawan

    where is test.php ???????

  • Dimas Andrianto Setiawan

    i got an error when running php please help me

  • Harry Smith

    Nice article thanks ravi.

    • Dimas Andrianto Setiawan

      do you use anddroid studio? or eclips??

      • Harry Smith

        Android studio

        • Nurrochman Ferdiansyah

          I’m using android studio, but there’s some error :
          error: package does not exist

  • Shashikant Farakate

    hey nice tutorial but I get some device is getting registered but when I try to send message from php to android app my app doesn’t recieving the notification.
    Android Monitor shows Error :
    10-05 21:25:05.154 443-498/com.example.shashi.pushnotification E/GMPM: getGoogleAppId failed with status: 10

    10-05 21:25:05.156 443-498/com.example.shashi.pushnotification E/GMPM: Uploading is not possible. App measurement disabled

    10-05 21:26:02.572 443-1181/com.example.shashi.pushnotification E/GCMRegistrar: internal error: retry receiver class not set yet

    10-05 21:26:02.585 443-1181/com.example.shashi.pushnotification E/URL: >

    10-05 21:26:44.331 443-1181/com.example.shashi.pushnotification E/shiashi GCM: Failed to register on attempt Post failed with error code 500

    • anuarg0022

      same here..please help

  • Nurrochman Ferdiansyah

    Anyone here use android studio to create this tutorial????
    i have problem when trying to import GCM. It’s like android studio didn’t recognize :
    Please Help πŸ™

    • Madson Gr

      did you try to compile on gradle? add this on the dependencies: compile ‘’

      and this one at the top: apply plugin: ‘’

      • Nurrochman Ferdiansyah

        Thanks for your response.
        i have solve it, when i add this on dependencies : ‘compile ‘’ . It’s still have same error.
        so i add gcm.jar manually then call it on gradle.

    • Because GCMBaseIntentService is deprecated

      • sujesh

        how to solve this issue

  • Dimas Andrianto Setiawan

    does anyone know what is test.php ??on the video ??? please

  • Vikram Kodag

    Hi, Thanks a lot for this tutorial! i have no errors at all . But i receiving notification message null from server at all time.please help me…thank u in advance.

  • Madson Gr

    Still using deprecated mysql?? Could you please update php codes to mysqli?

    • Atish Agrawal

      just add ‘@’ before the mysql_connect command in db_connect.php

  • zatyAbdullah

    works perfectly. will be great if u could share how to send push notification to multiple devices.

    • Dimas Andrianto Setiawan

      i didnt get the notif when i send in php server ,could you help me???

      • zatyAbdullah

        are u using cloud srver or local server..

        • Dimas Andrianto Setiawan

          im using xampp,local sever ,please help

  • pokala varun

    i am getting trying to register on demo server but its not registering plzz help me

  • Dimas Andrianto Setiawan

    hi why “setLatestEventInfo” in GcmIntentservice cannot find method?????

    • Pritish Joshi

      Its depcrecated in API 23
      Use Notification Builder

  • phan piseth

    cannot get id

  • Dimas Andrianto Setiawan

    {“multicast_id”:9008003352184322123,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”MismatchSenderId”}]},,, i got error this please help

  • Bhavik Shah

    Thanks alot for the tutorial its very descriptive and well formed.
    But I’m getting a problem the notification is not getting displayed on Notification Bar. I mean the text which is sent is not getting displayed only the App Name is Displayed and not the preview of the message

  • Ricky sharma

    i have not RECIVE subscribe MAIL

  • John Adjognidje

    Hi thanks for the tutorial i try to run with android studio on my xperia but i got this :
    From GCM : recoverable error (SERVICE_NOT_AVAILABLE) repeating…..Please Help… thanks in advance

  • Mohammed Almihdar

    Ok… so how do I send bulk notification to all registered devices? I don’t want to have to use the index.php for every notification… I may have 100+ devices registered.

  • Nishant Meena

    The method setLatestEventInfo(Context, String, String, PendingIntent) is undefined for the type Notification

    • Aviansh

      Notification.setLatestEventInfo() is removed in API Level 23

      • Prabhakar Purplepro Infotech

        so what is the solution for it

        • Pritish Joshi

          Notification noti = new Notification.Builder(context)

          notificationManager.notify(0, noti);

  • Nishant Meena

    Warning: mysql_connect(): Access denied for user ‘root’@’localhost’ (using password: YES) in C:xampphtdocsgcm_server_phpdb_connect.php on line 19

    how to solve this error i have no idea about the php mysql

    • Vivek Kurien

      Please check the whether the mysql have password, also check the port of mysql.

    • Atish Agrawal

      just add ‘@’ before the mysql_connect command in db_connect.php

  • Alvaro Rivera

    hi, is there any way to send the same notification to all registered devices?

  • Christian

    it does not work on my android studio:( error on the package then i downloaded a gcm.jar added it then the app run but when i try to register it cannot connect to the server and the just show a blank white space.. please help

  • Christian

    Anyone here who have got this project running in their android studio recently? Need Help badly..Thanks

    • yes, I have tried on Android studio

      • Christian

        Hi Rakhi. Could you send me your sample zipped project? i can’t seem to figure out what is wrong with my trials on making this thing work.. Thank you..and maybe some pointers on what you did. I’m really new to android hope you would help. Here is my email

      • cim gap

        Hello Rakhi,
        I would be very happy if you could help me and send me your files.
        While I am a php developer, I want to learn more about creating Android apps
        I am using the latest version of AndroidStudio and I would like to test this app.

        On the other hand if you would have time to create some for me (very simple), that would be great also – we could discuss this in detail if you are interested.

        My email adress is: cimgap [at]
        Many thanks in advance!

      • Bilal Khalid

        Hey rakhi can you please send your Android Studio code i am facing some problem while building?
        My email:

      • sandeep dhayal

        hi rakhi, send me too, thanks

      • Muhammed Jasil

        hi Rakhi,
        i am struggling to implement push notification using android studio, it ll be a great if u help me. please send me your code. my email –

        thank you.

      • Pradhuman Dhakad

        hi Rakhi,
        I have Some problem with android studio.
        can you help me with send me your code at my email

        please . Thanks

      • Mahesh D

        Hi Rakhi,
        Can you Please share your code to my email

      • min ho

        I have Some problem with android studio.
        can you help me with send me your code at my email

        thank you

      • Amit yadav

        hi , please can u send me your android studio project on my mail id.-

        i have some problem – device registration id is not right

        Could not find class ‘’, referenced from method

        getGoogleAppId failed with status: 10

        12-22 13:16:49.955 22476-22492/com.yadav.delmedix E/GMPM: Uploading is not possible. App measurement disabled

        please check this device id:-

      • Eng Dabour

        me too Rakhi please send me code on

      • Tejas Dhawale

        me to please m stuck with dependencies please send me code too

      • Kanchaporn

        Hi, Rakhi Dhavale
        I’m a newbie in android. Could you send me your code that work on android studio? I have tried to use the code from this article to send notification to registered android devices. I adjusted some code due to some syntax is deprecated. Now, the project can run without error but GCM function did not work including regID does not generate. please help me to solve this problem. My email:

      • Akash kumar

        In file, if i have wamp localhost then url should be passed as same as given or should include ip address, I am getting error ” Failed to register on attempt ” socketserver timeout, pleasehelp to resolve this issue, only URL issue I have

      • Wysnu

        Hallo Rakhi Dhavale,

        I have problem with android studio, can you help me with send me your code at :


        • I have implemented exactly the same code as mentioned in the post, just read the documentation on firebase at , its not any rocket science, they have explained in the most easy language that anyone would understand !

  • I please request you to update this article on GCM on your blog. GCM3.0 has been rolled out and many features have been introduced, for example topic messaging . An application can create one or more topics and register clients to each topic. Then messages are sent for a specific topic, GCM informing all clients who have been registered for it. This way one can reach a large number of clients, even all of them. Google I/O 2015 talks on GCM

    • Yes, I need to update. Got busy with few projects …

      • Hussam Aldin

        Ok when you do that am really in trouble with the new one πŸ™

  • Shijin Krishna

    Hi Ravi,

    Thanks a lot for the blog post!

    I am not familiar with native android app development. But currently I have requirement to send push notifications to already existing app which our customer is using.

    Would it be possible to upgrade the existing app’s code to receive notifications via GCM?
    Please let me know.

    Thanks in advance!
    -Shijin Krishna

  • Naina Jain

    I had issue clicking on notification on notification bar which is not opening desired Activity of that particular android application. how to do please share the code i have implemented gcm in my android application using this link :- thanks

  • Varun

    You can also use this nifty GCM Notification Test Tool –

  • Jian Carlo Gelacio

    why i cant received push message in my android phone???

  • Mark

    im stuck with trying (attempt) to register device on Demo Server

    • Mark

      Do i need the clould platform running ? i did create a project, get the api key and senders id

  • Vaibhav Kadam

    I have done with setting up. But whenever I click on send from server PushNotification is not carrying out.. please help

    • Vaibhav Kadam

      Problem was with API. We have to use browser’s API. Thank U ravi sir for this post

  • Rishab Ghanti

    Is it okay to use this code since google cloud messaging library for Android has been deprecated or is it preferable to use the newer version?

  • Arhaan Khan

    Where is test.php..??

  • Fabi

    I hope you can update this topic πŸ™ didn’t worked for me..

  • Sahil

    Hello Everyone!!!
    I have implemented GCM in my app by following this tutorial and tested that on various devices and in most of the devices it worked fine but I some devices like YU Android device, the notification only arrives when the app get opened. How to resolve it?
    Thanks in Advance…

    • Serious Sam

      Late reply I guess, however am posting for others to see. Set the delay_while_idle flag to false. If still in doubt, do a quick google search with the flag as the search term.

      • Everything is deprecated. Wait for 1 week for new article!

  • Arunkrishna k.k

    i got an Toast while this app is running “Invalid _Sender

  • Mohanraj Subramaniam

    I have referred lot’s of websites, but there lags clear picture of sending Push notifications using Intel XDK.. Any idea tech geek’s…

  • Bhavik Shah

    How to use same thing in Fragments?

  • Amarbir Singh

    Ravi please update your post some classes and functions are deprecated.

    • I am posting newer version of this article in 1 week time.

  • Raghav Satyadev

    @ravi8x:disqus please send the link of the updated version of this topic whenever you get it ready on “” it will be very helpful.

  • Dimas Prasetio

    hey Ravi, how if I wanna send message to all device ?

    • Please check back after 1 week. I am posting a newer version of this article using GCM 3.0

      In this article:
      If you want to send to multiple devices, send the gcm registration ids as an array to below function

      $registatoin_ids = array(‘regid 1’, ‘regid 2’, ‘regid 3’);

      $gcm->send_notification($registatoin_ids, $message)

      • Ibrahim Samad

        Nice tutorial…
        But on the issue of sending to many users, Will you have to always include all those users ids yourself? What if you want it that anybody who install the app should be able to receive the notification automatically?
        It might sound naive, But I can’t figure it out…Thanks.

        • Its called topic messaging and it was introduced in GCM 3.0 (I am explaining it in next article)

          Mean while supports topic messaging. Please check the below article.

          • Bhushan Shirwalkar

            bro.. i ran ur project.. did all steps carefully.. m able to register user in php db localhost from mobile.. but unable to push any message..when i created new project in google developer console page.. these are the details

            project link:

            Project ID:

            Project number:

            and this is what i put in

            static final String SERVER_URL = “”;

            static final String SENDER_ID = “pushgcm-1204”;

            still not able to send push but able to register.. anything wrong??

          • Raisel

            static final String SENDER_ID = Project number so, you have to code it like this, static final String SENDER_ID = ‘882818505743’; instead of static final String SENDER_ID = “pushgcm-1204”;

          • Bhushan Shirwalkar

            u saved my life.. thanks lot…:)

          • Be sure to check the latest gcm article which will publish in few days.

  • Alzahrani Abdullah

    hey Ravi, I’m still waiting for updates as you promised πŸ™‚
    There is one issue that I need you to solve in your new version:
    When closing the app, I can receive messages; however, after receiving any new message I get the message as a notification but when I open the app I see nothing.
    Other thing:
    Can you please develop local message store for all messages the user receive? That is, any time a user start the app at the first time, he will see the front page for registration, then he has to do nothing but opening the app without seeing the registration page every time he starts the app; and he will be able to see all messages he received in the past.

    Thank you

    • Hi Alzahrani

      Right now I am working on the same project only. It is taking much time than I expected. I almost completed the implementation. Need to prepare the content and the demo video.

      Can you please develop local message store for all messages the user receive?
      You can use SQlite for this. The project I am preparing is already getting complex and adding SQLite makes it even more difficult.

      • Alzahrani Abdullah

        I appreciate it. I’m a beginner and it will take me more time to develop something stable.
        I will try to use SQlite! I have never used it before. I work with MySQL mostly.
        Please don’t forget to target SDK 23.
        Thank you.

      • Loki

        Hello Ravi,

        I think there is no need to have a registration/login system. The token_id should be generated after the user launches the app.

  • Kunal Agrawal

    hey ravi by following your codes i have created one app and launched on play store ,thankyou so much for all useful tutorials. now i want to implement push notification on this how can i implement this codes on that.

    • Please wait for 4-5 days as I am posting new article about Push Notifications. By the way app looks cool, but color scheme is not uniform through out the app. May be you can improvise it.

  • Loki

    GCM is so buggy. That’s why everyone is using Parse for push notifications. Hopefully the new version of GCM will run smoothly,without any problems. I am looking forward for the updated tutorial.

  • shoaibfarhan

    Hello everyone, i successfully completed push notifications. i want to ask one question,
    if i send the 10 notifications one by one,how all the notifications are display in list view? in my project,the new notification is displays perfectly, if i send the another notification the previous notification is deleted, please help me anyone.

  • archirayan62 Archi

    Hello ravi sir when i send request i get error message
    bellow error message.
    “multicast_id”: 6360158858123878000,
    “success”: 0,
    “failure”: 1,
    “canonical_ids”: 0,
    “results”: [
    “error”: “NotRegistered”

    please give me solution.

    • It seems your device is removed from GCM or the registration id is not valid. Try to uninstall and install the app again.

      • Sheetal

        my app working fine… but app is closed ..and notification came.. after
        tapping on notificattion it does not see on main activity………. pls
        help.. iam stuck from one week here

    • Sheetal

      my app working fine… but app is closed ..and notification came.. after tapping on notificattion it does not see on main activity………. pls help.. iam stuck from one week here

  • harsh

    Hey Ravi when you are posting the latest article on push notifications

  • Ramkesh Yadav

    can you please give me link or email me a working android studio updated project at thanx

    • vijayarangan

      not possible to give a link or send email

  • 【J】【Y】【U】VIOLE【G】【R】【A】【C】【E】

    Hello.. is it possible for both the php and android app receiving those message and in the website not needing a refresh ?

    To be specific, I have this project that in android that after clicking “Reserve” button the user must be shown in the website directly with no refresh. This is the closest answer i found and i dont know what term to search on google. Thanks

  • k e y u r

    waiting for the latest tutorial on push notifs

    • Yeah, on Monday.

      • Mohammad Altaf

        Ravi, bro today is monday but unable to see your new tutorial for android

        • Yeah dude, It should be posted by tonight. Its huge tutorial and comes in 3 parts πŸ™

          • k e y u r

            take ur time bro.. πŸ™‚ make it worth the wait fr all

          • Mal

            Ravi bruh!
            What time exactly today, you will post the new push notification tutorial?.
            warm regards,
            South Africa!

          • Mohammad Altaf

            hi, Ravi what happened you did not publish tutorial last night ?

          • Yeah Mohammad, please check the blog now.

            Here is the demo

          • Mohammad Altaf

            Thank you bro

  • Mohammad Altaf

    HELLO …I follow every thing but when i run the app . App successfully run after press the Register button only blank activity shows . And in my data base not register any device . I used this url https://localhost/gcm_server_files/register.php

  • Mohammad Altaf

    Helo Ravi which time you upload new tutorial today.

    • Hi Mohammad

      I am still working on it. Got few issues. Will be published by late night.


  • harsh

    Hey Ravi can you help me in uploading multiple images to the server

  • harsh malhotra

    Hey Ravi have you uploaded the new tutorial on push notifications??

    • Hi Harsh, new post is published. Please check the home page now. Its lengthy article but very informative.

  • Android_Rocks

    hii ravi,

    i am waiting for new tutorial on push notifications.

    please give a link.

  • As this article is deprecated please follow the updated article meanwhile this article updated.

  • Heart Break Kid

    Hello Ravi how are you? I am working on android application just like “ESPNCricInfo” can you tell me how to show live score update in my android application of all cricket matches those are currently on espncricinfo web, cricinfo doesn’t provide any api.

    • Write a server side app which craws the website and parses the html and get the score. Using push notifications you can push the live score to all the devices.

  • Shivakumar

    Hi ravi. I m Working on ionic push notifications with firebase. How ever i m getting the device token using phonegap and cordova plugin.. But this device token can be used in for push notifications. Is their any idea for firebase push notifications. If something is changed in firebase i should get the notification. Please do help if any idea.

    • No Shiva, I haven’t worked with firebase.

  • rajnandani

    Hi ravi. i don’t have knowledge about the php than how we get server url.

  • Enrique

    Can you do this tutorial with the new GCM 3.0 Please! is exactly what im looking for

  • Sathish Estec

    I’m trying with this article . i can register the device and emulator also. but cant get the push notifications on both device and emulator . i have server id and api key also. after running this app i register with name and email-id , it will be stored/register in gcm database (local) . then i’m trying to send the msg to android from index.php page on browser . this is not happen. what is the problem here?

  • Subin Babu

    Please update this article. How long i need to wait for this, sir?

  • Prasad P

    It’s working for me, thanks a lot for this article writer

    • Akshay Ram

      is everything working fyn??

      • Ahmed Fahmy

        hey man i have proplem in

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

        can u help me?

  • Prerna Singhal

    stuck off at ‘ acquiring wakelock ‘

    • Akshay Ram

      hello has it been solved . the logcat is stuck at acquiring wavelock

  • Chicken

    Can you add file test.php in this article, thank you so much !

    • Updating the article now. Should be updated by end of the day.

  • Manjunath


  • Manjunath

    ravi sir plzz help me .i m working on that topic messaging how to update the google play services in emulator.i m getting update google play services whenever i m trying to run …..

  • Kumar Bharani

    hii sir, in my project there is no errors ,i run the app in my mobile it works well but after register the button click “trying(attrmpt3/5 to register device on demo server”
    where is the problem? can u pls tell me

  • Sharath

    Hi Ravi, am new to this concept, thanks for providing this tutorial it helped me alot, But am getting error as Connot resolve method ‘setLatestEventInfo(Context, String,String,Pending Intent) inside , Then I used Notification.Builder class to slove this problem.
    After running this, am able to register successfully, but my device is not receiving notification when i sent message from “index.php” file. I tried to find where i did mistake but, failed. Could you please tell me where exactly the problem.

  • Alfian Hidayat

    Halo ravi. i am found problem when i try test.php.


    multicast_id: 9004810007812981000,

    success: 0,

    failure: 1,

    canonical_ids: 0,

    results: [


    error: “InvalidRegistration”




    can you help me. thank you !

  • parminder

    import;……error in gcm
    setLatestEventInfo……..can”t resolve method…
    GCMRegistrar…….error in EVERY GCMRegister…plz help mee

    • vivekvyas

      add GCM.jar file and import …..

  • Akshay Ram

    Mr Ravi i need your help ,am getting this problem ,what should i do
    when i tried to change the SDK version to 9 ,more errors occurs in file V21/values

    Error:(8, 5) uses-sdk:minSdkVersion 8 cannot be smaller than version 9 declared in library C:UsersAkshayDesktopUniversityYear 3Mobile

    • Chandan

      hey didi you find any solution for this ?

      • Akshay Ram

        just add these in the dependencies

        dependencies {

        compile ‘’

        compile ‘’

  • Prakhar

    Hi Ravi,
    when you’ll update this tutorial ?

  • keerthi sankeerthana

    pushnotifications it working perfectly but while i am sending message by server but message is not display in my device

    • Ahmed Fahmy

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

      can u help me !!

  • Mesut DΓΆnmez

    Hey Ravi, I am developing a app and i am always using ur page to develop. I need push notification very much but chat application is very complex to understand. Can u update this article as soon as possible. Thank u very much master πŸ˜‰

  • Ahmed Fahmy

    hey Ravi , i have proplem in

    ( ! ) 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
    can u help me !!


      instead of mysql_connect() use mysqli_connect()

  • Mohab Youssef

    i need this article to work not the updated one as this more familiar to what i want ! please why when i send notification it is not working ? the app craches when i add user after none ? please help me you will save my life

    • You must follow the updated article at least the 2nd part. 2nd part explains exactly what this article shows.

      • Mohab Youssef

        i’ll try , but my aim is to make automatic push notification when mysql database has change in specific table is it posssible ?

      • Dhina cool

        Hi ravi try MQTT protocol

  • taimoor shaukat

    every time i register user (invalid sender) error in m device please help me to solve this

  • Divakar Vikram Singh

    I think u r using old gcm related class and method, plz make a tutorial on android studio with latest gcm code. my android studio gcm project showing error. help me


    i am getting null value on receiving notification, How to resolve it

  • justDisqus


    Can you please update this article? Because i want to implement just the push notifications, not chat app. Chat app makes the tutorial a bit complex for me .
    Android won’t consider gcm_defaultSenderId in


  • jΓ©rΓ΄me le champion

    Hi ! Thank you for this tutorial !
    I have a little question :
    I followed he entire tutorial and when i register, I receive this 3 following message :

    New Message: From Demo Server: successfully added device!

    New Message: Trying (attempt 1/5) to register device on Demo Server.

    New Message: Your device registered whith GCM

    So it seems that it’s working well but when i try to send a message by my self by making a ‘get’ on the send_message.php or by calling the “send_notification” function of “gcm.php” from a homemade php script or by using the “index.php” i don’t receive any messages on my android app..
    Do you know why ? Can you help me please ?

    Thank you

    • jΓ©rΓ΄me le champion

      I get my answer : the curl don’t work on my server so I had to post my message like this in “gcm.php” :

      array( ‘price’ => $message),
      ‘to’ => $registatoin_ids


      $context = stream_context_create(array(

      ‘http’ => array(

      ‘method’ => ‘POST’,

      ‘header’ => “Content-Type:application/jsonrn”.


      ‘content’ => json_encode($postData)

      $response = file_get_contents(‘’, FALSE, $context);

      if($response === FALSE){

      $responseData = json_decode($response, TRUE);

      echo $responseData[‘published’];



  • Shraddha

    Hey, cant we save these notifications from the server in the form of a list using volley into android application?

  • vinod

    sir, my doubt is if in case add data in row in table from the server, how can user get a notification like gmail. is this possible!!!!!!!!!!!!

  • syed muhammad awais

    Hello sir i appreciate your efforts and good work in android development.i want to ask you that when new data is being enter into the database then into the json file i need to notify that new data is been added into the data base so how can i do that i mean how i can do that without gcm or other google api so on i need it to be done by only using my sql and json file.

  • Android_Rocks

    Ravi sir ,

    Please Update this articles As fast as possible. realy i need . i have refer your chat app 2 but not configure proper so please give alone gcm only articles.

    Hope You post Only Gcm 3.0 articles

    • Please read the second part only as it has GCM only.

  • Heri Hakim Setiawan

    hello Ravi, i have an error while i compile your code….before that i say thank you for your tutorials, its very help me πŸ™‚

    this is my error Error:Execution failed for task ‘:app:dexDebug’.

    > org.gradle.process.internal.ExecException: Process ‘command ‘C:Program FilesJavajdk1.7.0_79binjava.exe” finished with non-zero exit value 2

    can you solved that error? thx

    • ranjeet kumar Sahoo

      in build.gradle
      under defaultconfig add multiDexEnabled true, hope this type of error would not come

  • Maamoon Yaghi

    Hello Ravi , everything is working fine except that I am trying to send a notification but its not working, traced the php files and still not working ,onMessege is not even called ,tried to debug the send_message.php but it is not even calling the file , GCM php file is not working either what might be the error ? please help

  • Arish

    It is for only one device…. I am confused I want to send push notification in all user which is attach to me…..What is the alternative choice please suggest me. Confused about registration id.

  • really you are a perfect hardcore programmer guy. This has helped me a lot to increase my traffic and has got more organic searches from search engines.

  • Minar Rahaman

    hello ravi ,

    What kind of changes needed at GCM.php if we convert it to FCM ?


  • Sagar

    Nice article,
    But here I face on problem, you have set layout for MainActivity as activity_main.xml, but you didn’t showed the activity_main.xml. What we suppose to write in that file. Please provide code.

    • AbelardoLG

      Hi Sagar,

      Please, check again this article.

      Best regards,


  • Nishant Sambyal

    notification.setLatestEventInfo(context, title, message, intent);// error in this statement.

  • Jyoti Jain

    Thank You Sir, You are doing a great work.

  • Jigar

    I am greatly thankful to you Sir.. I successfully integrated in and also receive notification. and my side i only store token ID in ‘GCMUsers’ table. I am not creating other tables as mentioned here.
    But My problem is that . when user uninstall app. and after install app, new token Id generate. so how to replace older token Id. How to delete that device old token ID. I also see response but canonical ID is 0. and i am not doing any kind of registration. Please help me..

  • Michael Magdy

    Hi Ravi
    Thank u for this amazing tutorial.
    I need to know how for user to subscribe to specific chat room(Topic) ? get notifications from this room only ??
    any idea would be appreciated

    • In the tutorial i have explained how to subscribe to Global channel. You can do the same.

      • Michael Magdy

        i can’t understand how to subscribe to a certain topic only !! and get push notification from this topic only !!

  • Michael Magdy

    When i am trying to import the project into android studio it told me that the project too old.
    Any solution for this??

  • bhavin

    can anyone write a code for test.php

  • syed muhammad awais

    Hello sir i appreciate what you do for people all over the world i need to know how can i implement GCM push notification for device to device for example if one teacher needs to notify their students then ? Help from you will be appreciated sir πŸ™‚

  • Mukesh Joshi

    What to write in activity_main.xml. I have created a TextView in it, as what I understand reading the activity. What else to write in it.
    And notification.setLatestEventInfo(context, title, message, intent); giving the error, even I have added GCM.jar to the project/libs and added in SDK Manager.

  • Venugopal

    In the above push notifications example, i’m having a problem with registered device could not connect to demo server. How to fix this problem. can anyone help on this

  • There should be one more thing in this app, batch notification, instead sending txt to one person, it will be better to send to all registered users.

      • Thank you for your reply, your tutorials help alot for person like me.
        I think my comment was wrong, I am talking about notification message, in that demo video, you have sent message individually, instead of that it will be better to send all registered users, how can I do that, but still I do need that chat app for sending short clips.

        • See every user will be subscribed to /global topic. You can send a message to global topic, if you want to send message to all registered users.

          Chap app just the example showing how send message to individual or groups. You can get the code from that app.

          • ok, thank you.

          • One thing, you need to manually subscribe the user to /global topic when the app is launched. It is not automatic.

          • at least i will get emails and names automatically right ? just like in that demo ?
            if it is like that, then fine, otherwise i’ll collect it manually, no problem either…

          • They are even collected manually right on registration screen.

          • ok, thank you bro, you replied.

          • πŸ™‚

          • zohaib khan

            what will be the dependencies of this project plz send me…

  • Venugopal

    Hi Ravi,

    In the above push notifications example, i’m having a problem with registered device could not connect to demo server. How to fix this problem.

    Thank you.

  • Hari Krishnan

    Hello Ravi,
    The official documentation says something about a configuration file which should be included within the app folder of my project. I am confused with that step coz you haven’t mentioned anything about it. Can you help me on this? Should i include that file in the app folder?

  • shivani garg

    i had already installed the google cloud messaging library but it displayed obsolete in extras folder.
    and also when I import the project of gcm push notification.then it doesnt import package for gcm

  • Chandan Sharma

    hii @@ravi8x:disqus . I want to make a chat app . Please tell me which approach should i use . Socket Programming or Gcm .. And why ?? Please answer this. I am confused between these two …

  • Stephen

    Please change this tutorial to updated one.GcmIntentService is deprecated.So android studio users can’t work with this sample

  • Amelia Abdullah

    the db_functions.php files is given errors in the server and i dont know php. what do i do?

  • Amir Kotb

    Hi Ravi, I have built this GCM chat a year ago, and my app is now too complicated, so it is better for me to just modify the GCM part according to the new updates. I am working with Eclipse, which doesn’t have the gradle option. Where can I start from to update this work – in this article – to make the gcm work? Thanks in advance

  • Concetto Developer

    hello Ravi, I have executed your code but i am not able to get notification when the application is in background.Kindly help me i am stuck. Thank you in advance.

  • Yazdan

    Hi ,
    how can i send one notification to multi users , just with one click ?!
    by the way thank you for your helpful and good tutorials.

  • Hi,
    Please update this article, and please include group notifications as well.
    Thank you for your website, it helped me alot.

  • Dhaval Tailor

    please solve this problem
    GCMRegistrar cannot resolve symbol

  • niteen bhende

    this is not working sir…
    when i close app and clear the recent open app and then send the notification it getting the notification but when i click on notification, it showing unfortunately stopped.
    app is not opened again.
    please reply, help newby like me to improve.
    thank you.

  • Gowtham Nimmagadda

    I got this exception IOException SERVICE_NOT_AVAILABLE at this line :.GoogleCloudMessaging.register(Unknown Source). I tried different ways but its not solved. Can you please say why do we get this issue ? Thank You

  • Devi Septian II

    hai mr. Ravi Tamada,
    i want ask to you something, i want sent my push notification to spesific user, how can i do that?
    sorry if my english is bad.

  • AI DA

    Hi Mr. Tamada…I;m so sorry, i’m currently trying this project of yours. can the apps still run even if I didn’t use the emulator…I’d prefer using the smartphones directly….i’m using the localhost:8080…how can implements the server…???

    • AI DA

      From GCM: error

  • Soft Fudge

    Hello Ravi, you tutorials have helped me alot in my applications but I’m a bit confused on how to use this GCM to send notification to android device automatically not from some webpage/CONSOLE. When User A sends a message to USER B, the message is delivered to server and the server then issue a notification for the USER B about the message. Here in this tutorial you are using online console to send the notifications to one/more users. BUT what if i want to send the notifications automatically. NO CONSOLE INVOVLED. THANKS IN ADVANCED, PLEASE reply to this comment here in this same post and not in FCM update of this post. PLEASE. I’ve searched everywhere to find the answer but non helped me.

  • Adedara Klever Olanrewaju

    Hey Ravi, nice tutorial there.
    I want to ask how can I send Push Notifications to users that I already have registered users and I am not getting their details any longer I just want to send notifications to them

    • Hi Adedara

      Wait for 3days. I am updating this article with Firebase push notifications.

      • Adedara Klever Olanrewaju

        Alright I will be waiting..Thanks

      • Soft Fudge

        please please make it quick and read my comment below and tell me what to do. I’ve followed your android chat tutorial upto part 2 and got the notifications sent from admin panel but couldn’t get the idea of how i can implement push notifications in my app. please read the COMMENT BELOW. PLEASE PLEASE

        • The Firebase article will be published tomorrow.

  • bhavin makwana

    i m success to send push notification to user,thanks to ravi sir
    but i want to open particular page when notification come rather than mainactivity..
    i m using navigation drawer content….

    i want to open third one (…plz help me if anybody know ..

    public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id =={



    else if (id == {



    else if (id == {


  • Sami

    Hi Ravi, as usual, amazing tutorial, but just check and modify the timestamp (the date) at the top of this page (October 14, 2012…).

    • Yes. It’s better I remove the timestamp or post the updated date.

  • Mstafa Dayanr

    Hi Ravi. Thank you for this updated post. It is so useful. But I have a question about limitations. Is there a limit with the number of users we want to send the notification (as in GCM). There was a limit of 1000 regIDs in GCM. Especially when sending message to 100K users, this cause a problem. I tried putting the code in a loop in php code. It works but as the number of users increase, it takes longer time to send notification. What do you think the precise solution is?

    • The solution is make all the users subscribe to a topic and send notification to that topic. In this article by default all users will be subscribed to topic ‘global’. When you send notification to ‘global’ topic name, everyone will receives it.

  • AbelardoLG

    Hello world,

    I’m back.

    At the time, I have the following errors:
    > “Could not find”
    > “Could not find”

    I made these steps:

    but nothing was solved.

    Can anybody help me with this issue? Thanks in advance.

    I changed them into 9.4.0 version.

    Best regards.

    • I forgot to mention these steps. Thanks for letting others know.

  • AbelardoLG

    Hi everyone,

    I run this application but “reg id” is null; I think that ‘MyFirebaseInstanteIDService’ is not running since I put a Log.e(TAG, “refreshedToken:” + refreshedToken); and it wasn’t showed in Console.

    How long should I wait to have the reg id?

    How could I know if this class is running?

    • You need to place correct google-services.json and device should have internet connection.

      • AbelardoLG

        Hi Ravi,

        I have that file under ‘app’ dir and my laptop/Genymotion device have internet connection.

        All is right but ‘reg id’ is not coming. πŸ™‚

        My google-services.json has included the SHA1 correct.

        Thanks, Ravi. Best regards.

        • Is Genymotion is having Google account added?

          Can u try in real device?

          • AbelardoLG

            I have got an Android 4.1.2 phone. I will execute this app whenever I have got a phone with a prior Android version installed.

            I will let you know my experience in a real device.

            Brs., Ravi.

          • AbelardoLG

            Hi Ravi,

            After to wait few seconds, I saw the reg id on the phone screen!!!!. Therefore, this thread is closed for me.

            Thank you for your patience, effort, time and questions in order to solve this issue.

            Now, I have an issue on the side server (“Call to undefined function curl_init()”) but this is an problem not related to your app. I will let you know how to solve this last problem for the people.

            Thank very much, Ravi.

            Great tutorial.

          • Is your problem solved?

          • AbelardoLG

            Hi Ravi,

            Good morning from Canary Islands (Spain).

            Yes, the client side issues were solved successfully; now, I have problems with the WAMPServer Apache HTTPD configuration file due to restricted access from my phone.

            A great tutorial!

            Best regards and thanks you for your help,


          • AbelardoLG

            Hi Ravi,

            I have a slightly modification to your original code. My app executes this business logic:
            1) Receive the regID….OK.
            2) Once I have got it, I send it to my PHP web server in order to register it inside my database…OK.
            3) This PHP web server responses to me with a clientID (an integer value)…OK.
            4) >>> HERE <<<< At the moment, I'm understanding how to retrieve these clientID via onResponse method and how to manage this data to be consumed by my app…PROGRESS.
            5) Then, this clientID will be stored in the app database to be used like token when my app talks with my PHP Web server instead of to use the regID (very long string)…NEXT STEP.

            So, I would like to ask you a question about the regID: if the client A is connected with my app, the client will obtain a regID; so, if another client, B, connects with my app…Will A and B get the same regID or they will have different regIDs?

            Thanks in advance and for your time&support.

            Best regards,


          • AbelardoLG

            Hi Ravi,

            I’m sorry for taking so long to write back.
            My problem was solved.

            Best regards.

          • AbelardoLG

            Hi Ravi,

            I’m sorry for taking so long to write back.

            Yes, my problem was solved.

            All the best,


          • AbelardoLG

            I updated the WAMPServer to its last version and this problem was solved as soon I run it.

            Best regards,


          • Cool.

  • Gamis

    Hi everyone !!! πŸ™‚ If you want to use some Api for Download the image in the Notification you can use Picasso like this:

    notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(

  • ahmed

    hello sir
    thanks for good tutorial
    Ii have a problem I use the code and get a success response {“multicast_id”:4977823335719589401,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1475538722422633%584545e6f9fd7ecd”}]} when I send from my server but it didn’t reach the android device but when I send from firebase admin the notification reach the device what is the problem and thanks

    • You are keeping the correct Web API Key in config.php. It should be yours.

    • Kiny

      I have same problem. When I run in your demo with my Web API Key and regID, my android device received notification. But when I run in my server, not received. I copy your file and run. I don’t understand why

  • Vaibhav Purohit

    hello ravi Sir,

    I m trying to implement this code in my application and i m getting this type of error..

    Error:(15, 8) error: zzae(Intent) in FirebaseMessagingService cannot override zzae(Intent) in zzb
    attempting to assign weaker access privileges; was protected

    Please tell me how can i resolve this error.

    thanku sir

  • Joon

    Curl failed: couldn’t connect to host
    Please help me…

    • May be internet problem.

      • joon

        internet not problem..
        our server php version 5.6 +…
        It could be a problem with the ssl?

    • Anderson Da Silva Bezerra

      cut off the “HTTPS” of
      $url = ‘’;
      in firebase.php

  • Kukuku

    Hello Ravi sir. Thank you for your tutorial, it’s really helpful. Do you have twitter? So I can mention you πŸ™‚ Thank you very much. You did all what is to be done

  • Shankar Johnny

    Hello Ravi sir.. thanks for a wonderfull tutorial , i was waiting for a perfect one ,since parse shutting down .. i have successfully implemented into my application and notifications are working for some and for some they are not receiving ,my brother phone redmi note 4G also not getting notifications. please help sir ,i have used topic ‘Global’ for sending to multiple users. Thanks

    • Hi Shankar

      Uninstall the app and install again. I see the problem my self too, but after 1day everything worked correctly.

      • Shankar Johnny

        Also sir , one more question can we actually use Firebase web api key in place of Google api key for chat app in config.php file and try? Will it work. Thanks

        • Nope it wont. You need to do modify the end url pointing to firebase domain. Also the push notification json format is changed in firebase. You can compare the push.php from both the articles.

          • Shankar Johnny

            i have changed accordingly what you have said sir . url and push.php files , thanks

  • Nishant Chauhan

    Hi Ravi,

    Could you please tell the per day limit of push notification on number of registered devices ? means on how many devices we can send push notification on daily basis.
    Thanks in advance.

    • Hi Nishant

      I didn’t find any limitation on their docs.

      • Arbaz Alam

        There is no limit on number of registered devices but there is a limit of 1000 message in a batch. That mean you cannot send message to more than 1000 device in one go or one batch.

    • Arbaz Alam

      There is no limit on number of registered devices but there is a limit of 1000 message in a batch. That mean you cannot send message to more than 1000 device in one go or one batch. message batch limit is there…

  • Jibarath

    Thank you!

    Please add the internet permission in the manifest file.

    • It will work without INTERNET permission.

      • Jibarath

        I can’t get registration id without internet permission.

        • Oh I see. But It doesn’t need the permission. I have tested.

          • Viswanathan G

            I tried without internet permission. It worked.

          • Jibarath

            Yes, Its working.
            I don’t know why it happens for me at first time.
            Anyway, Thanks a lot.

          • You are welcome πŸ™‚

  • Yair Hadari

    Thanks for contributing this valuable post to the community!
    In the HTML demo the payload is not being displayed.
    Any reason for this?



    I’m getting this on emulators and devices, “Firebase Reg Id is not received yet!”

  • Salin

    Hi Ravi,
    I’m facing an issue that the device token is not to be changed .if a user logged out and another user logged in there should be different devicetoken .how can i don this??


  • Chaitanya Dharmale

    Error:Minimum supported Gradle version is 2.14.1. Current version is 2.10. If using the gradle wrapper, try editing the distributionUrl in /home/chetan/AndroidStudioProjects/FCMExample/gradle/wrapper/ to when we edit 2.14.1 then it alsp show the same error

    • saurabh sarpotdar

      you need to update your project to use the latest gradle build version… checkout files for both module:app and your project..and edit them so they will point to gradle 2.14.1..u can google it…how to update gradle version for your project…

  • Viswanathan G

    Thanks for posting this article. Basically if we follow the steps you mentioned it is working fine. If you can elaborate more by explaining the flow in a short video will be helpful in many posts.

    • I already explained about push notifications so many times. Thats why didn’t prepared much guide in this article.

      • Viswanathan G

        Thanks Ravi for your quick response. I will look into your other articles for more details on push notifications.

  • raghav khanna

    Hi Ravi,
    I have a confusion regarding unregisterReceiver() method. When we unregister our broadcast receiver in the onPause() method, will the app still receive intents when the app is in background?

    • No it won’t be received. The main purpose of intent receiver is to update the UI when the app is opened. When the app is in background, you will get the same data payload when the notification is tapped and app is opened.

  • theP

    Hi Ravi,
    How to send Notification With Data in Php And How To get That (Data ) Notification (with More Values) in android , Because i Want to send Notification with message,url and some types. So Plesae Help Me Reagarding This.
    I know how do to in Gcm ( Like Intent,GetExtra) But I dont know how to achive in FCM .

    • Hi

      This is already explained in this article. Check the json properly. I am sending data payload. You can add more values this.

      • theP

        But In Demo You Are Not Added Data Payload.. So Please Give Me Suggestion.. And Without Json WE Can Not get Notification in android, cause in GCm We Nvr use json..??

        • When parsing the json, you need to get the other json values using their node names. In android I have written the below code to get the payload. You need to perform other json operations like getJsonString() on to this payload to get the desired values.

          JSONObject payload = data.getJSONObject(“payload”);

          In php you need to add your values to this payload node. In the article I have written the lines of code which sends ‘team’ & ‘score’ in push notification. You need to get those values from payload json object.

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

          • theP

            Thanks.. I Will Try..

  • Dhruv

    hello sir i am getting response from your script but notification is not recieved by android devices.
    when i am sending from firebase console it is recieved by android devices

    response: “{“message_id”:5473666725740641859}”

    {“data”:{“title”:”testing by dhruv”,”is_background”:false,”message”:”vfcvxc”,”image”:””,”payload”:{“team”:”India”,”score”:”5.6″},”timestamp”:”2016-10-07 12:14:25″}}

  • bhavin makwana

    hi,sir ..this working for me fine but my app have more than 2000 user
    …and fcm or gcm only allow 1000 key or app to send a notification…i have all users key in my server..
    below 1000 is working fine to send a message through php..but above 1000 no one user can get notification,
    so, if u have any idea regarding how create loop in php or something else to rid this issue ..

  • Babin Raj M

    hi ,sir i have run in to problem ,the notification icon is not showing ,and also when the app is in background notification sound is also not working

  • ARASHI Funsho

    As usual Ravi, Top-Notch tutorial…… Cheers bro.. much needed stuffs…… will try out and leave feedback…

    • Sure Arashi, will help you out if you got any problem πŸ™‚

  • Adie Saptono

    Great Tutorial Master Ravi, I wanna ask something how to export project from android studio to multi platform like android & ios? thanks in advance

  • Batuhan Burak ERSΓ–ZLÜ

    It’s all works, thank you so much

  • Goutam Kundu

    I already having GCM setup for my project and also our server configure with the code through which we are able to send and receive notification.As because our server code using the existing project id for the notification and also app is live.It will difficult to change the project id and api key .Please suggest what should I do i order to implement FCM in my project.

    • Make the server supports both GCM & FCM. Release new app that supports FCM. After few weeks you can see all the users migrated to newer app which is FCM is supported, then you can discard support to GCM completely.

  • gautam kumar

    FCM Notification works fine for lolipop and above api devices but on kitkat and below like redmi phones it is inconsistent means sometimes it receives notification when app is open or background but not when app is stopped instead autostart permission is given and on some of the devices notifications does not come at all .Is there a way to solve all these problem please guide , anyway nice tutorial

  • saurabh sarpotdar

    hey…I am geting the notification and all but when I click on it..I only see my key in the bottom and the contents of msg…I did check the bindings to fields and extra we are passing thru seems what can be the problem..?

    • You have to pass the complete Intent data to MainActivity in push receiver class.

  • AbelardoLG

    Hi everyone,

    I have come back! :S

    Once I used the Firebase console in order to send myself a message, this message appears:
    “Sadly, Notifications is stopped”

    Does anybody know what’s wrong?

    I followed the code that gently Ravi showed us.

    Best regards.

    • AbelardoLG

      I googled about this issue. I deleted the cache content of the “Notifications” app but this error is still appearing again.


    • Rachit Agarwal

      same issue with me too…

      Does anybody has a solution?

  • abdur rochman wachid

    Hi Ravi,
    Thank you for tutorial,
    i wanna ask you, what emulator you are use for this tutorial, it’s look have good gui.

    Thank You

  • test test

    is it only work on above android version 19?

    • Yes

      • Babin Raj M

        how can i fix the problem …
        to make support from api version 14 and above

        • Babin Raj M

          i found a fix which works for me by simply adding a permission in manifest

          now it will show notification for below apI 19

          • Rachit Agarwal

            but there is a problem.. when i tap on notification icon… it opens my app but changes are not reflected back in textView.

            Anybody please help..

          • Aakash Chaudhary

            Thank you Babin you are a life saver

  • Geraldo K Fillipus

    Good tutorial

    thanks Ravi, but how to do i handle notification like the previous tutorials, what i mean is i want to post notification when there is an update to the server.
    so how do i do that with firebase?

    • I already provided code to send notification from php to firebase. Call the same code to send messages whenever there is a change in server.

      • Geraldo K Fillipus


  • Andrew Buchan

    Hi Ravi, great tutorial. Quick question. I am working on an Android app which consumes an API. There are 2 types of users, admin and regular users. Admins call a specific endpoint of the API to send a message to a regular user. It is at this point that I would call the PHP code you provided to send a message to a specific user. My question is how do I get the Firebase reg id for a specific user? If I get it once for user A, will that same reg id always be the same for user A?

    • Hi Andrew

      You need to create a REST endpoint which takes user regId and stores in users table (may in other table relating user). The regId changes sometimes. So usethe method TokenRefresh() in Add your code in that method which sends the regId to your server to store in db. This way the regId in server will be updated each time it changes. From here you can use the regId to send messages. Also if the message is targeted to huge number of users, consider using topic messaging.

  • saeed

    am not getting access to your code even am tried to subscibe,still i didnt get verification on my emailid

  • Rachit Agarwal

    Hi Ravi… I am a big fan of yours…
    I want to know whether this FirebaseMessagingService is getting started on its own or somewhere in MainActivity it is started manually?

    If it is getting started automatically just by registering in manifest code, then how to start it manually on REBOOT of my device. What should i write in my OnReceiver() method that gets triggered on Receiving REBOOT intent action.

  • Paritosh Chaudhary

    Hi Ravi..!!

    Thanks for your tutorial on how t integrate FCM in Android app. I Have successfully completed a 1:1 chat app in android using Firebase. Now i am stuck a one thing that how can i send the other using with whom i am chatting with a notification that he has a new message if that user is offline.

    Do i need to create an API for that or i can do it in my android app only. I have a Java server where i am able to send other notifications to the app. I now need to send a message notification to the other user. Please guide me how i can do that. Thanks

    • PINKesh Darji

      can you please share code that you have implemented for 1:1 chat using firebase.

  • Suraj Patil

    Hi Ravi…
    Thanks for your tutorial. Its working fine when app is foreground but when app is background and I click on notification it shows only registration Id. How to show message in an activity?

  • Prashanth Debbadwar

    Hi Ravi,
    Thanks for nice tutorial. I am maintaining a static flag in application class. I need to check that flag when pn comes. Though that flag is true I am getting false in Firebase message listener. Maintaining some flags in application class and accessing in gcm message listener was working fine with old gcm implementation. It is not working with firebase. I think firebase message intent service is running in different process. any solution for this?