Hello friends, I got a lot of messages requesting to publish Android Push Notification using GCM tutorial. So today I am posting it. Majority of people finds android push notification using gcm is a difficult task. Now if you also had trouble or still stuck in implementing android push notification using gcm then don’t worry today I came up with an easy to follow tutorial. Just read the whole post carefully and you will be able to implement android push notification using gcm in your app.
Firebase Cloud Messaging Tutorial using PHP and MySQL
With this tutorial you will be able to send notification on individual device manually. If you are looking for device registration on server to broadcast messages to multiple device follow this Google Cloud Messaging Tutorial to Broadcast Message across Multiple Devices.
Contents
What is GCM?
For peoples who don’t know what is GCM? GCM stands for google cloud messaging. It is a service given by google that helps us to send both downstream and upstream messages between mobile and server. GCM is free to use and you can also create real time chat applications using GCM.
Also check: Android Push Notification Tutorial using Firebase
Android Push Notification using GCM
In this post we will not be creating a chat application. We will only create a simple example of integrating push notification using google cloud messaging. Before going further you can check the following video to know what we will be creating on this tutorial.
Creating an Android Studio Project
- Again we need to create a new Android Studio Project. So open Android Studio and create a new project. I have created AndroidGCM.
- Now once your project is loaded, copy the package name of your project. You can get the package name by going to the manifest file.
1 2 3 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedcoding.androidgcm"> |
- Now we need to configure our application in Google Developers Console.
Creating an App in Google Developers
- In this step we need to get google-services.json file. This file contains the configuration specific to your application.
- Go to this link. And click on GET A CONFIGURATION FILE (See the image below).
- Now you will be asked to enter an app name, and your application’s package name. Just put an app name (I have written MyGCMExample) and the package name of the project your created. We copied the package name after creating project from the manifest so you only need to paste it here (see the image below) and click on Continue To Choose and Configuration Service.
- Now in the next screen you will see a button to enable google cloud messaging, click on that.
- After clicking on Enable Google Cloud Messaging you will get Server API Key and Sender Id. Copy it and save it on a text file it will be used.
- Now Scroll below and click on Continue To Generate Configuration Files.
- Now you will get a button to download the configuration file. Click on the button and you will get your goolge-services.json file.
- Your Google App part is over, now we will again come to our Android Studio Project.
Implementing Android Push Notification
Project Configuration
- Follow the steps from here very carefully. The first thing we need is to add the google-services.json to our project.
- Click on the project explorer and select project.
- Right click on the app folder and paste the json file you just downloaded.
- Come inside your app level build.gradle file and add the following lines.
1 2 3 4 5 6 7 8 9 10 11 |
dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' //This line is added compile 'com.google.android.gms:play-services-gcm:8.3.0' } //This line is added apply plugin: 'com.google.gms.google-services' |
- You also need to add two more lines inside your project level build.gradle file. So open project level build.gradle and modify the codes as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// 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:1.5.0' //These two lines are added classpath 'com.google.gms:google-services:1.5.0-beta2' classpath 'com.android.tools.build:gradle:2.0.0-alpha6' // 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 } |
- Thats it now just sync your project.
Creating GCMRegistrationIntentService
- After syncing create a new java class named GCMRegistrationIntentService.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
package net.simplifiedcoding.androidgcm; import android.app.IntentService; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; /** * Created by Belal on 4/15/2016. */ public class GCMRegistrationIntentService extends IntentService { //Constants for success and errors public static final String REGISTRATION_SUCCESS = "RegistrationSuccess"; public static final String REGISTRATION_ERROR = "RegistrationError"; //Class constructor public GCMRegistrationIntentService() { super(""); } @Override protected void onHandleIntent(Intent intent) { //Registering gcm to the device registerGCM(); } private void registerGCM() { //Registration complete intent initially null Intent registrationComplete = null; //Register token is also null //we will get the token on successfull registration String token = null; try { //Creating an instanceid InstanceID instanceID = InstanceID.getInstance(getApplicationContext()); //Getting the token from the instance id token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); //Displaying the token in the log so that we can copy it to send push notification //You can also extend the app by storing the token in to your server Log.w("GCMRegIntentService", "token:" + token); //on registration complete creating intent with success registrationComplete = new Intent(REGISTRATION_SUCCESS); //Putting the token to the intent registrationComplete.putExtra("token", token); } catch (Exception e) { //If any error occurred Log.w("GCMRegIntentService", "Registration error"); registrationComplete = new Intent(REGISTRATION_ERROR); } //Sending the broadcast that registration is completed LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } } |
Creating GCMTokenRefreshListenerService
- Now create a new class named GCMTokenRefreshListenerService.java this will be used to register the device again if the server token has changed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package net.simplifiedcoding.androidgcm; import android.content.Intent; import com.google.android.gms.iid.InstanceIDListenerService; /** * Created by Belal on 4/15/2016. */ public class GCMTokenRefreshListenerService extends InstanceIDListenerService { //If the token is changed registering the device again @Override public void onTokenRefresh() { Intent intent = new Intent(this, GCMRegistrationIntentService.class); startService(intent); } } |
Creating GCMPushReceiverService
- Now we need to create the receiver for our android push notification using gcm. Create a new class named GCMPushReceiverService.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package net.simplifiedcoding.androidgcm; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import com.google.android.gms.gcm.GcmListenerService; /** * Created by Belal on 4/15/2016. */ //Class is extending GcmListenerService public class GCMPushReceiverService extends GcmListenerService { //This method will be called on every new message received @Override public void onMessageReceived(String from, Bundle data) { //Getting the message from the bundle String message = data.getString("message"); //Displaying a notiffication with the message sendNotification(message); } //This method is generating a notification and displaying the notification private void sendNotification(String message) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); int requestCode = 0; PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT); Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentText(message) .setAutoCancel(true) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, noBuilder.build()); //0 = ID of notification } } |
Coding our MainActivity
- Now come to your MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
package net.simplifiedcoding.androidgcm; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.app.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.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; /** * Created by Belal on 4/15/2016. */ //this is our main activity public class MainActivity extends AppCompatActivity { //Creating a broadcast receiver for gcm registration private BroadcastReceiver mRegistrationBroadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Initializing our broadcast receiver mRegistrationBroadcastReceiver = new BroadcastReceiver() { //When the broadcast received //We are sending the broadcast from GCMRegistrationIntentService @Override public void onReceive(Context context, Intent intent) { //If the broadcast has received with success //that means device is registered successfully if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_SUCCESS)){ //Getting the registration token from the intent String token = intent.getStringExtra("token"); //Displaying the token as toast Toast.makeText(getApplicationContext(), "Registration token:" + token, Toast.LENGTH_LONG).show(); //if the intent is not with success then displaying error messages } else if(intent.getAction().equals(GCMRegistrationIntentService.REGISTRATION_ERROR)){ Toast.makeText(getApplicationContext(), "GCM registration error!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Error occurred", Toast.LENGTH_LONG).show(); } } }; //Checking play service is available or not int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); //if play service is not available if(ConnectionResult.SUCCESS != resultCode) { //If play service is supported but not installed if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { //Displaying message that play service is not installed Toast.makeText(getApplicationContext(), "Google Play Service is not install/enabled in this device!", Toast.LENGTH_LONG).show(); GooglePlayServicesUtil.showErrorNotification(resultCode, getApplicationContext()); //If play service is not supported //Displaying an error message } else { Toast.makeText(getApplicationContext(), "This device does not support for Google Play Service!", Toast.LENGTH_LONG).show(); } //If play service is available } else { //Starting intent to register device Intent itent = new Intent(this, GCMRegistrationIntentService.class); startService(itent); } } //Registering receiver on activity resume @Override protected void onResume() { super.onResume(); Log.w("MainActivity", "onResume"); LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(GCMRegistrationIntentService.REGISTRATION_SUCCESS)); LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, new IntentFilter(GCMRegistrationIntentService.REGISTRATION_ERROR)); } //Unregistering receiver on activity paused @Override protected void onPause() { super.onPause(); Log.w("MainActivity", "onPause"); LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); } } |
- At last we need to add our listeners and broadcast receivers to manifest file, we also need to add some permission on manifest file.
- So open AndroidManifest.xml and modify it as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedcoding.androidgcm"> <!-- Adding permissions -internet -Wake_Lock -C2D_Message --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <permission android:name="net.simplifiedcoding.androidgcm.permission.C2D_MESSAGE" android:protectionLevel="signature" /> <uses-permission android:name="net.simplifiedcoding.androidgcm.permission.C2D_MESSAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- GCM Receiver --> <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="com.gnirt69.gcmexample"/> </intent-filter> </receiver> <!-- GCM Receiver Service --> <service android:name=".GCMPushReceiverService" android:exported="false"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE"/> </intent-filter> </service> <!-- GCM Registration Intent Service --> <service android:name=".GCMRegistrationIntentService" android:exported="false"> <intent-filter> <action android:name="com.google.android.gms.iid.InstanceID"/> </intent-filter> </service> </application> </manifest> |
- Thats it now just run your application.

Android Push Notification using GCM
- And if you can see the registration token in the toast then Bingo!, you have done it 😉
- In real world scenario we store this token into web server to send the push notification to the device, but as this tutorial is meant to teach you about implementing gcm only we need to copy this token to send a notification.
- Thats why we have displayed the token in the log as well, so that you can copy the token from the log. So just see your log and copy the token (see the image below).
- Copy the whole token string and remove “token:” from it. Now you have the registration token and your Server API Key.
Sending Push Notification to the Device
- To send push notification go to this link.

Android Push Notification using GCM
- On the first input field enter your SERVER API KEY, on second enter REGISTRATION TOKEN and on third enter the message you want to send, and click on send.
- And check your device.

Android Push Notification using GCM
- Bingo! We got the notification. Now the only thing remaining in this tutorial is building the web panel to send push notification. So lets build it. I am using PHP and WAMP Server for this.
Web Panel for Our Android Push Notification using GCM
- Open wamp server and go to root directory (You can also use other servers), in my case it is C:/wamp/www.
- Create a new folder here (I created GCM).
- Create a form here to send the push notification. So for the form create a file named index.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<!DOCTYPE html> <html> <head> <title>Android Push Notification using GCM</title> </head> <body> <h1>Android Push Notification using GCM</h1> <form method='post' action='send.php'> <input type='text' name='apikey' placeholder='Enter API Key' /> <input type='text' name='regtoken' placeholder='Enter Device Registration Token' /> <textarea name='message' placeholder='Enter a message'></textarea> <button>Send Notification</button> </form> <p> <?php //if success request came displaying success message if(isset($_REQUEST['success'])){ echo "<strong>Cool!</strong> Message sent successfully check your device..."; } //if failure request came displaying failure message if(isset($_REQUEST['failure'])){ echo "<strong>Oops!</strong> Could not send message check API Key and Token..."; } ?> </p> <div>Total Views <br /><span><?php echo $count; ?></span></div> <footer> Copyright 2016 © All Rights Reserved to <a href='https://www.simplifiedcoding.net'>Simplified Coding</a> </footer> </body> </html> |
- The output of the above code will look like.
- If it is looking very ugly then apply CSS to make it look cool, the same as I have done in my web panel. 😛
- Now create a php file named send.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<?php //Checking http request we are using post here if($_SERVER['REQUEST_METHOD']=='POST'){ //Getting api key $api_key = $_POST['apikey']; //Getting registration token we have to make it as array $reg_token = array($_POST['regtoken']); //Getting the message $message = $_POST['message']; //Creating a message array $msg = array ( 'message' => $message, 'title' => 'Message from Simplified Coding', 'subtitle' => 'Android Push Notification using GCM Demo', 'tickerText' => 'Ticker text here...Ticker text here...Ticker text here', 'vibrate' => 1, 'sound' => 1, 'largeIcon' => 'large_icon', 'smallIcon' => 'small_icon' ); //Creating a new array fileds and adding the msg array and registration token array here $fields = array ( 'registration_ids' => $reg_token, 'data' => $msg ); //Adding the api key in one more array header $headers = array ( 'Authorization: key=' . $api_key, 'Content-Type: application/json' ); //Using curl to perform http request $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) ); //Getting the result $result = curl_exec($ch ); curl_close( $ch ); //Decoding json from result $res = json_decode($result); //Getting value from success $flag = $res->success; //if success is 1 means message is sent if($flag == 1){ //Redirecting back to our form with a request success header('Location: index.php?success'); }else{ //Redirecting back to our form with a request failure header('Location: index.php?failure'); } } |
- Thats it now you can use your web panel to send push notification to your android application.
- Though if you are still confused 😛 you can download my source code from below.
Majority of peoples find difficult to implement Android Push Notification using GCM. Please give your feedback about this tutorial. I want to know whether this post made integrating Android Push Notification using GCM easier or not.
I have tried my best to simplify this tutorial as much as I can. If you are still having trouble you can ask by comments. Thank You 🙂
How to unregister while logout
Hi I am getting this exception:
E/AndroidRuntime: FATAL EXCEPTION: IntentService[]
Process: com.cogentec.m.androidgcm, PID: 26829
java.lang.IncompatibleClassChangeError: The method ‘java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)’ was expected to be of type virtual but instead was found to be of type direct (declaration of ‘com.google.android.gms.iid.zzd’ appears in /data/data/com.cogentec.m.androidgcm/files/instant-run/dex/slice-com.google.android.gms-play-services-gcm-8.3.0_db59c06674daea6c0c3eaf5ead4da580c37597bf-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.cogentec.m.androidgcm.GCMRegistrationIntentService.registerGCM(GCMRegistrationIntentService.java:45)
at com.cogentec.m.androidgcm.GCMRegistrationIntentService.onHandleIntent(GCMRegistrationIntentService.java:32)
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)
Please can anyone encounter this problem.
First time I didnt get Registration token. after removing android:enabled=”false” in manifest file i am getting this error
Nice tuto
thnk u so much god bless u ,
belal my server side code of index .php send.php are not working every time i got a message like Oops! Could not send message check API Key and Token.. even if i used same api key and sender id into ur defined template its working fine
May be u r using my json configuration file.. do check that you have pasted your own json configuration file or not
hi Belal When i send data from index to send.php data are not received in send.php part could u tell me whats the prolem,even i have used same code still getting problem.
Thanks
i am getting same problem as @nilesh and i have pasted the json file which i got from google,
Have you tried with my admin panel??
yes sir.
So is it working or not?
yes
above comment was by mistake.soryy sir it’s not working in my case
I have solved the problem ,actually facing trouble in my server side where some function were blocking index.php..
Thank you,
Update this line.. it will work
curl_setopt( $ch,CURLOPT_URL, ‘https://gcm-http.googleapis.com/gcm/send’ );
Excellent tutorial ,one of the most straight forward on the sublect I have found.
Everting went well till the point of sending a message.Using ur webpage for it .It said the message was successfully sent but It never arrived at phone.
Check the registration token
Excellent tutorial.One issue , it all went well until I sent a message from the link , it said the message was successfully sent but no message arrived at the phone.
??
Hi Thanks for this tutorial!
but, Do you support this push features in the language is English only?
Are there any messages can appear in Korean?
English messages appear well.. Help me..
Waiting for this tutorial since 2 months thank you so much
hello Belal,
thanks for your tutorial.
i got a problem here,
after running the app from android, there’s eror message “GCM registration error”
pls help me
Thank you so much .. it’s work good and easy to understand ..
I will try to save taken ID to database for sending many users ..
thanks again ..
Hi, Nice Tutorial. I redirected by your comment from the tutorial http://www.androidwarriors.com/2015/10/push-notification-using-gcm-in-android.html. If a user uninstalls his app and re-installs it again, then could we get a new registration token id?
Hi, tanks for this great tutorial!
Is there a way to send a message to all registered devices instead of one by one?
YOu should check this tutorial
https://www.simplifiedcoding.net/google-cloud-messaging-tutorial-android-application/
Hello Belal,
Thank you So much . but one issue is there..
there is three devices are there..two devices are API level 16 and one is 21 API level.
ISSUE : in API 16 if this Application is not running then also NOTIFICATION comes….means if i am sending from Browser.. but in API 21 if application is running than and only than Notification is comes/Appears,
Hey , great tutorial , but I have an issue.Everting works great , but the messages are nit arriving to the phone?
Hi Belal.. It´s great. !!! works perfect.. !!!
I´m using my own index.php and all is ok.
Thanks very much..
I will test second part
Marcelo
Excellent Tutorial.But what should we do if we want to read the notification on clicking it?
also how to add multiline messsage?
Asslamualikm Bilal thank you so much for the code (it is where i needed help most).
To everyone who is having a hard time making the code work , read the theory first so you will know what’s happening and where it went wrong: https://developers.google.com/cloud-messaging/gcm#arch
For those who did not receive the msg on their phone make sure you are using you Server Key when you send the notification from the web browser.
Make sure you clean and/or rebuild your android application after you add the code and also Sync project with gradle (after I did that I received the msg)
Take a look at https://www.simplifiedcoding.net/google-cloud-messaging-tutorial-android-application/
Here is all the project.. and when you clik over a notification you will see the url you set at
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(“http://www.your domanin.com”));
Please explain this row in manifest file:
will this code send push to more than 1500 devices?
Just Amazing Bro! I did it, I will continue doing more practices, you are doing it great.
Perfect.
Thank You Bro.
Hello Sir, the code worked just fine for me. A lot of thanks for this tutorial. But can you tell me something? Suppose my internet connection is off and a push notification is sent. When it is not showing when I switch on my Internet connection? And after enabling my internet connection when I am sending another notification then the previous one coming first and the 2nd one follows. Can this problem be resolved? When I switch on the internet can I get the notifications that are pending? If so let me know How..?
Hey please reply…. need to know the push notification is not coming when the app is not open. its only showing when the app is in background or it is running. Can you tell me why it is? and there is any solution for this or not. just let me know.
Great tutorial, but im getting an error on the app im developing. One of my activities implements a google map, so i had to add ‘compile ‘com.google.android.gms:play-services:8.4.0’ and for using GMC i add compile ‘com.google.android.gms:play-services-gcm:8.3.0’, and apply plugin: ‘com.google.gms.google-services’ and that throws me the error:
“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 help me with this issue?
how to insert the token number in a database…. 🙂
https://www.simplifiedcoding.net/google-cloud-messaging-tutorial-android-application/
I converted mobile site into app and its working fine. I introduce click to call features its working on mobile site but not
working on converted app can anyone help me out
where i find Device REGISTRATION TOKEN when we do live on google app
Excellent tutorial! Very very very well done man! Keep up the good work. You made us all saved so much time! lol
how to make the apps running in background so that it can receive notification although being force closed by the phone?
Error:Error: File path too long on Windows, keep below 240 characters : C:\Users\Bernard\Downloads\Compressed\send-push-notification-to-multiple-device-using-gcm-master\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.3.0\res\drawable-xhdpi-v4\abc_textfield_search_default_mtrl_alpha.9.png
Can you help me with this issue?
Store your project on any other drive like paste it inside only d: and open.. or you can also change project name to a shorter one and try (y)
plz send me server side code in asp .net instead of php. thank you
Fatal error: Call to a member function fetch() on a non-object in /home/u390405250/public_html/sendNotification.php
on line 11
i am getting the above error when i am hosting in my web server hostinger
Try using the web panel I have given you to test the push notification.. (y)
Hi Friend,
i got a problem here,
after running the app from android, there’s error message “GCM registration error” and it does not show token
how to resolve that problem.
Belam plz help me if i run on mobile how i find registration key
Hi,
thank you for your code!!! I’d like to start an alarm on loop mode after receiving a notification until user clicks on a button. Can you help me?
App doesnt received any message if the app is close.
Everything works fine but when the App is close it doesnt receive any message
Hi,
In my app, i have to use push notifications in some cases. Can i get acknowledgment or confirmation of delivery to device messaging to my web app server? Because i need to do some work based on delivery receipt of the push notification. If not then what is the remedy?
those the app wakes when a notification is received?
Hai
Nice tutor and thank you for the tutor.
I wanna ask how to put sound in notification?
Everything is work unless sound.
Thank You
Nice Tutorial.
First ill start off saying that this is the best tutorial i have used for android learning and i have gone far and wide trying to find something. Thank you for your work. Everything worked GREAT except the last step when i copied the code for the send.php file. i copied it and saved it to the correct directory and when i go the the send.php file in my browser nothing comes up. just a blank page. I restarted my apache server and still nothing. Any ideas would be great! Thanks.
How can I send notification in bulk to all the devices that are using my app
Hi Belal,
The Tutorial is very good…. It works like a charm for me….I just wanted to know that how can i implemented the chat using GSM…Hope to get a reply from you…
cool! its working..
When i send a notification from the panel in my device,
my app forced close !!
Do someone no why?
Nice code Belal. Thank you so much.
But cant receive the notification after killing my app.
It will gives the following error
W/GCM-DMM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE pkg=com.cabipool (has extras) }
I had added the Activity.RESULT_OK but not works please help me
I’m having this problem also, have you solved it?
where u used gcm api and sender id? please tell me i didn’t understand
It is used on sending push notification.. see the web panel there you need to enter api key to send push notification..
hi.. how to broadcast to many tokens with this toturial, thanks
can you help me
I want to send to all rows in column in the table token tokens that I have created
$tampiltoken=mysqli_query($con,”SELECT token FROM token”);
$rt=mysqli_fetch_array($tampiltoken);
$reg_token = array($rt[‘token’]);
thanks
Hi Good day, this tutorial was Great but i have some issue. I try to use your web panel to try the push notification the panel say’s its success to send but no one show notification in my emulator . . I think the problem is on emulator?
I also double check the api key and it is ok . .it is the same that I attach on your web panel
Thanks Very good tutorial
how i can store the device id or token to mysql database… and if possible post some example that how to send push notification to all registered users….
I already given the link to this tutorial in the beginning of the post
https://www.simplifiedcoding.net/google-cloud-messaging-tutorial-android-application/
Follow this to get your answer
thanks for this great tutorial!
but i have error in gradle
(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.)
Hello Belal,
Thanks for your effort .
i was using Pars.com to push notification but as you know it is not helpfull anymore , so how can i use this tutorial by push notification by User ID .
Thanks.
Instructor Belal, you are a wonderful instructor, i have read through your tutorial code and it is wonderfully stated, letter on i started working with the code but my challenges now is this object called “InstanceID”, my android studio can’t recognize it and i’m running android studio 1.5.1, what do i do to solve this problem please?
Dear Belal,
I am implementing Push notification for Multiple devices. I am following full your code. While registering the device name and email id is inserting and token is not inserting. Can you please tell me what is the problem
heyy i have tried this everything is going right ..but app is not giving any toast message of token
My first ever tutorial that run without an error. This is really great one.
hi sir
code run ok
but token key very large some change the token key short
given ieda
Excellent tutorial.. Thank You.
Hi,Awesome tutorial…..great help…Thankyou so much
I want to send notification whenever my table to get new data? if its possible
i have tried your code…it worked smoothly,i wanted to know how i can expand the “Push Notification” so that we can have a big view of info.
what i’m saying is how i can expand the notifiation recieved by pressing it and dragging down.like we can see in some applications.Please reply or mail me.
It is great tutorial .
But i want to know , which step justifies that token sent to 3rd party server .
Please let me know .
Hi bro,nice tutorial.But i want to send the push notification to all user( those who are use the app) without receiver user id.This is possible or not.
Hi,nice tutorial.I want to send the push notification to all user.(Only app user,not registered user ).this is possible or not.
Please reply or mail me.
Thanks man,it really worked
Great Tutorial,
I want to ask 1 thing, my api server key in google developers console is different from the current key defined in google-services.json file which i have downloaded. Please clear me this thing.
i downloaded source code but it shows hello world application only.
please help me
really usefull tutorial but for me token number is not generating in logcat
can u tell me how to solve this problem?
really useful tutorial …but token number is not generating in logcat
can u tell me how to solve this problem?
Code work but push not received when screen is off, (android lollipop 5.0/5.1).
Help please
I think u have to be give App wake up permission in Androidmanifest…
Thank you extremely much mannnnnnnnnnnnnnnn God blesss you!!!!!
Hello Belal Khan
Thank you for learn.
after run app crash application and this error.
FATAL EXCEPTION: IntentService[]
Process:package, PID: 17524
java.lang.IncompatibleClassChangeError: The method ‘java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)’ was expected to be of type virtual but instead was found to be of type direct (declaration of ‘com.google.android.gms.iid.zzd’ appears in /data/data/yadbegir.jfa.mansoor.com.yadbegir/files/instant-run/dex/slice-realm-optional-api_82aa9dab5d973e04cc1850ef40d4e3808a75f9c1-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 package.service.GCMRegistrationIntentService.registerGCM(GCMRegistrationIntentService.java:33)
at package.service.GCMRegistrationIntentService.onHandleIntent(GCMRegistrationIntentService.java:25)
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)
please help.
Hi Belal Khan,
I have implemented notification code in my project with your reference code and working well but when app is not running then not getting any notification.
So please could you suggest what should I do?
Hello Mahendra,
I am also getting same problem. When app in foreground or in background i receives notifications but if i remove app from background means totally from “Recent app tray” then i cant receive anything.
I also want solution on it. Please tell me if u get any solution.
I got the same error. Please help me if u solved it. Thanks in Advance.
Nice man it worked one time as opposed to other tutorials.But i have some FAQs?
1.If the registration token changes when my phone is offline, how do I handle that using your code considering that the token has to be stored in my users table in a remote MySQL and that I have to open the app to note the changes in the token, and a change in it means my messages wont get to my users?
Getting notification through your web panel…
But when i try to send the same using my web panel ,it gives an error message saying – “Oops! Could not send message check API Key and Token.”
Please help !!
please send me server code of yours..
Are you maintaining a database to hold API_key and reg_id??
Issue Solved 🙂
Tip :- **Dont use free webhosting sites for GCM**
They have limited functionalities
Hi bro,
i have passed the all details correctly but its not working, below is my code,please adivise me if am wrong
‘jkk’,
‘title’ => ‘Message from Simplified Coding’,
‘subtitle’ => ‘Android Push Notification using GCM Demo’,
‘tickerText’ => ‘Ticker text here…Ticker text here…Ticker text here’,
‘vibrate’ => 1,
‘sound’ => 1,
‘largeIcon’ => ‘large_icon’,
‘smallIcon’ => ‘small_icon’
);
//Creating a new array fileds and adding the msg array and registration token array here
$fields = array
(
‘registration_ids’ => $reg_token,
‘data’ => $msg
);
//Adding the api key in one more array header
$headers = array
(
‘Authorization: key=’ . $api_key,
‘Content-Type: application/json’
);
//Using curl to perform http request
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, ‘https://android.googleapis.com/gcm/send’ );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
//Getting the result
$result = curl_exec($ch );
curl_close( $ch );
//Decoding json from result
$res = json_decode($result);
//Getting value from success
$flag = $res->success;
//if success is 1 means message is sent
if($flag == 1){
//Redirecting back to our form with a request success
header(‘Location: index.php?success’);
}else{
//Redirecting back to our form with a request failure
header(‘Location: index.php?failure’);
}
Thanks for the tutorial but my app the first demo crashed when I just launch it pliz I need your help, thanks at first they were bringing an error on mRegistrationReciever in the on pause and on resume in main activity,
Thank you for the tutorial but i have a problem, when i try to open my app it crushes as it launches what could be the problem
This is the BEST GCM tutorials. Everyone I recommend this one. Thank you so much. I referred lots of You tube video tutorials and dozens of other web tutorials. But none was helping. Only your one able to help me and resolved all of my issues. And thanks lot for the php side code. Most of them do not include it. God Bless you for sharing your knowledge among dummies like us. I wish you all the best. Keep up the good thing. May you get more knowledge and good health.
Awesome clarification on GCM… Thank You
Hello Belal Khan
Thank you for learn.
after run app crash application and this error.
FATAL EXCEPTION: IntentService[]
Process:package, PID: 17524
java.lang.IncompatibleClassChangeError: The method ‘java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)’ was expected to be of type virtual but instead was found to be of type direct (declaration of ‘com.google.android.gms.iid.zzd’ appears in /data/data/yadbegir.jfa.mansoor.com.yadbegir/files/instant-run/dex/slice-realm-optional-api_82aa9dab5d973e04cc1850ef40d4e3808a75f9c1-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 package.service.GCMRegistrationIntentService.registerGCM(GCMRegistrationIntentService.java:33)
at package.service.GCMRegistrationIntentService.onHandleIntent(GCMRegistrationIntentService.java:25)
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)
please help.
Add Below code in Application build.gradle.
configurations.all {
resolutionStrategy {
force ‘com.android.support:design:23.4.0’
force ‘com.android.support:support-v4:23.4.0’
force ‘com.android.support:appcompat-v7:23.4.0’
}
}
This is Awesome. Thanks man
hii belal its a nice tutorial.its working fine but when i switched off my phone and then restart it again Notifications are not received.Please help me how can i resolve that issue
how i can send notification on more then 1000 devices ,as by gcm we can send notification to only 1000 devices at a time.I know i should distribute reg token in array of 1000 so if more then 1000 token are generated they get stored in new array n should use the array seperately to send notification…
pls send me some code as i don’t know php much
thankyou
Hi belal,
Thanks for the post. I am new to android, i followed your code after lunching the app i got this error
E/AndroidRuntime: FATAL EXCEPTION: IntentService[]
Process: com.example.arun.gcmexample, PID: 2948
java.lang.IncompatibleClassChangeError: The method ‘java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)’ was expected to be of type virtual but instead was found to be of type direct (declaration of ‘com.google.android.gms.iid.zzd’ appears in /data/data/com.example.arun.gcmexample/files/instant-run/dex/slice-com.google.android.gms-play-services-gcm-8.3.0_a7beddb01ea4b1c76f48b11827ce39187995b723-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.example.arun.gcmexample.GCMRegistrationIntentService.registerGCM(GCMRegistrationIntentService.java:43)
at com.example.arun.gcmexample.GCMRegistrationIntentService.onHandleIntent(GCMRegistrationIntentService.java:31)
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)
Plz, give the solution for this. Thanks in advance…
I found the solution for above issues, well Nilesh given the solution. That the same code i used in my app.
Some of the used plugins use these libraries as well and the conflict was in the usage of different versions of these libraries. I solved this issue by using the force command inside the application gradle (see below):
configurations.all {
resolutionStrategy {
force ‘com.android.support:design:23.4.0’
force ‘com.android.support:support-v4:23.4.0’
force ‘com.android.support:appcompat-v7:23.4.0’
}
}
I am getting exception on these two lines please check
GCMRegistrationIntentService.registerGCM(GCMRegistrationIntentService.java:40)
GCMRegistrationIntentService.onHandleIntent(GCMRegistrationIntentService.java:28)
Thanks.
hi Bellal
Your link to GET A CONFIGURATION FILE has changed . I did not find the button GET A CONFIGURATION FILE.
Hi,
Its a great tutorial.
I am able to receive messages from GCM server when data data is send from link mentioned above: https://www.internetfaqs.net/sc/gcm/”
But when i try to send a message from an app server i wrote in c#, i can’s send the message.
Response status is “OK”. But Response body has message:
“You have browsed from an unrecognized IP address. The proxy therefore denied access to this site or page:”
Can you please help me on how to resolve this error to send a message.
title not show ?
Hi Belal,
I think we need to amend the above code like below, isn’t it?
Please explain if not.
Oh wow i executed it in first attempt. ThanQ Belal for this tutorials.
how to disable push notif if app is running, please help.
Hi
I tried the tutorial, and I keep getting a message stating that I should check my API key or Token, but I checked it on a service is made, and it worked, but without the payload. Could you advice?
Hi Belal,
Best Notification Service?
GCM or FCM
my server side code of index .php send.php are not working every time i got a message like Oops! Could not send message check API Key and Token.. even if i used same api key …please help me sir
Hi. I’m trying to develop an emergency app that allow you to send sos message to 5 number from your contact list. I also want to implement shake function so when the user shake their device the app will automatically send sos message to the number that they choose. Can you help me with the coding? I’m so desperate I can pay someone to actually makes this happen lol
Hi belal or anyone please tell when the token will change ,In above code GCMTokenRefreshListenerService is there ,where it will call and when we need to use.Overall the tutorial is cool and good
Hello Sir..
One issue is there.
I use this link to send notification
https://www.internetfaqs.net/sc/gcm/index.php
Fill all the fields then it shows the message
Cool! Message sent successfully check your device…
But..
My device not received any Notification.
Please Help Me..
Thank You..
Hii Belal,
GCM Is Deprecated Soo Can You POST The Code About How To Send Notification With FCM.
Thanks In Advanced
Hii Belal
GCM is Depreacted By google soo can you Post Code about android push notification using FCM
Thanks
I use c# instead of php. sir please tell me how to write gcm code in c# as like php to run notification
Hello,
I am facing an app crash with the error as “java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean .androidgcm.helper.AppController.isLoggedIn()’ on a null object reference”.
Please help!!
Thanks in Advance 🙂
I’ve tried this tutorial on my app and it doesn’t seem to work. It shows the error of “Oops! Could not send message check API Key and Token…” . All I want to know is does this tutorial still work for GCM now or does it need any changes now since it’s already 2017 and GCM might have gone through changes that might affect how this code is written.
Thanks.
it showing me a toast …
Google play service is not installed/enabled in this device
but i have already done this
It giving error
E/FirebaseInstanceId: Failed to resolve target intent service, skipping classname enforcement
E/FirebaseInstanceId: Error while delivering the message: ServiceIntent not found.
I dont know why “Firebase” is there Im trying to use GCM…
I added following in Manifest till its giving such error
Please help me out..
Thanks
I did all things right , but i am not getting the token..
anyone there to help please guide me i am doing this from last 3 days but from this tutorial i can’t get the token
Use the updated firebase cloud messaging tutorial instead
How to send same to message to multiple devices? Can u please provide some information on this..
When i am trying to send a notification fro the web panel it give me this Error :: Oops! Could not send message check API Key and Token.. , But i am giving the correct token and API Key can u please help
Hello Belal,
Using GCM can we send push notification to another device.