The 1st Part covers the server side implementation of the app i.e building the REST API and the server app. In this part we’ll integrate the GCM in your new / existing android app. In the 3rd part the final chat app modules will be integrated.

This article also provides you a test interface where you can test any of your gcm apps by sending a sample push notification message.

android realtime chat app using gcm php mysql

I am also posting the project structure of the Android Project to get a clear picture file structure needed to build the final app.

android-gcm-simple-chat-app-project-structure

Integrating GCM In Your Project

Once you got the idea of the project structure, let’s start add the gcm into your app.

1. Create a new project in Android Studio and fill all the details required. When it prompts to select a default activity, select Blank Activity and proceed.

2. The next step is downloading the google-services.json file. This configuration file contains google services information specific to your app. You can configure google services like cloud messaging, google analytics, admob, sign in with google in the same configuration file. But in this article, we’ll choose only the gcm.

Goto this doc and click on Get a configuration file which prompts you to fill quick app related information.

3. On the developer console, choose the project that you previously created in Part 1, give the current project’s package name. Enable Google Cloud Messaging and click on Download google-services.json.

gcm-downloading-google-services-json

4. Add the downloaded google-services.json to your project’s app folder. Make sure that you are placing this json file correctly under app folder. Otherwise you won’t be successful in implementing the gcm.

5. Open build.gradle located under app level and do the below changes.

add apply plugin: ‘com.google.gms.google-services’ at the top.
add com.google.android.gms:play-services:8.3.0 dependency

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "info.androidhive.gcm"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.+'
    compile 'com.android.support:design:23.+'
    compile "com.google.android.gms:play-services:8.3.0"
}

6. One more important change is, open build.gradle located in root directory of the project and add

classpath ‘com.google.gms:google-services:1.5.0-beta2’

classpath ‘com.android.tools.build:gradle:2.0.0-alpha6’ in dependency and clean the project from Build => Clean Project.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0-alpha6'
        classpath 'com.google.gms:google-services:1.5.0-beta2'

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

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

7. Now under your project’s main package, create four packages named activity, app, gcm and helper. Move your main activity class into activity package.

8. Under app package, create a class named Config.java. This class contains app configuration information related to gcm.

package info.androidhive.gcm.app;

/**
 * Created by Lincoln on 05/01/16.
 */
public class Config {

    // flag to identify whether to show single line
    // or multi line text in push notification tray
    public static boolean appendNotificationMessages = true;

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

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

    // type of push messages
    public static final int PUSH_TYPE_CHATROOM = 1;
    public static final int PUSH_TYPE_USER = 2;

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

9. Under helper package, create a class named MyPreferenceManager.java This class stores data in SharedPreferences. Here we temporarily stores the unread push notifications in order to append them to new messages.

package info.androidhive.gcm.helper;

import android.content.Context;
import android.content.SharedPreferences;

public class MyPreferenceManager {

    private String TAG = MyPreferenceManager.class.getSimpleName();

    // Shared Preferences
    SharedPreferences pref;

    // Editor for Shared preferences
    SharedPreferences.Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Sharedpref file name
    private static final String PREF_NAME = "androidhive_gcm";

    // All Shared Preferences Keys
    private static final String KEY_USER_ID = "user_id";
    private static final String KEY_USER_NAME = "user_name";
    private static final String KEY_USER_EMAIL = "user_email";
    private static final String KEY_NOTIFICATIONS = "notifications";

    // Constructor
    public MyPreferenceManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void addNotification(String notification) {

        // get old notifications
        String oldNotifications = getNotifications();

        if (oldNotifications != null) {
            oldNotifications += "|" + notification;
        } else {
            oldNotifications = notification;
        }

        editor.putString(KEY_NOTIFICATIONS, oldNotifications);
        editor.commit();
    }

    public String getNotifications() {
        return pref.getString(KEY_NOTIFICATIONS, null);
    }

    public void clear() {
        editor.clear();
        editor.commit();
    }
}

10. Create a class named MyApplication.java under app package. This is a singleton class needs to be added to AndroidManifest.xml file.

package info.androidhive.gcm.app;
import android.app.Application;

import info.androidhive.gcm.helper.MyPreferenceManager;

public class MyApplication extends Application {

    public static final String TAG = MyApplication.class
            .getSimpleName();

    private static MyApplication mInstance;

    private MyPreferenceManager pref;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }


    public MyPreferenceManager getPrefManager() {
        if (pref == null) {
            pref = new MyPreferenceManager(this);
        }

        return pref;
    }
}

11. Create a folder named raw under res. Download notification.mp3 and paste it in res => raw folder. This is a custom notification sound which will be played whenever a new push notification is received.

12. Create a class named NotificationUtils.java under gcm package. This class is used to show the notification in notification tray. This also contains major functions like checking app’s running state (background / foreground), downloading notification image attachment from url, playing notification sound and clearing notification messages.

package info.androidhive.gcm.gcm;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.text.Html;
import android.text.TextUtils;
import android.util.Patterns;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import info.androidhive.gcm.R;
import info.androidhive.gcm.app.Config;
import info.androidhive.gcm.app.MyApplication;


/**
 * Created by Ravi on 01/06/15.
 */
public class NotificationUtils {

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

    private Context mContext;

    public NotificationUtils() {
    }

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


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

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        final PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        mContext,
                        0,
                        intent,
                        PendingIntent.FLAG_CANCEL_CURRENT
                );

        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                mContext);

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


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

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

        if (Config.appendNotificationMessages) {
            // store the notification in shared pref first
            MyApplication.getInstance().getPrefManager().addNotification(message);

            // get the notifications from shared preferences
            String oldNotification = MyApplication.getInstance().getPrefManager().getNotifications();

            List<String> messages = Arrays.asList(oldNotification.split("\\|"));

            for (int i = messages.size() - 1; i >= 0; i--) {
                inboxStyle.addLine(messages.get(i));
            }
        } else {
            inboxStyle.addLine(message);
        }


        Notification notification;
        notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentIntent(resultPendingIntent)
                .setSound(alarmSound)
                .setStyle(inboxStyle)
                .setWhen(getTimeMilliSec(timeStamp))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                .setContentText(message)
                .build();

        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();
        bigPictureStyle.setBigContentTitle(title);
        bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
        bigPictureStyle.bigPicture(bitmap);
        Notification notification;
        notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentIntent(resultPendingIntent)
                .setSound(alarmSound)
                .setStyle(bigPictureStyle)
                .setWhen(getTimeMilliSec(timeStamp))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                .setContentText(message)
                .build();

        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();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

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

    /**
     * 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);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            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() {
        NotificationManager notificationManager = (NotificationManager) MyApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

    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) {
            e.printStackTrace();
        }
        return 0;
    }
}

13. Create a class named GcmIntentService.java under gcm package. This service extends IntentService which acts as a background service. This service basically used for three purposes.

> To connect with gcm server and fetch the registration token. Uses registerGCM() method.

> Subscribe to a topic. Uses subscribeToTopic(“topic”) method.

> Unsubscribe from a topic. Uses unsubscribeFromTopic(“topic”) method.

package info.androidhive.gcm.gcm;

import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;

import java.io.IOException;

import info.androidhive.gcm.R;
import info.androidhive.gcm.app.Config;


public class GcmIntentService extends IntentService {

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

    public GcmIntentService() {
        super(TAG);
    }

    public static final String KEY = "key";
    public static final String TOPIC = "topic";
    public static final String SUBSCRIBE = "subscribe";
    public static final String UNSUBSCRIBE = "unsubscribe";


    @Override
    protected void onHandleIntent(Intent intent) {
        String key = intent.getStringExtra(KEY);
        switch (key) {
            case SUBSCRIBE:
                // subscribe to a topic
                String topic = intent.getStringExtra(TOPIC);
                subscribeToTopic(topic);
                break;
            case UNSUBSCRIBE:
                String topic1 = intent.getStringExtra(TOPIC);
                unsubscribeFromTopic(topic1);
                break;
            default:
                // if key is not specified, register with GCM
                registerGCM();
        }

    }

    /**
     * Registering with GCM and obtaining the gcm registration id
     */
    private void registerGCM() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String token = null;

        try {
            InstanceID instanceID = InstanceID.getInstance(this);
            token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

            Log.e(TAG, "GCM Registration Token: " + token);

            // sending the registration id to our server
            sendRegistrationToServer(token);

            sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER, true).apply();
        } catch (Exception e) {
            Log.e(TAG, "Failed to complete token refresh", e);

            sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER, false).apply();
        }
        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
        registrationComplete.putExtra("token", token);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }

    private void sendRegistrationToServer(final String token) {
        // Send the registration token to our server
        // to keep it in MySQL

    }

    /**
     * Subscribe to a topic
     */
    public void subscribeToTopic(String topic) {
        GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
        InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
        String token = null;
        try {
            token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            if (token != null) {
                pubSub.subscribe(token, "/topics/" + topic, null);
                Log.e(TAG, "Subscribed to topic: " + topic);
            } else {
                Log.e(TAG, "error: gcm registration id is null");
            }
        } catch (IOException e) {
            Log.e(TAG, "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage());
            Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public void unsubscribeFromTopic(String topic) {
        GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
        InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
        String token = null;
        try {
            token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            if (token != null) {
                pubSub.unsubscribe(token, "");
                Log.e(TAG, "Unsubscribed from topic: " + topic);
            } else {
                Log.e(TAG, "error: gcm registration id is null");
            }
        } catch (IOException e) {
            Log.e(TAG, "Topic unsubscribe error. Topic: " + topic + ", error: " + e.getMessage());
            Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}

14. Create a class named MyInstanceIDListenerService.java under gcm package. This service invokes onTokenRefresh() method whenever there is a change in gcm registration token.

package info.androidhive.gcm.gcm;

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

import com.google.android.gms.iid.InstanceIDListenerService;

public class MyInstanceIDListenerService extends InstanceIDListenerService {

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

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. This call is initiated by the
     * InstanceID provider.
     */
    @Override
    public void onTokenRefresh() {
        Log.e(TAG, "onTokenRefresh");
        // Fetch updated Instance ID token and notify our app's server of any changes (if applicable).
        Intent intent = new Intent(this, GcmIntentService.class);
        startService(intent);
    }
}

15. Create a class MyGcmPushReceiver.java under gcm package. This is a receiver class in which onMessageReceived() method will be triggered whenever device receives new push notification.

package info.androidhive.gcmtest.gcm;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

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

import info.androidhive.gcmtest.activity.MainActivity;
import info.androidhive.gcmtest.app.Config;

public class MyGcmPushReceiver extends GcmListenerService {

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

    private NotificationUtils notificationUtils;

    /**
     * Called when message is received.
     *
     * @param from   SenderID of the sender.
     * @param bundle Data bundle containing message data as key/value pairs.
     *               For Set of keys use data.keySet().
     */

    @Override
    public void onMessageReceived(String from, Bundle bundle) {
        String title = bundle.getString("title");
        String message = bundle.getString("message");
        String image = bundle.getString("image");
        String timestamp = bundle.getString("created_at");
        Log.e(TAG, "From: " + from);
        Log.e(TAG, "Title: " + title);
        Log.e(TAG, "message: " + message);
        Log.e(TAG, "image: " + image);
        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);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils();
            notificationUtils.playNotificationSound();
        } else {

            Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
            resultIntent.putExtra("message", message);

            if (TextUtils.isEmpty(image)) {
                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, image);
            }
        }
    }

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

16. Open AndroidManifest.xml and do the below necessary changes.

> Add MyApplication to <application> tag using name attribute

> Add INTERNET, WAKE_LOCK, GET_TASKS and C2D_MESSAGE permissions.

> Add MyGcmPushReceiver & GcmIntentService as services and GcmReceiver as receiver.

> Replace info.androidhive.gcm with your current project’s package name.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.gcm">

    <uses-permission android:name="android.permission.INTERNET" />

    <!-- needed for older devices -
     used to check app background / foreground status -->
    <uses-permission android:name="android.permission.GET_TASKS" />

    <!-- START Added for GCM -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <permission
        android:name="info.androidhive.gcm.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="info.androidhive.gcm.permission.C2D_MESSAGE" />
    <!-- END Added for GCM -->

    <application
        android:allowBackup="true"
        android:name=".app.MyApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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


        <!-- START Added for GCM -->
        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="info.androidhive.gcm" />
            </intent-filter>
        </receiver>

        <service
            android:name=".gcm.MyGcmPushReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

        <service
            android:name=".gcm.GcmIntentService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>

        <!-- END Added for GCM -->

    </application>

</manifest>

17. Finally open MainActivity.java and make the following changes.

> In order to receive the push notifications, device has to support google play services. So checkPlayServices() method is used to check the availability of google play services. If the play services are not available, we’ll simply close the app.

> Register a broadcast receiver in onResume() method for both REGISTRATION_COMPLETE and PUSH_NOTIFICATION intent filters.

> Unregister the broadcast receiver in onPause() method.

> Create an instance of broadcast receiver in onCreate() method in which onReceive() method will be triggered whenever gcm registration process is completed and a new push message is received.

package info.androidhive.gcm.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.Toast;

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

import info.androidhive.gcm.R;
import info.androidhive.gcm.app.Config;
import info.androidhive.gcm.gcm.GcmIntentService;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private BroadcastReceiver mRegistrationBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            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
                    String token = intent.getStringExtra("token");

                    Toast.makeText(getApplicationContext(), "GCM registration token: " + token, Toast.LENGTH_LONG).show();

                } else if (intent.getAction().equals(Config.SENT_TOKEN_TO_SERVER)) {
                    // gcm registration id is stored in our server's MySQL

                    Toast.makeText(getApplicationContext(), "GCM registration token is stored in server!", Toast.LENGTH_LONG).show();

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

                    Toast.makeText(getApplicationContext(), "Push notification is received!", Toast.LENGTH_LONG).show();
                }
            }
        };

        if (checkPlayServices()) {
            registerGCM();
        }
    }

    // starting the service to register with GCM
    private void registerGCM() {
        Intent intent = new Intent(this, GcmIntentService.class);
        intent.putExtra("key", "register");
        startService(intent);
    }

    private boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                        .show();
            } else {
                Log.i(TAG, "This device is not supported. Google Play Services not installed!");
                Toast.makeText(getApplicationContext(), "This device is not supported. Google Play Services not installed!", Toast.LENGTH_LONG).show();
                finish();
            }
            return false;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

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

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}

Now run & deploy the app on a device. Make sure that your device is having internet connection and you followed the above steps correctly. After the app is launched, you should able see the gcm registration token as a Toast message. You can also find the registration token in LogCat.

gcm-registration-token

Testing Push Notifications

In order to test the push notifications, I have created a simple interface where you can type a sample message and send it to devices. Note that the sensitive information (API key & registration token) you are providing is not stored on the server in any manner. Also the demo test panel works when you are following the steps explained in this article only.

1. Goto to the push notifications test panel.

2. Enter your GCM API Key that you have obtained from google developer console.

3. Enter the gcm registration token which is logged in your Android Studio LogCat.

4. Type a message and click on Send Push Notification button. There is also an option provided to test push notification with image attachment.

android-gcm-push-notifications-test-panel

If you are able to get the push notifications using the test interface, congratulations! You are only a few steps away from building a fully working realtime chat time. So let’s start building the remaining modules in 3rd Part.

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

    thanks Ravi
    great tutorial

  • newDevL

    Hi Ravi,
    I can access the portal fine via http://192.168.11.1/gcm_chat/

    but when the app call the API http://192.168.11.1/gcm_chat/v1/user/login
    i get a 404 Page Not Found ?

    {
    “error”: true,
    “message”: “Oops! An error occurred while registereing”
    }

  • Yaqoub Alsaadi

    hi Ravi
    i need to use web server insted of local server!
    i try to add the files but still not working
    >is there any solution for this

    • Thomas Nana Baisi Davis

      i need this too, on my go daddy server i get the volley error : null

  • Lou Chavez

    hey Ravi i follow this tutorial http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ what part of this im going to change . .Like what you said all google Api’s you use from there are deprecated.

  • Lou Chavez

    Please I need help I want to put push notifications to my app as one of my features

  • Dhaval P

    hi Ravi, first of all thank you for the detailed tutorial. however i would like to use Retrofit instead of volley.. so is there any drawbacks of doing that? or is it fine to go with that + to use retrofit with your demo project approximately how much of the code should i change?

  • Nitesh

    While logging getting error json parsing error: Value true at error of type java.lang.Boolean cannot be converted to JSONObject

  • MUSHTAQ M.A

    Can you post about retrofit

  • Bhushan Shirwalkar

    m using latest stable AS 1.5…and i have below line in project level build.gradle:
    classpath ‘com.android.tools.build:gradle:1.5.0’

    when i try to change it as you meintioned which is:
    classpath ‘com.android.tools.build:gradle:2.0.0-alpha6’

    it gives me this warning:
    Warning:Gradle version 2.10 is required. Current version is 2.8. If using the gradle wrapper, try editing the distributionUrl in C:UsersBhushanAndroidStudioProjectsGCM3.0gradlewrappergradle-wrapper.properties to gradle-2.10-all.zip

    so i dug further n changed that gradle-wrapper.properties.. tried to download latest gradle-2.11.zip n gave related path in settings>gradle as well as made 2.11 in project structure>project>gradle version, but still gave me errors.. so does AS1.5 stable not support alpha/beta gradle?? or i need to update AS to latest canary/dev/beta? or is it ok if i stick with gradle:1.5.0 in classpath with that warning?? thanks

    Edit: problem solved.

    • Nimzy Kevin Maina

      how did you solve your problem??

  • Ashutosh Tripathi

    does this app support one to one chat also instead of just group chap…thanks

    • Ashutosh Tripathi

      someone please reply…thanks

  • akalanta

    Hello there, I am trying to develop a trivia game app and I want to have the push notification to set up a request to connect. From there both people will be on a screen where they will be answering questions. Do you have any ideas on how I go about this? I am a beginner and I am trying to understand all this material.

  • Yaqoub Alsaadi

    i am trying to upload all file in my webhost server but no thing work at all !!!
    any help ???

  • Prathibha Nandini

    @ravi8x:disqus Waiting for the update of article http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

    I’ve used the current chat article to send notifications to device, but it is not like previous article, I’m not able to print the received notification on screen, the string extra which we sending through intent to main activity is always null

    • Can you give me the code of both. The code sending data to main activity and the code receiving the intent in main activity.

    • Prathibha Nandini

      @ravi8x:disqus http://paste.ofcode.org/MaQLSVXGNVCcDYafg4rYn2 Here I’ve used Shared preference and Intent to save the message. But, both of them return null. When the Notification is received I need to display it on screen when notification is opened. Similar to GCMMessageView.class of old article

      • Is the message is printing in Log using Log.e(“msg”,message) ?

        • Prathibha Nandini

          No. It’s not. http://paste.ofcode.org/3iHzbuiZ4TcBH9ADksqNzd These are the 2 classes which is handling notification

          • You need to verify few things.

            1. Make sure that you are using correct google API key in php project.

            2. Make sure that you have downloaded correct google-services.json and added it to android project.

            3. Verify the logs in MyGcmPushReceiver class first as push messages will be received by this class first.

            4. In main activity you are reading the push notification wrongly. The push message will be received in the below method, not in onCreate method.

            mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            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
            String token = intent.getStringExtra(“token”);

            Toast.makeText(getApplicationContext(), “GCM registration token: ” , Toast.LENGTH_LONG).show();

            } else if (intent.getAction().equals(Config.SENT_TOKEN_TO_SERVER)) {
            // gcm registration id is stored in our server’s MySQL

            Toast.makeText(getApplicationContext(), “GCM registration token is stored in server!”, Toast.LENGTH_LONG).show();

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

            Toast.makeText(getApplicationContext(), “Push notification is received! n message is – ” , Toast.LENGTH_LONG).show();
            }
            }
            };

  • Radovan Heldák

    Thumbs up 🙂 I love this tutorial 😀

  • Yaqoub Alsaadi

    brother Ravi Tamada
    thanks aloot
    plz want your help to upload php files to 00webhost….
    waiting you brother

  • Giovani Fernandes

    i have a problem. AndroidRuntime: FATAL EXCEPTION: main Process: PID: 10695
    java.lang.NullPointerException
    at android.support.v7.widget.RecyclerView.computeVerticalScrollRange(RecyclerView.java:1654)
    can you help me?

  • Heart Break Kid

    That is such a wonderful tutorial will you please tell us how to implement a “Poll System (just like twitter have)” in android application?

    • You can write a service which executes for an interval?

  • Bhushan Shirwalkar

    Hi Ravi. I need some help in my project. Do you mind if i contact you?

  • fidel castillo

    Hi Ravi, excellent tutorial, I have an error when I test the application on a physical cell , with the simulator I have no problems , the error is in this line
    StringRequest strReq = new StringRequest(Request.Method.POST, EndPoints.LOGIN, new Response.Listener() {, thank you

    • What is the error?

      • fidel castillo

        My bad, the error is, Volley error: null, but with genymotion i have no problems with the login, however with a real cellphone the login fail.

        • What is your url address you are accessing from the device?

  • priyanka 123

    Hi Ravi, Thanks for the tutorial. its excellent.. I am facing a problem. During login i am getting Volley error: null, code: null. The username and email id is not added in database. When I am using Postman it works well. Please help me.

    • Are you accessing the project by ip address?

      • priyanka 123

        yes.. I think its volley timeout error.. i tried using this too but still not working

        request.setRetryPolicy(new RetryPolicy() {
        @Override
        public int getCurrentTimeout() {
        return 50000;
        }
        @Override
        public int getCurrentRetryCount() {
        return 50000;
        }
        @Override
        public void retry(VolleyError error) throws VolleyError {
        }
        });

      • ajit

        same prob i am facing

      • ajit

        yes i am using ip

      • kushagra

        @ravi sir please solve this issue many people are facing the same issue

  • ajit

    How to create chat app without using php coding

  • ajit

    why we are storing all deta in sql.insted of google storage

  • Rishika Kapur

    Done with 2nd Part of the tutorial without any error. Brilliant tutorial @@ravi8x:disqus Thank you

  • Jp Kansara

    Hello Ravi, Thank you for this very nice tutorial. But I have got some error while updating build.gradle (both) is as below:

    Error:Execution failed for task ‘:app:processDebugGoogleServices’.
    > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 8.3.0.

    Can you please help me to solve this error? I have searched in google but didn’t get proper solution.

    Looking forward to your reply.

    • Vincent H Guyo

      post your build.gradle

  • poker

    Show Error:InvalidRegistration during place notification. And also when launch app on device it crash first time after toast message of registration token.Second time it run fine.please solve my problem Thanks in advance 🙂

  • Junaid TT

    Once again brillient tutorial from Ravi…Thanks

  • Sachin RV

    Hi Ravi, First of all thanks a lot for great tutorial. I have implemented this successfully, although I am facing small issue. In main activity, recyclerview notification count n message will not be cleared even if I check the message from chat page.

  • Alex Silva

    Code download isn’t working.

  • Prathap

    Error:Execution failed for task ‘:app:processDebugGoogleServices’.
    > File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it.
    This is d bug which i have got…and i have google-services.json nut don’t knw wer to paste it…i hav tried al d combination of roots as well…plzz fix dis ASAP ji

  • Pfunzo Mudau

    it works great when i send a push notification with an image, if i exclude an image it breaks,what could be the problem ? @ravi8x:disqus

    • Are you seeing any error in logcat?

      • Pfunzo Mudau

        .NullPointerException

        at com.apps.mudau.pfunzo.karabossolution.gcm.NotificationUtils.showSmallNotification(NotificationUtils.java:105)

        at com.apps.mudau.pfunzo.karabossolution.gcm.NotificationUtils.showNotificationMessage(NotificationUtils.java:93)

        at com.apps.mudau.pfunzo.karabossolution.gcm.NotificationUtils.showNotificationMessage(NotificationUtils.java:53)

        at com.apps.mudau.pfunzo.karabossolution.gcm.MyGcmPushReceiver.showNotificationMessage(MyGcmPushReceiver.java:71)

        at com.apps.mudau.pfunzo.karabossolution.gcm.MyGcmPushReceiver.onMessageReceived(MyGcmPushReceiver.java:58)

        at com.google.android.gms.gcm.GcmListenerService.zzq(Unknown Source)

        at com.google.android.gms.gcm.GcmListenerService.zzp(Unknown Source)

        at com.google.android.gms.gcm.GcmListenerService.zzo(Unknown Source)

        at com.google.android.gms.gcm.GcmListenerService.zza(Unknown Source)

        at com.google.android.gms.gcm.GcmListenerService$1.run(Unknown Source)

      • Pfunzo Mudau

        if the app is opened it works without an image, but if it’s running on the background and i send a push notification without an image it breaks

  • Yaqoub Alsaadi

    brother Ravi Tamada

    thanks aloot

    plz want your help to upload php files to 00webhost….

    waiting you brother

  • Ramesh K Menon

    Can you explain about batch push notification or any other istead of parse

    • Batch push notification can be done by sending the push to a channel. All the users who subscribed to that channel gets the notification. By the way this article doesn’t uses parse. It uses direct GCM.

      • Ramesh K Menon

        I’m using parse push notification for my app and parse already stopped.so which is good alternative for parse and give me an explanation

  • Ramesh K Menon

    Is there any other push notification instead of parse

  • thanx for this awesome tutorial ! everything’s good, but NotificationCompat.BigPictureStyle is not working on my case, my device always get small notifications. i do some logging and the method “showBigNotification()” on NotificationUtils.class is called, and image URL and bitmap is not null TT (i expect panda bitmap hehe) , anyway thx a lot Ravi 😀

    • If you are sure that your BigPictureStyle function is called and image is downloaded, there may be space issue to display then notification. Normally image will be hidden if there is not enough space in notification tray. Clear all the notification except your notification also remove the USB as it takes two notification spaces. Also swipe down the notification to see the image.

      Let me know if none of them are not fixing the issue.

      • aaaahh yeeahh you’re right ! i just swipe down the notification and the image is there ! i don’t know it’s have to be like that because other app usually show full notification with image, now it’s complete thanx 😀

        • Yeah, android hides the image if there is no enough space. Anyway congrats.

          Happy Coding 🙂

  • Trey Rosius

    These 3 articles have cleared all my doubts about GCM and Notifications.And you took about a week to get them ready.Your something else.Please keep up the good work.
    Thanks A Million.

  • Prathap

    Error:Execution failed for task ‘:app:processDebugGoogleServices’.
    > File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it.
    This
    is d bug which i have got…and i have google-services.json nut don’t
    knw wer to paste it…i hav tried al d combination of roots as
    well…plzz fix dis ASAP ji

  • Disha Mourya

    Awesome tutorial …Ravi Sir..

  • Disha Mourya

    A group can contain up to 20 devices only?

  • Disha Mourya

    Using this logic how can i implement single user chating?

  • DEEPAK SHINDE

    Error:Execution failed for task ‘:app:processDebugGoogleServices’.

    > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 8.3.0.

    Hey, I’m having this problem and Stack Overflow solutions are not working.
    I tried adding plugin line at the bottom of app level build.gradle, but it’s not working either
    Can you please look into it?

  • Prathap

    Error:Execution failed for task ‘:app:processDebugGoogleServices’.
    > File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it.
    This
    is d bug which i have got…and i have google-services.json nut don’t
    knw wer to paste it…i hav tried al d combination of roots as
    well…plzz fix dis ASAP ji

    • Disha Mourya

      Remove This from gradle:

      apply plugin: ‘com.google.gms.google-services’

      and add this in string.xml:

      Your Project ID

      • balaSaikrupa puram

        what is “your project id” means and where do I get this….

    • Shreyash Patel

      Add this google-service.json in app folder or module folder and then after apply plugin your bugs is solve

      • Prathap

        k i ll try out…tankz fr ur concern

      • Prathap

        hav tried bt not able to fix it…same popin up

  • Vishal Sheth

    Plugin with id ‘com.google.gms.google-services’ not found in Android Studio 🙁

    • Shreyash Patel

      this possible after putting .json file in app folder without adding this file in app folder you get error

      • Vishal Sheth

        I thought so too, but I have placed the google-services.json in the app folder of the Android project.My project structure shows the google-services.json file exactly as in the given screenshot.

        • Shreyash Patel

          you have also change Project build.gradle by adding this
          classpath ‘com.google.gms:google-services:1.5.0-beta2’

  • Shreyash Patel

    Hello Ravi sir,

    I first time implement the Push notification concept in android apps.

    I have implemented this push notification code in my project and i try for test its give just toast message ” Push notification is received! ” but no notification i shows till now in my device and i test this by your testing tools and one another testing tools both gives just Toast no notification are give.

    So what is the problem and why it not shows any notifications.

    Thanks & Regards

    • Is your device getting the gcm token which we printed in LogCat?

      • Shreyash Patel

        Yes
        Token Printed in toast and Logcat also This Token and My Apps API Key use for sendinf Push then its just display Push notification Received

        • If you are getting a Toast saying “Push notification received” then you successfully integrated the gcm. Handling the push notification is covered in the 3rd part.

          • Shreyash Patel

            Thanks for your reply.

            if i want notification when my apps is close then i need to refer 3 rd part. 3rd part is for Chat Apps but i don’t want chat apps so can i refer 3rd part
            and its shows notification when apps is close because till now i try to get notification then toast is get when apps is open or else its shows apps unfortunately close.

            If i need to show notification only from admin then which method i need to implement from 3rd part in client side.

            thanks

          • 3rd part is not about just chat app. It’s about handling the push notifications in various activities when the app is foreground / background state. Once you get the complete picture, you will be able integrate the push the way you wanted for your app.

          • Shreyash Patel

            ok sir,

            I will try to implement

            Thanks

  • Åmol Çhavhan

    Chavva Tutorial

  • Arihant Jain

    Hello Sir,

    I want to implement push notification in my app through eclipse .where i put google-services.json and how to implement please help as soon as possible

    • Don’t be afraid of Android Studio. Move to AS right away 🙂

      • Arihant Jain

        But i want to completed my project in eclipse do help me how to implement push notification in eclipse and sir also provide some in app purchase subscription code through google wallet

  • Arihant Jain

    Hello sir,

    I implement deprecated push notification code all work fine but i didn’t get notification on my mobile.I used your push notifications test panel. to send message message it also show pop message send successful but i didn’t get message on my cell.

    Api Key-AIzaSyBgvUlLc_PHr2kNALr80bh8uERGOaYcSXo

    Registerred Id-APA91bGiXxrio1t6NXWFe5Z0CJS9nMNxZAB5tnuUqqzm-5TrmFt9jAH1OAV5z-X3uYBinwJdCXI2C1_z7rCMsFmnBfjsMtNredhhFcjuQyPbFxKdus__bqCjxxa-e2PcOtV15_3qvCIj

    Please help to solve this. Thanks

  • esther nzomo

    Hello.
    am getting an error with the R.string.gcm_defaultSenderId in the Gcm_Intent_service. please help me.

    • Make sure you applied this line in build.gradle
      apply plugin: ‘com.google.gms.google-services’

  • Shriram Sukumaran

    I am struck with the login page. There is no response when i click the enter button

  • Muhammad Nurhidayat

    Hello Ravi, your work is awesome,
    I have a question, why in my phone I still get notification, whereas I already change GOOGLE_API_KEY and google-services.json with my account. Something missing? thanks.

    • Normally we need to remove the user from GCM, which I haven’t explained in the article.

      • Muhammad Nurhidayat

        why you have to remove the user? this api key and google-services.json is not used your account anymore. Thank you

  • Trey Rosius

    You have a typo in article 1. You wanted to write XMPP but wrote XAMP.

  • surfer

    Hi, i encountered the error: “peer not authenticated”, may I know what is the cause?

  • Eduardo Herrera

    Hey Ravi, when i try to login, a toast say Volley error:null

  • Magnificent BhuvAn

    Ravi Sir, In the part 2 segment , i only see the toast message “Push notification is receive” when i check the app in test panel… Where is my typed msg in test panel .. and also i did not unable to receive the image

    • 2nd part is about integrating the gcm and testing the push notification only. In the 3rd part, the handling of actual push message is explained.

      When you receive the image push notification, swipe down on the notification to see the image.

      • Magnificent BhuvAn

        mmm thanks sir,,, i will try and send my report quickly….but the article is awesome….. #Theri

  • hui

    you have error in manifest file fix it.#

  • Ashley

    Hi Ravi,

    I need some help,
    I’m getting these in my logs:

    [03-Mar-2016 18:47:38 UTC] PHP Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/ajappsco/public_html/chat/demo.php on line 24

    [03-Mar-2016 18:48:17 UTC] PHP Notice: Undefined variable: tasks in /home/ajappsco/public_html/chat/demo.php on line 26

    [03-Mar-2016 18:48:17 UTC] PHP Warning: Invalid argument supplied for foreach() in /home/ajappsco/public_html/chat/index.php on line 212

    [03-Mar-2016 18:48:17 UTC] PHP Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/ajappsco/public_html/chat/demo.php on line 32

    Fatal error: Call to undefined method mysqli_stmt::get_result() in

    /home/ajappsco/public_html/chat/include/db_handler.php on line

    164

    It’s something to do with $tasks = $stmt->get_result();

    Can you help?

    • You need to install mysqlnd support. (MySQL Native Driver)

      • Ashley

        On the app im getting a error:

        Failed send message Cannot add or update a child row: a foreign key contraint fails (‘ajappsco_gcm_chat’.’messages’, CONSTRAINT ‘messages_ibfk_2’ FOREIGN KEY (‘user_id’) REFERENCES ‘users’ (‘user_id’) ON DELETE CASCADE ON UPDATE CASCADE)

        Any help?

        • Ashley

          Dont worry I worked it out,

          Thank you again.

  • sunny sun

    the registration is going well but I couldn’t receive any notification and i don’t know why as i’m testing on real device because my emulator not have google play ?
    could please help me

  • Ashley

    Ravi,

    I have another question,

    I seem to be getting notifications from Androidhive,

    I’ve changed the URL in endpoint,
    What else do I need to amend?

    Thanks,

  • Diego Manuel Garay Leiva

    In StringRequest strReq = new StringRequest(Request.Method.POST,
    EndPoints.LOGIN, new Response.Listener()… Send a java.lang.NullPointerException When i migrate the GCM3.0 to other android project. I have the same settings of the GCM 3.0. Help me Pliss… Gretings From Chile !!!

  • Magnificent BhuvAn

    Sir, i finished part 3, but when i press enter in the Login Activity,, it show the error Unfortunately my app is stopped….. what i do,,,,

    • Check the LogCat. There might be an error.

      • Magnificent BhuvAn

        Sir, it shows “could not find persistableBundle……”… now what i do…… I search and try something from google… but…..

  • Alex Kash

    Hi, Please I’m very confused
    I’m trying to implement the Push Notif in my App with GCM 3.
    I don’t know if I should start straight with this code or in part 1

    • You will get good knowledge of GCM integration if you follow all the 3 parts.

      • Alex Kash

        Hey Ravi, thanks for you support… Is there any way to chat directly with you
        follow the 3 parts might be a bit long for me while my app doesn’t require so much

      • Alex Kash

        Hey Ravi,
        please is there any way to chat with you please?
        I don’t have enough time to follow and troubleshoot all the 3 parts while doesn’t require so much
        Thanks

  • Abdel

    Hi Ravi sir,
    Thanks for your great tutorials.
    I understood pretty much all the code you wrote excepte this line : “sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER, true).apply();”
    and an other one like it.
    I don’t seem to know the use of it. Can you please explain that to me ?
    One more thing, I’m thiniking of using shared prefs to store the GCM Token , so we don’t need to search for it every time; what do you think about that ?
    Many thanks in advance.

  • fpegios

    Hello Ravi! This great tutorial! Could you give me some info how to use the test panel in my pc locally? Thanks in advance.

  • Sharath Weaver

    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 GCMIntentService.java , 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.

  • Magnificent BhuvAn

    Sir, when i try first time the app is successfully runned. I uninstall the application but i did not perform logout operation… next time i install the application. when the app is open it suddenly closed and display the error “unfortunately the app is stopped”… i think some error in logout operation….what is your opinion sir….i try to solve this problem last one week.. but i did not have any solution …. now what i do … sir… in logcat the error is could not fine Persistablebundle and Fatal exception : main

  • Tom

    Hi Ravi,
    thanks for the tut. I still cannot get the admin page to work. It loads the topics from db, but i cannot add a message to a topic.
    Error: “Sorry! Unable to send message”
    I tried Postman with vars (user_id and message). Even there it says: “Field message_id does not have a default value” although I provided one.
    Thanks for your advise

  • Shriram Sukumaran

    hi ravi sir ,
    i followed your tutorials, i am getting volley null error in the android app (login page). Most importantly am getting 404(url not found) error during the api testing.Please help me.

    • Francesco

      me too

    • Anubhavanand884

      Me too getting Volley Error: Null

  • Venkat Sammeta

    03-09 21:48:01.747 11309-11309/info.androidhive.gcm E/AndroidRuntime: FATAL EXCEPTION: main

    Process: info.androidhive.gcm, PID: 11309

    java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollVertically()’ on a null object reference

    at android.support.v7.widget.RecyclerView.computeVerticalScrollRange(RecyclerView.java:1654)

    at android.view.View.onDrawScrollBars(View.java:12832)

    at android.view.View.draw(View.java:15128)

    at android.support.v7.widget.RecyclerView.draw(RecyclerView.java:3097)

    at android.view.View.updateDisplayListIfDirty(View.java:14056)

  • Manu

    Hi Ravi ,
    I am getting a 404(url not found) for /user/login testing

  • Manu

    Guys those who are getting 404 error while REST testing
    use the full path instead
    for eg./user/login should be like /index.php/user/login

  • Hi Ravi, I was doing it right, and succeed, but why when I send data to gcm using push_test.php of my project that I keep in my own web hosting take a long time to be done ?, but in this link http://demo.androidhive.info/gcm_chat/push_test.php it just take little bit time..? :'(
    why…, please help me…

  • DEEPAK SHINDE

    Hi, I’ve followed all your steps, and even though above test panel says, test notification has been sent! I don’t get any notification. I do enter the server key we have created and the GCM token from logcat. Can you think of anything ?

  • Magnificent BhuvAn

    mmm Thanks Ravi Tamada Sir, Nice Article …. Hatsoff

  • Kepi Agrawal

    Hello , Thanx for such a awesome post.. but i am not getting notification on time it reaches too late.. and some time its not proper like if i am sending “HI” it wil reach as “ggcce” .. can you please help me.

    Thanx in advance..

    and yeah one more thing you are such a brilliant guy i just love your tutorials..

  • Александр Виноградов

    That’s realy cool Ravi !! Thanks! Hello from in Russia

  • Dusien Yeldisbayev

    Cool! Thanks! Hello from Kazakhstan

  • Erik Franck

    Hi, thank you very much for your help.
    Just one problem : Can’t access to the push notification test panel. It links to a php file but it never opens. Any server problem ? 🙂

    • Erik Franck

      Problem solved 🙂

  • Mayur Chougule

    Hi Ravi, thank you for this post. I downloaded your .apk file, and everything works. Then I tried to use that in my app, but it keeps giving me an error: “MismatchSenderId”.
    {“multicast_id”:6607548391650009580,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”MismatchSenderId”}]}

    I looked up a lot, everyone says something about senderId in the Android app. I am not sure where this is in your example or where I would fix the Project ID in my app. I am new to this, I would really appreciate if you can give me more insight on this.

    Thank you!

    Mayur

    • Mayur Chougule

      I apologize. I created a new application on GCM, but never downloaded a new version of google-services.json.
      It works great! Thank you! 🙂

  • Christian Fouda

    I downloaded the files both client side and server side. I then integrate them within my app. I can log in as the database is updated. The topic are loaded properly but I can not send a message to a topic. Additionally I can not send a message to a single user. I always get “Sorry. Unable to send the message.”

    Any idea?

  • Hello Mr Ravi

    Thanks for this tutorial and the whole project

    i’ve installed this on my website and everything going “ok”, after enable mysqli and pass the get_result(); error i’m getting another issue at the point of register the user

    with Postman i’m getting the message “Oops! An error occurred while registereing” and with android app i’m getting the message “json parsing error: Value true at error of type java.lang.Boolean cannot be converted to JSONObject”

    can you help me on this please?

    Regards

    • Fixed, Thanks

      • Faten Hazira Jamaludin

        how did u fixed it?

        • Setting AUTO_INCREMENT the user_id of table users and message_id of table messages will fix the error in user register

          • Faten Hazira Jamaludin

            fixed. thank u 🙂

          • You’re welcome 🙂

          • Shriram Sukumaran

            thanks a lot was struggling with for a week…..thank you so much pedro!!!!
            but still i am not able to see any of my contacts in the chat room. I just get a blank white screen with a toolbar can you help?

          • Are you trying in Local Host or Shared Hosting?

          • Are you trying in Local Host or Shared Hosting?

          • Shriram Sukumaran

            am trying it in the localhost is there any problem in it?
            Should i host in some other place?

          • AnthonyHaddad

            same problem:/ how to fix please ?

          • What is the problem? clearly explain it.

          • Shriram Sukumaran

            hi sir,
            really pleased with your tutorial very happy that you are extenting your help to clear the errors. I will explain you clearly

            When i log in by entering the mail-id and the name i am able to see only the white screen with violet toolbar named Google Cloud Messaging (as designed by you).There are no topics or chats in there.

            Also wen i send messages between two emulators i am not able to see the messages in the chatroom as unread. I am able to read it only when i click on the chat(i.e when i go into individual chatroom)
            thank you.

          • May be you are having php errors. Check the urls from a rest api client and make sure that the json is generating correctly.

          • Shriram Sukumaran

            thanks for your reply. But i dont have any problem with the rest api all the url’s are working perfectly i have tested them using postman (app).Any other suggestions please. Orelse please tell me whether i should check with any specific url (please specify the method type also(put,get,etc..))

          • AnthonyHaddad

            go to your MySQL’s chat topics table and add topics in there

  • Eno

    can u give me push_test.php script ..? please

  • 최준혁

    Thanks ravi. great tutorials for gcm beginner like me but.. i got an error.

    when my application is running state, push notifications received well BUT, when background state, application just stop running. HERE’s error Log, give me a answer plz..

    —————————————————–

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: Process: com.example.my1.activity, PID: 14804

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: java.lang.NullPointerException

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.example.my1.tuber.gcm.NotificationUtils.showSmallNotification(NotificationUtils.java:105)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.example.my1.tuber.gcm.NotificationUtils.showNotificationMessage(NotificationUtils.java:93)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.example.my1.tuber.gcm.NotificationUtils.showNotificationMessage(NotificationUtils.java:53)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.example.my1.tuber.gcm.MyGcmPushReceiver.showNotificationMessage(MyGcmPushReceiver.java:72)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.example.my1.tuber.gcm.MyGcmPushReceiver.onMessageReceived(MyGcmPushReceiver.java:59)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.google.android.gms.gcm.GcmListenerService.zzq(Unknown Source)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.google.android.gms.gcm.GcmListenerService.zzp(Unknown Source)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.google.android.gms.gcm.GcmListenerService.zzo(Unknown Source)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.google.android.gms.gcm.GcmListenerService.zza(Unknown Source)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at com.google.android.gms.gcm.GcmListenerService$1.run(Unknown Source)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

    03-19 14:24:54.633 14804-15465/com.example.my1.activity E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

  • Anubhavanand884

    I am getting
    Failed to resolve: com.google.android.gms:play-services-measurement:8.3.0
    How to get rid of that ???

  • AnthonyHaddad

    hello sir, great tutorial, very organized.

    im having this problem where the topic chat room doesnt load, the box is empty where there should be topics.

    any idea how to fix it please? thanks.

    • Do you have topics in your mysql topics table?

      • AnthonyHaddad

        the problem was in my code logic, i have misplaced 2 rows.
        thanks for the awesome tutorial Ravi 🙂

  • Helmi Susanto

    Hi Mr. Ravi, i very love your tutorial

    this is simply and organized, iam beginer of android code and very help me,

    GOD bless You Sir…

  • Anum Amin

    Your every tutorial is simply awesome – well explained. Thanks for making Android’s developer life easy!

  • Dnyaneshwar Kanpurne

    Hi Ravi … when i get push notification on device it is also showing previous push notifications with currect push … how to fix this problem …

    • In Config.java make set appendNotificationMessages to false.

      • Fatah Zull

        Hi Ravi, Push Notifications not working when my app in foreground. how to fix this problem?

      • Akshay Gaba

        No Push Notification when app in foreground ? How to fix this ravi sir?

      • Hari V

        Hi Ravi , Notification is not working in Foreground.

        LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification) is breaking

  • Ketan Thakkar

    Hello, Can You helpe me to create Device to Device Chat (Personal Chat Application).

    Email ID : ktn.thkkr@gmail.com

  • Ibrahim Samad

    Thanks for that tutorial 🙂
    Please will I need to reference the “Google API Key” anywhere in the android project. I don’t seem to find it anywhere in the java files.
    THANKS

    • Shriram Sukumaran

      Yes,Obviously you need to have your own API key to enable the GCM services for your project. Have you got your API key from the Google developer console or not? If not goto the below link to obtain the same
      https://console.developers.google.com

    • Shriram Sukumaran

      You can find it in the config.php file. Replace your own key with the existing one. If you have not your own then goto
      https://console.developers.google.com and get it.

      • Ibrahim Samad

        No, am referring to the android project(the java part), not the restapi or PHP.
        I don’t have any problem with the PHP aspect.

        • Shriram Sukumaran

          Probably we don’t mention our api anywhere in the java coding

    • Matias

      Hello,

      I have the same problem, I can not find in the project configuration id android project or API Key. You could solve it ?. Thank you

      • You won’t add Google API manually in this. Instead we download google-services.json in which api key is added automatically.

  • wapjude

    please where do i post the API key cause it fails to generate the device ID

  • Mohab Youssef

    How can i send automatic notification when mysql database has a change in specific table ?

  • wapjude

    please help could not get my device registration id, what could be wrong

  • prasoon sharma

    I had one question …when i use ‘

    com.google.android.gms:play-services-gcm:8.4.0’ in that case i am not able to get gcm_defaultSenderId

    • justDisqus

      not even in 8.3.0

  • Mridul Dhar

    I am having a problem in the manifest in the line
    <service
    android:name="gcm.GcmIntentService" . Android Studio says it cannot recognise GcmIntentService even though the dropdown list shows this service when I type only gcm.

  • md technology

    Awesome Tutorial.

  • Dear Ravi,

    The tutorial is very helpful. I am stuck at few places, however. At which point should we ideally call RegistrationIntentService. I am thinking to call it on login. But when I get the token in RegistratoinIntentService, I store it on my app server but then I want to open MainActivity. How to do it.? Please help.

    Thanks.

  • justDisqus

    Great Tutorial.

    However, when I import this tutorial source code, it works fine, except it shows the notification is sent but it isnt on the device. Only notification with image is received.

    Secondly, I was trying the same code with my own package name and json file, it shows this error
    Attempt to invoke virtual method ‘package.name.helper.MyPreferenceManager package.name.app.MyApplication.getPrefManager()’ on a null object reference’

    I tried to fix it but unfortunately couldn’t.

    Thanks in advance

    • Have you added MyApplication to AndroidManifest.xml application tag? Check the package name there.

      • justDisqus

        Many thanks, that was the issue.

        Now i am relieving this error

        Error:(73, 66) error: cannot find symbol variable gcm_defaultSenderId
        in GcmIntentService.java

  • samudrala sandeep

    Sir I have downloaded the source code given in this article. I have opened gcm3.0 project in andriod studio. when I run it in a emulator it is asking name and email, after giving it if I tap enter button, I got volly error:null.

    How to resolve it.??

    • Kaushal Shah

      I also had the same Problem! Found Solution:

      volly error: null because URL used in Demo is changed now.

      in File: appsrcmainjavainfoandroidhivegcmappEndPoints.java

      Change it BASE_URL = “http://demo.androidhive.info/gcm_chat/v1”;

      Now, It will work Fine.
      If the same exist then check your phone net connection!

  • Saurabh G

    Hi Ravi,
    I have implemented the Push Notifications in my app successfully, it working as expected at my end but app gets crashed when app runs in other countries. And without push notifications app working fine in other countries.
    Can you please tell me the possible reasons fro this and solution over this as well..??

    • Myscrap New

      Do you get the message from the Demo server??

    • Myscrap New

      i cant get push notification from the server.. Please help

  • JohnyD

    Hello all,

    First – it is amazing tutorial about GCM, thank you very much Mr. @ravi8x:disqus.
    I`m little confused because in part 1 of tutorial – implementing GCM is deprecated and not updated and made me trouble with my project:
    – I have implemented all of steps from this tutorial (mean part 2) – it is worked.
    – I want to make notification from my server side (localhost), not from Ravi`s test panel.
    So, my question is – is it possible join this functional solution (i mean only part 2) with my localhost server and php files? If yes, how? What I need do? What php files are needed? Can someone please help me?

    Thank you!

  • Ved Prakash

    hi everyone, how to solve this issue when i import project in studio
    Unknown host ‘jcenter.bintray.com’

  • Akshay Gaba

    Successfully able to build my project with this code but unable to push notification from your panel.Tried multiple times with API-key and GCM token

  • Abdelstar Ahmed

    hi ravi can u please say how to change $stmt->get_result() with $stmt->bind_result() and $stmt->fetch
    cause mysql didn’t defined it in my server

    • PR_DIMPU

      instead install mysqlnd it will work

    • Tendai Maswaya

      Hi Abdelstar, did you find a solution to your problem, im facing a similar problem and have not found the solution yet.

  • Yogesh

    hi ravi nice tutorial..but i want to use only push notification from server to mobile…this tutorial is related with chat & its bit complicated..can u make one article for simple push notification for server to mobile…Thanks

  • aseel saif

    why we use the singleton class???

  • Krona

    Hi Ravi, I’m following this tutorial in my application, but I have some problems.If I send a message, a notification sound come out on a device that sends a message. Which part is wrong?

  • Android_Rocks

    Please solve my Error .
    i have an error with server side coding .
    i have download your code and server side past your coding this folder “gcm_chat”. and also change “config.php” file .
    >Android Side Perfect Integration no Error . Complete Run And Store id to my Vps Server .
    >But i cant Send Push Message because When I run “index.php” . Its say “Fatal error: Call to undefined method mysqli_stmt::get_result() in/gcm_chat/demo.php on line 25”

    >and also in browser alert say “Sorry! Unable to fetch topic messages”
    > i have a vps server so please tell me what about other requirement

    • Tendai Maswaya

      Same problem here. No solution yet. Will update if i do

      • Android_Rocks

        officially Ravi have no given any answer so i have lost of RND on web and i have found one super Blog about pure gcm if you can refer this artical

        https://neurobin.org/docs/android/push-notification-gcm-client-server/

      • pranav m.s

        I think in your server side PHP script . You are using or created the connection in MySQL but here you are trying to use mysqli so please have a look at your connection string.If the connection is created in mysql so you should use mysql with the same instance.

  • Android_Rocks

    this permission is deprecated please give alternative.

    • Hmm. I don’t have the code ready.

    • Fabio

      Hi,

      Just add this to file Manifest:

  • Mateusz

    Hi Ravi I saw that in my JSON from google I do not have lines which are in Your JSON:
    “”cloud_messaging_service”: {
    “status”: 2,
    “apns_config”: []
    }”
    do You know if that might be an issue ? I can not find anything in google… (I have enabled GCM before creating JSON)

    • Have you enabled Google Cloud Messaging before generating the json?

      • Mateusz

        Yes!

  • Fabio

    Hi Rabi,
    As I update my gcm_id and how to know when change to be stored in database?

    Very Thanks!

    • يعقوب السعدي

      hi Fabio
      could send your project and server php??

  • dev

    hello Ravi,
    i am getting a browser alert say “Sorry! Unable to fetch topic messages”

  • Hari V

    Hi Ravi, Thanks for the detailed explanation. Flowed the tutorial, but not able to manage Application in foreground! Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
    pushNotification.putExtra(“message”, message); is breaking. Could you pls throw some light on the same ?

  • krn
  • Raja R

    Almost 2 weeks gone..no reply?
    Getting volley error:null
    Gcm Id not getting………

    • kushagra

      I am not getting the toast when the app first launch, not getting any gcm registration in the log cat and when I use to type username and email in app it toasts volley error:null

      • Fesi Nagetive

        did you find any answer to this I am also facing the same problem?

        • kushagra

          still no @fesinagetive:disqus

      • Ibrahim Samad

        If you are not getting registration token, check to make sure you actually included .MyFirebaseInstanceIDService in your android manifest file.

    • Shriram Sukumaran

      hello raja,
      are the url’s such as post,get working properly(in api testing)?

      • kushagra

        yes its working properly but with the minor changement from this link — /user/login to /index.php/user/login….logcat showing error

        23676-24548/info.androidhive.gcm E/LoginActivity﹕ params: {email=example@gmail.com, name=abc}
        23676-24548/info.androidhive.gcm E/LoginActivity﹕ params: {email=example@gmail.com, name=abc}
        23676-23676/info.androidhive.gcm E/LoginActivity﹕ Volley error: null, code: null
        23676-23676/info.androidhive.gcm D/Volley﹕ [1] Request.finish: 7764 ms: [ ] http://live_ip_address/gcm_chat/v1/user/login 0x44e0acb1 NORMAL 7

        I think the problem lies in that i am using http://live_host_ip_address/gcm_chat/v1/index.php/user/login from the Postman Chrome REST API but in logcat its showing http://live_host_ip_address/gcm_chat/v1/user/login

    • kushagra

      i have created question regarding this-http://stackoverflow.com/questions/38367844/chat-app-using-gcm-php-mysql

    • Aqib Khan

      ii also geting this problem

  • Thomas Nana Baisi Davis

    i uploaded to my sever and changed the base_url now am getting volley error :null

  • Pradeep Kumar Reddy

    I’m not getting notification sound. what could be the issue ?

  • JK Khant

    gcmsenderid not found “String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId)”

    • Eno

      getToken(“your_senderID”) or u define in string.xml, so use getToken(getString(R.string.gcm_default))

      • JK Khant

        thanks eno but my problem is solved i miss add this line in grandle file”apply plugin: ‘com.google.gms.google-services'”………….

  • Ceyhun Mamedov

    com.google.android.gms:play-services:8.3.0 gives error

  • Boon

    You always create complicated code for even single task.You should do simple task simply

    • Can you give an example of complex and easier solution for it?

  • I want video tutorial for it please do this 🙁

  • Saurabh Bhat

    Hi Ravi, you are doing a great job and reducing the pain of a developer. keep up the good work going. In my project i have migrated from GCM to FCM, whole project is working fine but can you please tell me how to get the count of push when app is in background or closed. Count works fine when the app is in foreground but when my app is in background as soon as the page loads it vanishes please please help!!

  • Aqib Khan

    Can’t redirect to app settings for Google Play services this error occurs

  • SeungJun Jung

    For whom having trouble with MultiDex Problem (When applying your application to smartphone)…

    You would want to do something like…

    But multiple application tagging is not possible in android.

    If you are having trouble with this issue, please visit this site:(http://stackoverflow.com/documentation/android/1887/multidex-and-the-dex-method-limit#t=201701231628028017765)

    and try to use MultiDex.install(this) (reply # 12)

    Good luck

  • sulistyo adi

    hi Ravi, can i replacing volley with retrofit2 as well

  • Ansari md

    hii,
    Notification not showing when app in running please help me as soon as possible

  • Ritu Rajan

    Your test.php show notification sent but didnt received any notification except a Toast msg on device?

  • Patrick Hills

    Hello Ravi thanks to you for new upcoming programmers like us making a head way out, The app runs fine but when i onclick on a top it crashes;
    Thank you.

    below is the log

    03-18 19:35:17.429 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: FeatureProxyBase class constructor
    03-18 19:35:17.430 22998-22998/com.example.telcomaghana.hisschat D/MultiWindow: MultiWindowProxy constructor.
    03-18 19:35:17.430 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: getService(), serviceName = multiwindow_service_v1
    03-18 19:35:17.477 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: FeatureProxyBase class constructor
    03-18 19:35:17.477 22998-22998/com.example.telcomaghana.hisschat D/MultiWindow: MultiWindowProxy constructor.
    03-18 19:35:17.477 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: getService(), serviceName = multiwindow_service_v1
    03-18 19:35:17.500 22998-22998/com.example.telcomaghana.hisschat V/wst: zzzDisableLRTBSensorDirection mControlFlag===0
    03-18 19:35:17.501 22998-22998/com.example.telcomaghana.hisschat D/ActivityThread: ACT-AM_ON_PAUSE_CALLED ActivityRecord{233ccdee token=android.os.BinderProxy@3bb6628f {com.example.telcomaghana.hisschat/com.example.telcomaghana.hisschat.activity.MainActivity}}
    03-18 19:35:17.508 22998-22998/com.example.telcomaghana.hisschat D/ActivityThread: ACT-PAUSE_ACTIVITY handled : 1 / android.os.BinderProxy@3bb6628f
    03-18 19:35:17.509 22998-22998/com.example.telcomaghana.hisschat V/ActivityThread: Handling launch of ActivityRecord{744ca9c token=android.os.BinderProxy@1eadfca5 {com.example.telcomaghana.hisschat/com.example.telcomaghana.hisschat.activity.ChatRoomActivity}}
    03-18 19:35:17.541 22998-22998/com.example.telcomaghana.hisschat V/ActivityThread: ActivityRecord{744ca9c token=android.os.BinderProxy@1eadfca5 {com.example.telcomaghana.hisschat/com.example.telcomaghana.hisschat.activity.ChatRoomActivity}}: app=com.example.telcomaghana.hisschat.app.MyApplication@246e1648, appName=com.example.telcomaghana.hisschat, pkg=com.example.telcomaghana.hisschat, comp={com.example.telcomaghana.hisschat/com.example.telcomaghana.hisschat.activity.ChatRoomActivity}, dir=/data/app/com.example.telcomaghana.hisschat-1/base.apk
    03-18 19:35:17.542 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: FeatureProxyBase class constructor
    03-18 19:35:17.543 22998-22998/com.example.telcomaghana.hisschat D/MultiWindow: MultiWindowProxy constructor.
    03-18 19:35:17.543 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: getService(), serviceName = multiwindow_service_v1
    03-18 19:35:17.544 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: FeatureProxyBase class constructor
    03-18 19:35:17.545 22998-22998/com.example.telcomaghana.hisschat D/MultiWindow: MultiWindowProxy constructor.
    03-18 19:35:17.545 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: getService(), serviceName = multiwindow_service_v1
    03-18 19:35:17.546 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: FeatureProxyBase class constructor
    03-18 19:35:17.546 22998-22998/com.example.telcomaghana.hisschat D/MultiWindow: MultiWindowProxy constructor.
    03-18 19:35:17.546 22998-22998/com.example.telcomaghana.hisschat D/FeatureProxyBase: getService(), serviceName = multiwindow_service_v1
    03-18 19:35:17.582 22998-22998/com.example.telcomaghana.hisschat V/TextView: stopSelectionActionMode()
    03-18 19:35:17.582 22998-22998/com.example.telcomaghana.hisschat V/TextView: stopSelectionActionMode()
    03-18 19:35:17.582 22998-22998/com.example.telcomaghana.hisschat V/TextView: stopSelectionActionMode()
    03-18 19:35:17.586 22998-22998/com.example.telcomaghana.hisschat D/AndroidRuntime: Shutting down VM
    03-18 19:35:17.587 22998-22998/com.example.telcomaghana.hisschat E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.telcomaghana.hisschat, PID: 22998
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.telcomaghana.hisschat/com.example.telcomaghana.hisschat.activity.ChatRoomActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2521)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595)
    at android.app.ActivityThread.access$800(ActivityThread.java:178)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5631)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
    Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
    at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:198)
    at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
    at com.example.telcomaghana.hisschat.activity.ChatRoomActivity.onCreate(ChatRoomActivity.java:63)
    at android.app.Activity.performCreate(Activity.java:6098)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595) 
    at android.app.ActivityThread.access$800(ActivityThread.java:178) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470) 
    at android.os.Handler.dispatchMessage(Handler.java:111) 
    at android.os.Looper.loop(Looper.java:194) 
    at android.app.ActivityThread.main(ActivityThread.java:5631) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) 

  • Dexter Fury (Kombat Zone)

    Am getting this error

    Warning: mysqli::mysqli(): (HY000/2002): Connection refused in /var/www/html/demos/gcm_chat/include/db_connect.php on line 24
    Failed to connect to MySQL: Connection refused
    Warning: mysqli::prepare(): Couldn’t fetch mysqli in /var/www/html/demos/gcm_chat/demo.php on line 41

    Fatal error: Call to a member function bind_param() on a non-object in /var/www/html/demos/gcm_chat/demo.php on line 42

    • Dexter Fury (Kombat Zone)

      Am using Xammp

    • Ibrahim Samad

      Check to make sure mysql is started and mysqli extension is enabled(which should be the case by default)

  • Dexter Fury (Kombat Zone)

    Please help i cant go to admin panel am getting this error

    Warning: mysqli::mysqli(): (HY000/2002): Connection refused in /var/www/html/demos/gcm_chat/include/db_connect.php on line 24
    Failed to connect to MySQL: Connection refused
    Warning: mysqli::prepare(): Couldn’t fetch mysqli in /var/www/html/demos/gcm_chat/demo.php on line 41

    Fatal error: Call to a member function bind_param() on a non-object in /var/www/html/demos/gcm_chat/demo.php on line 42

    • You need to enable mysqli extension or install mysqlnd.

      • Dexter Fury (Kombat Zone)

        Thanks for the reply i will try that, also please post new source code all the links from part 1, 2 and 3 are not working.

        • The Download button is there at the beginning of the article.

  • Waqas Ahmed

    i need code that how to upload mp3 file to wamp server using php mysql…and how to download mp3 file from wamp server to android like whatsapp..pls this is my project i need ths code
    waqaskhattak99@gmail.com

  • Muneer Khan

    Greetings, I’ve followed the part 1 and 2 correctly, however when I run the app it gives the following error
    “FATAL EXCEPTION: IntentService[GcmIntentService]” in LogCat, anyone knows what this means? Thank you! 🙂

  • Kevin.c Ciang

    @ravi8x:disqus I got this error message in android monitor while testing it:

    FATAL EXCEPTION: IntentService[GcmIntentService]
    Process: com.ciangproduction.cp.gcmchat, PID: 17656
    java.lang.IllegalAccessError: Method ‘void android.support.v4.content.ContextCompat.()’ is inaccessible to class ‘com.google.android.gms.iid.zzd’ (declaration of ‘com.google.android.gms.iid.zzd’ appears in /data/data/com.ciangproduction.cp.gcmchat/files/instant-run/dex/slice-com.google.android.gms-play-services-gcm-8.3.0_5c1d4906320bc415b6e4fa1a57736a6d7609d332-classes.dex)
    at com.google.android.gms.iid.zzd.zzdL(Unknown Source)
    at com.google.android.gms.iid.zzd.(Unknown Source)
    at com.google.android.gms.iid.zzd.(Unknown Source)
    at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
    at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
    at com.ciangproduction.cp.gcmchat.gcm.GcmIntentService.registerGCM(GcmIntentService.java:65)
    at com.ciangproduction.cp.gcmchat.gcm.GcmIntentService.onHandleIntent(GcmIntentService.java:52)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.os.HandlerThread.run(HandlerThread.java:61)

    the error is in this line

    InstanceID instanceID = InstanceID.getInstance(this);
    token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
    GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

  • Subrata Debnath

    from my mobile whenever i try to enter my name and email id ,its saying volley error:null.

  • Premkumar Agrawal

    Hi, Ravi will this thing work with Firebase because whenever I try to add Google Cloud Messaging in GOOGLE API Manager it takes me to Firebase console.