Android Push Notifications using Firebase Cloud Messaging FCM & PHP

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

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

1. Firebase Message types

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

1.1 Notification Message:

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

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

1.2 Data Message:

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

1.3 Messages with both notification and data payload:

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

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

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

2.2 Topic Messaging

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

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

3. Integrating Firebase Cloud Messaging

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Subscribing to Topic

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

FirebaseMessaging.getInstance().subscribeToTopic('news');

Unsubscribing from Topic

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

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

4. Sending Messages from Firebase Console

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

5. Sending Messages from PHP Backend

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

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

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

6. Demo

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

Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info

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

mikrosmile

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

Guest

Hey,

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

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

draffo3

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

xavi!

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

Ignacio

Hi Ravi,

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

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

Elie GAKUBA

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

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

Any help would be much appreciated,

Thank you 🙂

Raj

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

Anyone know wot the issue might me?

Raj

Got it fully, thanks again Ravi for the code and tutorial u’ve provided here. 😀

android_cro

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

Raj

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

VDev

Hi Ravi,

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

Fresher

Can u please implement the server side programing in java?

Amol

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

HM

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

Amol

i am getting force close error

and i have no idea why ???

krishna

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

Unauthorized
Error 401

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

Hasan

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

kwishnu

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

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

Ivan

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

Please help.. thanks in advance.

jean

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

Kash

Brilliant… Thanks

dashing

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

oth

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

Arief Abdul Aziz

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

AbelardoLG

Hi dashing,

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

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

Thamilvanan Go

Hi Ravi,

Am having problem with getting push notification:

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

Pratyush

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

Nadeem Khan

Thank you very much….

andy

This tutorial is awesome. Thanks!!

Cesar

did u get some response? im totally clueless about this

KashifB

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

jean

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

Victor

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

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

I am a bit hopeless. Can anyone help us?

mrhungonline

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

joker

yes .. me to sir

rendy

how to connecting?

BaiKin

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

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

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

BaiKin

Hi Ravi,

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

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

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

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

Fabse

Hi,

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

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

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

Thank you!

BaiKin

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

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

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

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

and add this line right after it:

notificationIntent.putExtra(“message”, message);

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

messageTextView = (TextView) findViewById(R.id.text_view_message);

and add this line right after it:

messageTextView.setText(i.getStringExtra(“message”);

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

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

Fabse

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

Thank you!

Fabse

Did somebody solve this problem?
I still have it 🙁

Alessandro Universus

I have your same problem…

Fabse

Could you solve it?

Guest

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

So please help out me…

Piyush Gupta

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

So please help out me…

khaled al

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

thanks in advance.

tjvanderende

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

Please someone post the code here.

gowtham

I too have the same Problem Please help me !

gowtham

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

Gowtham

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

gowtham

Am also having the Same Error …Please help me too

Chandan

Hi Ravi,

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

Please help me with this.

Thanks,

Chandan

Gobinath

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

Tobbbe

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

Ram

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

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

villarino

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

How I fix this problem?

Thanks

pablo

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

pablo

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

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

Steven

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

Steven

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

ask

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

Kaka

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

Jaya Prakash

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

Many thanks in advance.

Claudio Suriano

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

Claudio Suriano

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

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

Claudio Suriano

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

Anas Azeem

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

Jaya Prakash

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

François

Hi Ravi,

Thank you very much for your tutorial, it’s really helping 🙂

Jaya Prakash

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

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

Khalid

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

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

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

dragnovich

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

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

Thushara

Hi Ravi ,

Thank you soo much..Very helpful tutorial.

Thushara

Karthik

Hi Ravi,

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

Thank You,
Karthik.G

kryton

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

四維 包

change…

$fields = array(

‘registration_ids’ => $registration_ids,

‘data’ => $message,

);

to…

$fields = array(

‘registration_ids’ => $registration_ids,

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

);

done…

isiah

what fixed this codes?

isiah

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

can you help me solved this error?

isiah

Hey did you solved this problem yet?

isiah

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

frans.yunet

dear ravi

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

2. and how to re-registered deviced again ?

tks

Kent

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

francois

You juste have to put your mail and after it’s funny.
Thanks Ravi for this tuto 🙂

jawad ibrahim

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

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

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

Mickey

It work perfectly

Manoj

Hi Ravi,

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

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

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

Rikhil Jain

Hello Sir,

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

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

Joannes A. Rommers

Did you find an answer to this?

Henry

Hi Ravi,

Great Tutorial.

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

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

Thanks a lot …

Soubhab

One of the best tutorial ..

Thanks once again ….

Charbel Sarkis

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

GreatCoder

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

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

harsh

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

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

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

Aditya

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

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

@Ravi : Please Help

Hector

Hello!

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

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

I hope you can help me. 😉

Richie Q. Grabner

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

Thx

Richard

Marc

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

pawan

Hi Ravi,

Thanks a lot Pawan

Amr

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

Amr

Hi Ravi,

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

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

Paula

Hi Ravi,

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

I’m trying your code in Android Studio but I have an error: Gradle: error: package com.google.android.gcm does not exist

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

Thanks

Paula

Marc

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

Basel

Hey Ravi,

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

Regards,
Basel

Onest

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

Kath

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

saab

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

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

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

Thanks

Jonathan

Harpreet Sardar

Did any one solve this problem, Please advice

Harpreet Sardar

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

arief abdul aziz

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

Federico Boesche

Thanks Ravi.. usefull and great tutorial!

Stephen Sugrue

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

arief abdul aziz

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

Glory

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

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

Gaurav Singh

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

abhay

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

Patrick

Hi Ravi!

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

if you have any moment, please take a look at here ravi “http://developer.android.com/google/gcm/c2dm.html” , it says that our latest C2DM
“will accept no new user” and “C2DM developers are strongly encouraged to move to Google Cloud Messaging (GCM)” that’s why i’m asking you for the newest tutorial thanks ravi 🙂

ankita

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

kaushik patel

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

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

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

Rohit Behl

How to work with SQL SERVER? any suggestion

Guest

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

Mattia Adducchio

Hello,

first of all: Thanks a lot!

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

Best regards,
Mattia

Eaiman Shoshi

Hello,

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

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

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

LoungeKatt

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

Glory

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

any one can fix it???

Guest

Check my comment for an updated and more efficient version of the code 😉

Glory

Where???
link or site please….

Steve Rodger

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

Noor Fadhilah

Hi Ravi,

Thanks a lot.

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

Thank you.

Noor

Hi Ravi,

Thanks a lot.

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

Thank you.

Saad Bn Muaz

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

Moustafa Ashmawy

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

Valerio

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

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

Thank’s a lot 😀

Danny

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

Liron Vaizer

hi!

thanks!!! it is a greate tutorial!

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

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

Alessandro Universus

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

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

Alessandro Universus

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

Alessandro Universus

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

Pedro

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

yourkishore

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

Nazeerahmed

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

Pobo

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

Candy Wijaya

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

bharath

hey not working for me

adhadimas91

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

usman khan

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

Regards,

adhadimas91

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

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

semi

thank you very match

Deepak Singh

Hi ravi,

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

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

Your help will be appreciated.

Thanks
Deepak singh

Rajnish

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

siddhesh morye

Hi Ravi ,

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

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

Omar

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

Kaylee

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

omar

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

Kaylee

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

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

Omar

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

Omar

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

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

Matteo Valenza

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

Matteo Valenza

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

generateNotification(context, message);

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

Sorry for my silly question 🙂

Steve Rodger

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

Pravin Patil

Hi Ravi,

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

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

Omar

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

eugenevdm

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

Omar

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

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

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

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

Tasos

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

eugenevdm

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

FiL0

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

jy

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

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

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

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

Omar

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

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

Aguirre

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

king

Thanks Ravi, great tutorials.

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

nishal

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

Omar

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

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

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

$users=$db->getAllGCMUsers();

if ($users != false)

$no_of_users = mysqli_num_rows($users);

else

$no_of_users = 0;

if ($no_of_users > 0) {

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

$ID=$row[“id”];

$empid=$row[“emp_id”];

$regId=$row[“gcm_regid”];

}

}

$gcm = new GCM();

$registatoin_ids = array($regId);

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

print_r($registatoin_ids);

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

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

nishal

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

Omar

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

else

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

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

But thanks for getting me started with GCM.

Kiko Rico

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

Joannes A. Rommers

Have you find a solutions for this?

Dev

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

Khushboo Mehta

Any updates on this question

geka

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

Anilton Fernandes

Please, help me with this issues on WakeLocker.java

PowerManager.WakeLock wakeLock;
acquire(Context):void
release():void

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

eugenevdm

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

Marc

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

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

Guest

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

Vaibhav

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

We will be thankful to you.

FYP Project

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

Fabse

I have the somae Problem, could anybody fix it?

Ali

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

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

I hope to help me in this problem

Thank you

Vaibhav

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

Smit Patel

but for the server?

Vaibhav

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

Smit Patel

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

Vaibhav

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

Smit Patel

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

Vaibhav

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

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

Hope2Help

Can you post the error response from logcat?

Daryl

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

lakhwinder singh

some things happen to me

Hope2Help

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

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

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

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

Guest

Unauthorized

Unauthorized
Error 401

Hope2Help

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

lakhwinder singh

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

Ninjahitam

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

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

Vivek

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

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

Ivan

Somebody can send a working code (google_play_services) to me on allsystop@gmail.com? I will be very grateful!

Vivek Ravi

This is may be n/w problem.

Ivan

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

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

Israel

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

Israel

Is there any way to run it on a mobile?

Ivan

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

Namdev Londhe

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

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

mitsus

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

Thanks a lot

ABY MATHEW

I have hosted the php files on my serve.
When testing with test.php
I am getting this
{“multicast_id”:8505446966783816304,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}

What is the problem?

TomChen

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

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

Amit Gahlot

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

Prashasya Choudhary

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

sushant

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

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

Shubham Singh

i did, app starts on the device and “trying to register” happens for 5 times but it doesnt registers. and test.php returns multicast that many people have commented
{“multicast_id”:9032333512512220474,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}

Shubham Singh

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

nasznjoka

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

zheguo wo

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

Unauthorized

Unauthorized
Error 401

how to do ?
please help me.

4droid_Learner

You need to get a browser key from cloud.google.com/console !! An API Key will not work!

4droid_Learner

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

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

Aung Tun Kyaw

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

Rakesh

not solved by using this

sri

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

can any body help me please it is very urgent.

asaf

Hello, i had same prablom.

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

“http:///phpServer/register.php”

sri

i have placed PHP file under WAMPWWWGCM_SERVER_FILES*.php

sweety

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

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

Ronak Thacker

just edit this file then all code working fine….

NOTE :

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

Nik Muhammad Amin Nik Muhammad

i tried you way but seems not working

Vanraj

I Could’t Register dont know whats the matter

SengHyun lee

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

anil patel

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

Bimal chawla

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

Anubhav

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

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

Cheer 🙂

moataz

hey plz can you send me test.php to (mutaz.ghanem@gmail.com) i downloaded code but nothing sent to my email thanks 🙂

ramabu Mahopo

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

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

Ritesh

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

Vasudev Vyas

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

Vlado Mihaylov

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

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

Aung Tun Kyaw

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

Vasudev Vyas

Thanx its done.

Vlado Mihaylov

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

Gyani

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

Mahdi Kenji

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

Joven

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

Mahdi Kenji

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

Joven

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

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

Nikhil Raj

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

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

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

daragon

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

bill

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

karpaga prasanna

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

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

sri

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

moataz

plz can you send it to (mutaz.ghanem@gmail.com) cuz i downloaded the code but i got nothing 🙂

vishnu

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

ranjith

me to have the same problem please help

ranjith

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

vishnu

thank you…

des

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

HQ

me too not able to get the message on device

dev

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

yo

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

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

Naceur Amir

Have you found a solution for this problem i am in your case please help
email : naceuramir@gmail.com

arash ataafarin

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

sumit

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

Mohammed alhammouri

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

Luis

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

sri

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

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

sat

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

bapu

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

riverspart

It woks! Thank you so much 🙂

raghave

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

ecki kawy

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

Mahdi

Hi,

Is it possible to use this feature for chatting?

DomenicoButtafarro

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

Guest

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

raghav

Hii ,

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

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

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

Sumit

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

3Arpit Sharma

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

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

nantha

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

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

sam

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

ahammed hafees

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

mohdkhalilsabba

add permission:

in your manifest

sam

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

Sukhjit

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

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

Guest

InvalidRegistration,

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

BTW the data save on MySQL perfectly.
please help

ibrahim disouki

where is this file test.php??

yuval

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

Masterwix

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

ibrahim disouki

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

and call the following lines code in private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() presents inMainActivity.java.
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());

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

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

ishwari

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

sushant singh

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

sushant singh

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

thanks

sushant singh

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

Nitesh Upadhyay

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

Mohamed Ismail

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

please help me

IrsHaD

same here help !

Jevon

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

Prashant Kumar Katariya

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

Jyothi Dadi

device successfully registered
But Message Not receiving on Device

can anyone please tell me

Bhupendra

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

you will get
Any IP allowed

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

azad

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

;extension=php_curl.dll

AGuismo

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

Jyothi Dadi

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

dhinesh5152

great great great great great…. working perfectly….

lesiaki

its give me a blank result

Nguyễn Đình Thảo

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

Elprogramador Incansable

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

Joombla

Things are deprecated in this tutorial. I hope Ravi can fix this. Thank you for this site Ravi 🙂

Asuej28

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

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

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

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

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

Duy Tran

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

Mamro Kirill

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

SELASSI ABDELLAH

Any tutorial link to the new method ?

Rakesh

during php execution it generates following errors
”

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

“

Naz

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

dsp

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

Ravi Ranjan Singh

Good tutorial. Very helpful 🙂

vishal gadhiya

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

Virender

Hi ravi sir

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

Please reply
Thanks

Nishu

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

BalintFarago

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

Naz

Thanks Ravi, these tutorials are a great help for us newbies! 🙂

Prash

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

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

Rakan

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

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

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

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

Amar Raj

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

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

Guest

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

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

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

Manoj Tiwari

Hi ,

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

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

akhil

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

Rainer Schleevoigt

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

J

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

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

Riya Dashoriya

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

Vineel Sadineni

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

arash ataafarin

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

and line 19 of “GCM.php” to this :
$url = ‘https://android.googleapis.com/gcm/send’;

Ravi please correct these lines.
Thanks

Taha

which line do you mean ?
line 19 is blank

Taha

ok i changed it to : $url = ‘https://android.googleapis.com/gcm/send’;

and i deleted this (url: “send_message.php”,)
is that true ?

arash ataafarin

you should change line 19 of GCM.php to $url = ‘https://android.googleapis.com/gcm/send’;

RB

you have to create a server key in order to recieve messages. P.S. a SERVER KEY is required.

arun

Is com.google.android.gcm.GCMBroadcastReceiver deprecated now?

abhinav

abhinav

Thankyou for the wonderful tutorial….

When I am trying to register via myserver/gcm_server_php/test.php with the three input values, then the– myserver/gcm_server_php/register.php says
{“multicast_id”:6156241302573131157,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}

but the values are added in the server database.

and When I am trying to register with my android phone with name and email address…then after clicking on Register button……It says ——>

hey plz can you send me test.php to (mutaz.ghanem@gmail.com) i downloaded it but nothing sent in my email

Amit Yadav

I got same Error as moataz..Plz help me

Alberto Gaudicos Jr

do you have updated tutorial about this? GCM is not located anymore at GCM but in Google Play Services already…

jrla

In android SDK Manager click Obsolote and GCM will Apear

Alberto Gaudicos Jr

i can’t locate GCMBaseIntentService and GCMRegistrar, i import google play services rather than GCM because it says deprecated and it already added at google play services. I need the updated tutorial, please update..

jigar

Hii Ravi Tamada… This is a very nice tutorial for newbies and it has worked on my app properly… just want to tell you that few steps are not specified in this tutorial… i would like you to specify them… like Whitelisting the server ip address, deploying the api key. etc… please also specify this steps..

Thanks for the tutorial

TB

On most devices this code has been working perfectly, but for some reason on one device I tested on it gave me a message:
“From GCM: error(AUTHENTICATION_FAILED)” and it doesn’t register the device on the database. I looked up the problem in Google’s GCM class and it seems to have something to do with an incorrect password for a google account on the device, which doesn’t make any sense because on all my other devices I can type anything into the “Email” field when registering on the home screen and it still registers fine.

Anyone else get this error?

ShivamDev

Can we have the same working with Java as I’m not comfortable with PHP.

How can i resolve this?There are many post regarding this but its not solved yet.please tell me anyone

Edu ECR

Hi, I got the same error a few days ago. It seems that the reg_id has to be made in the client side. If you try to prove adding an user only in the server side you will obtain this error.

So, this error is not important. Everything is OK. Later, if you implement the client side, you could check that the process works properly.

Ram

sir, i’m using WAMP server. and my device is registered successfully and also added to my server. but i’m unable to get the push messages from server to my device.
i had removed ; also from “php.ini” file .
and havn’t given any server address while generating API key. and tried to fix it a lot.. but i con’t. plz help me to fix it sir..

Ashu

Hey I am facing same prob let me know if you have got any solution.

ashu

I got the solution, I was creating android key in google console instead of browser key.. Possibly you are doing the same

Shubham Singh

did you got it working?

ROPK

sir, where is the GCM Registration ID from? it can be generated myself or it must be generated by Google?

Hi, Appreciated the tutorial, I have been prepared the setup and every thing went fine. Only one concern is that when I do register from the emulator, I didn’t see any message in the next activity as your device is registered. I have given server_url, and tried both browser key and server key in server side php code, database tables also prepared but no data is populated when I do register in the emulator. But I’m not sure why I couldn’t see the message in the screen after the registration step. Can any one suggest me in this regard.

Gelli Ravi Kumar

Finally, with some changes in the manifest file I achieved this. The registered device ID, name, email are stored in the database, and displayed in index.php too. But, when I enter a message and do click send button, my emulator is not receiving any notification. I’m not able to figure out how to resolve this ?

leonidas

i have the same problem as you , did u manage to fix it ?

Gelli Ravi Kumar

I have connected two real android mobiles such as 4.2.2 and 2.3.3 to the development IDE. From my PhP server, the push notifications are going well only to 4.2.2. but not for 2.3.3. Similarly two emulators of the same kind such as 4.2.2 and 2.3.3 are connected and tried to send notifications. But the emulators couldn’t received them. I’m not aware of why these all happening in a discriminatory way. I’m still try to figure out the technological edge of this problem, may be some expert like the author of the article in this field can give us better understanding.

leonidas

it doesn’t work for me too in both emulator and real device , still wondering where is the problem , may the author help us.

dev

Thanx Ravi..its working after so many attempts over some months…finally its working.
Tips:
1)Use server key
2)attach gcm.jar from extras->google folder
3)run config.php,db_connect.php and register.php before index.php page
4)sign-in with your genuine google account in settings->Account&Sync in emulator.
Once again
Thanx Ravi.. 🙂

Gelli Ravi Kumar

Hay dev, Good to hear that it is working nice. I’ve followed exactly all the above steps, and even I have also been attempted once with a Server Key and a Browser Key. My app is nicely working for Android 4.* series but come to the Android 2.* and 3.*, the push notification are not at all transferred. Can you share us your experience while facing problems, also on which android real phones, have you been tried out for successful push notifications.

it works well on local host but not on a 3rd party server. I am able to register my device on the that server but unable to send messages from it to registered devices anyone facing the same problem.

An

I think you have issue with url field in sendPushNotification(id) function.
In this tutorial is url: “send_message”,
Please debug network request when you click Send button.
If you use chrome, F12 select network, you will see the request when click send button.

Shubham Singh

thanks buddy for a quick reply. i am not sure how to see the request as you suggested but i am getting a response message as “Curl failed: Failed to connect to 2a00:1450:4001:c02::5f: Network is unreachable”

on localhost it works perfectly but on personal server user gets registered 5 times and mainactivity shows could not register on demo server…also notification thing is not working on personal server but working on localhost…… plz help…… Thanks

Shubham Singh

facing same issue

Shubham Singh

try abin’s solution it worked

Sachin Chandra

Hi all,
I am getting the below error in my local host.

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

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

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

Guest

hey plz anybody can send test.php to (mutaz.ghanem@gmail.com) , i downloded code but nothin sent to my email

Ashu

Dear Ravi, I tried all things of yours message is also coming but no notifications sound and no vibration happens. Phone is vibrating if any other notification comes but not on ur app. Please guide me for this

Dario Mirkovski

Dear All,

I had the same error of having problems with the notifications on the phone. However, I managed to fix in adding the following line in GCM.php:

Well, i guess GCMIntentService uses methods which are already depreciated. Do some research and see. For the notifications, please use the following web site to check if the GCM thing is working and if you set the proper values.

Insert the Project Code and the API KEY. If everything works, you should get an null message. Otherwise, check the tutorial and set the things i’ve mentioned.

MDO

WELL DONE
may god bless you for this great work
works fine
just for notice
every one should replace the server url with its own server ip !! how??
firstly you should get your machine ip from your cmd:
go to your cmd -> type “ipconfig”
then copy the IPV4 adress
for instance 192.xxx.x.x
then you should know the wamp server port in order to connect to register.php page
usually the wamp server port is 80
but in my case i changed to 8080
so the server url is going to be like this:
“http://192.xxx.x.x:8080/register.php”
good luck 😉

bhishm

sir , my device is registering on demo server but data is not saving on the server database….the total server side work is not working…plz help. thanks.

Sarini Tharindya

I think your database connection is not working..are you changed config.php??

bhishm

Thanx for replying Sarini. Yes i changed my all database detail in config.php but still my data is not going to my server database. Plz help??

so if my phone restart and application does not open yet, it possible retrieve push notification.

sorry for my bad english

ruby

hi everyone..
sorry for my broken english… i have few question…

1. at sdk manager..
it didnt show gcm unless i click obsolete.. then it will show gcm… its ok??? and my gcm installation are successful

2. i’ve stuck at avd manager… i can install it but when i try to register my email at ‘account & sync’ it show exchange email… how can i settle it?? because it show “setup could not finish. This server required security features your phone does not support”.. what should i fill in server???

Sarini Tharindya

create another AVD and Try it.

Sarini Tharindya

sir.. my app is working..but if Isend msg from server to device.msg not coming to device. can you help me??

ruby

Hi sarini… can you teach me how to register email on emulator? Do you have to register on exchange email?

Sarini Tharindya

please search in google “how to register email on emulator” and follw 4 th link from to Top. 😉

Sarini Tharindya

i sloved it.. i changed my api key as browser api key. thank lot.. very good tutorial. without any error..

FM

i have the same problem can u explain further

Sarini Tharindya

I think you use android key as your api key.. you should create browser key(not android key) in exsiting project , that means which is you used before to generate android key and again create browser key and used it.. 🙂

FM

Do you mean i have to use a browser key as my google api ?

Sarini Tharindya

yep.. 🙂

FM

i tried that it didn’t work. trust me.

Guest

Without details I can’t say any Thing. but i can sent my working project if u like.

Hello, can anyone help me how can i use cloud’s pop messages on my android device as a command to perform some action .for eg i want to put my phone on vibration mode through that pop message ..? how can i do that..much needed help asap..!! plz

SIVARAMAKRISHNAN .V

Hai Ravi..can we run this on real devices? I tried now but i am not getting the notification.please help me .

Shubham Singh

@ravi8x:disqus hi ravi, i noticed that in this tutorial and another tutorial( android-login-and-registration-with-php-mysql-and-sqlite) you use diffrent approaches to send data from device to server(registration) why so

Archana K C

Hi Ravi, i followed the same steps in both android as well a php, its working fine!! i am getting Notification message also.
But i face one major problem in displaying the message. when application is closed i receive the notification message but when i drag it, the contents will not be displayed. i am getting a blank page. How to get that particular activity when click of notification message.If that view is opened and a new message is sent then it will be shown on that view.

Kindly someone please let me know the solution….

Neeraj Gupta

I am not getting Notification in My Android Device. Is there any setting in PHP. I changed only in config file username,password,database name and API KEY. that it.

Anti Apps

I am not getting notification in My Android Device.

I Changed config.php file(PHP) and CommonUtilities.java(Android)

– config.php (Username,Password,Database & Google API Key)

– CommonUtilities.java (Server URL,Sender ID)

I am run application in android device and register with NAME & EMAIL. After getting message “From Demo Server : successfully added device!”

After this message i m go to the database n check table – One row inserted in table with same name and email (It means php connection working very well).

I am trying to send notification to registered user but not getting notification.

Please help me.

Saad Sheikh

Same Problem with me..

Ashutosh Tiwari

Any sol ?

ap

same problem with me…

ravindra

My device is not registered with demo server .How can do this….

Nathan

I don’t know if you guys are still having this problem, but it might be an issue with the API key? Make sure you have the right one, and that you have it set the API Access to ‘Any referer allowed’

SK Resat

m2 pls help …..

nikolay edison

Hi,
first of all thank you for this tutorial that saved my life.
What if i want to send a message from my device to another registered device?
Thanks in advance.

munam

anyone have this project in running condition.please can u sebd it to me…i tried but there is alot of errors in it..please if someone have gv it to me

saad sheikh

This is working properly dear..

Guest

Thanks for sharing Ravi Tamada very useful one.I got a following error:

Very nice tutorial. Too bad it breaks on Android Studio with the new GoogleCloudMessaging and the obsolescence of GCMBaseIntentService. Have you got an update tutorial taking advantage of that? I found little connections between the new library and the old solution you were so kind to offer a tutorial for.

Hmatyi

Hi! Your tutorial is very nice! 😀
Everything works well, but i have a question: how can i send a message to all registered users?
Sorry for my bad english!

fernando

I use a while in php , selecting all the registered ones

Alberto

Hi, how do you use the while? or where?

Hendi

give me a download link of your project, a project I can not send a notification to the client

Ved Pawar

Hi,Thanks for a nice tutorial.I want to know how can I send the user to different activities on notification click. Can I need to take some tag in the push notification message by which I can differentiate the message or any better option is there.

sarath kumar

thanks it works…but it delivers only internet connection is present in mobile,I want to hold the notification when in offline and after delivers the message when internet connect available..Is it possible???Thanks in advance to everyone

karlos

hi!i am having problem to import in android studio, is it compatible??

Ram

hi i am new to android programming i am trying to follow your tutorial but now the GUI of the Google APIs Console page changed when compared to the images so facing problem. any help in this regard

Abubaker

hi i am new in android i am trying to run following toturial but when i click on register button from my device a blank white page pop up and no device register in database please help me

Lord Thomas

Same problem here , successful registration to GCM but blank page and nothing written in DB. If i add everything by myself in DB den ok it can send message to device. What’s wrong?

joe

I suspect it may be your
SERVER_URL = “http://10.0.2.2/(your folder name)/register.php”;

I am using xampp localhost. so i just stuck with the default setting for SERVER_URL and it worked!

Loki

You could use your ip adress for the SERVER_URL string as your ip/gcm/register.db..That’s all. I run it successfully on the Genymotion emulator!

Alain Bonnefoy

Hello,
I tried to add several informations in the message I send vis send_notification($id,$msg), like that: $msg = array ( “siteName” => $_GET[“pushsitename”], “message” => $_GET[“pushmsg”], “webSite” => $_GET[“pushwebsite”], “date” => $_GET[“pushdate”]); But strangely when I call extras.getString(“message”) for example, the message is empty whereas other fileds are ok. Is there any limitation in the number of value pairs to send?

Alain Bonnefoy

I found the problem; I don’t know where the problem is exactly but any string containing character with accent is not transfered.

Abdul Rahman Majeed

I have set the respond time in database and want to get result from GCM at that time, how can i implement this ???

Pham Anh

i got an error “INVALID_SENDER” but i have entered correctly my project id. It is: focus-electeron-752. May you check for me?

On your developer dashboard you should find something like project id:focus-electeron-752 and project name: xxxxxxxxxx(JUST NUMBERS)

enter the project name because that one is the project id but google didnt notice they wrote them incorrectly

Laxman Singh

This is very nice tutorial all is working well i wanted to know that how to display gcm response
and how to deal with canonical ids for the multiple registration of same device .

Ravindra

Can you explain how gcm device registered in demo server..??

soRai

Hi at! I’ve got a lot of registration ID’s in my MYSQL Database. The Problem what i now have is, that we have TO MUCH “Not Registered” Datasets in our Database. Cause the user deinstalled our app or something else.

So how can i “grab” the $result and delete them in one step?

Could you please help me?

Jon Morris

This is a great tutorial, excellent job. Works as followed, however; can you explain why the Registration Layout continues to load even after device has been registered? I have compared to several and reworked in different versions with no luck.

Maybe you can explain why the app is asking for Username and Email even after registered.

Thanks so much for your work, very helpful.

Akshay Thakare

I still don’t understand how the GCM registration id is being saved by the app?

Pham Anh

You must open the template by eclipse or android studio then edit the activity files

Pham Anh

How to send notification to a group of users or all user?

pofos

hello. your example work good. but there are 2 problems. when my phone receive the message and i tap at it on the notify center it opens a blank screen. that means all the messages received when the app is not opening wont be saved. second, after i successfully registered my phone to server and close the app then open again, it will be the register screen @.@ (however it still can reeceive message). please help me. my current knowledge does not enable me to solve this 🙁

Usman Maqsood

What is the purpose of this string “DISPLAY_MESSAGE_ACTION” and how does it serve it?

Максим Гуров

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:wampwwwgcm_server_phpdb_connect.php on line 19

hasan

You have not given code for test.php ?

Loki

I can register and pass all the info in the database. However when I send a message,the push notification thing is not going to my genymotion emulator(it has google play services):(.

Loki

Fixed!! I used the wrong API key!! Thank you my friend. May God bless you!!

volpesfuggente

Hi, thank you very much for this tutorial.
I have followed your guide for the development of a PUSH service in my app. But if the app is closed (or killed) the push notifications cannot be received. You can I fix this?

Nhâm Vũ

🙂 Thank ravi for amazing tutorial. But i have a question, how to receive message when force stop app. Waiting for your cmt!

thank Ravi for amazing tutorial, but how to show push notification badge count on app icon in android programmatically

Guest

Hello, Thanks for this amazing tutorial, it saved me two years ago.
But now I try to build the same project, I can register and all, but I cannot receive push notifications, it worked before with this same code, now it doesn’t !!!! anyone with the same problem ?

duke cyger

Maybe U need to Update your GCM library or Change the Key.

Alex

Thank’s for the useful tutorial but I still continue to have some issues!
Can you provide an example on how myServer can push notifies to registered devices?
Thank’s in advance

Ron

I can see a lot of question regarding this wonderful tutorial, no question in that.. but i can’t find any answers for those question. It would be great if Mr. Ravi or anyone could help us out with our question to make this tutorial more awesome.

waseem ahmad

how TO Start New Activity ..On CLick Of Notification

please Answer

I Started …New Activity
But Aftr Some Time
App Is Like started And Main Page Is Opened

Stefan

Hi Ravi, how do I write the PHP code so I can setup a page to send push notifications to multiple registered devices from one text box?

Your help is very much appreciated.

Thank You,

Rendi Arcanggi

Hi Ravi. Thank you for the tutorial. I would like to ask you how do I modify the display device one at a time using the button next and prev. if i click next then automatically send a message to the next device.
Thank you.

Manav Patadia

Great tutorial!!!! thank you 🙂 working fine on eclipse but libraries are not supported in android studio…

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

Ercan

Hello, when i try to send message to device after send button i can’t see on device. what can be problem ?

Sunny

Thanks Android-hive For Great Tutorials.
Could You Please Make some tutorial on SIP protocol .
Thanks in advance

Hauke Schrills

Hello , thanks for this tut., I have only one question.: How can I send a Message from my App to the Server?

Ronak

Excellent tutorial. Thanks.

Gon Her

What if we need to send a notice to 10,000 devices?

Edwin

@Ravi Tamada, the only problem i see is that usually even a new app would have 1000+ users and sending notifications to each user is not really efficient..

yoon

Thanks. You are genius

Rehan

Hey Ravi.. First I would like to thank you for providing such helpful and detailed tutorials 🙂 However this tutorial seems to be a bit outdated as Android now uses the Google Play Services for configuring GCM client. Can you please provide us an updated tutorial

Gerer Reger

how can we send gcm message in one click to all the users the code in php does provide option to send message to all users but it has to be done one by one , for each user individually how can we do the same for all users in onclick button

how to by pass registration form if device already registered.
or redirect to new activity

Pankaj Chauhan

Sir, I want to know is it important to use 3rd-party application server? Can we use GCM without it?

Fernando Ybus

Thank you again!

IrsHaD

is it working ..work’in ??

Alika Demon

wroking and how??

azmigiga

Hi, I have registered my userid and email. I check a gcm_users table and all information is there … gcm_recid,name,email, and date. Successful registration

Then I run gcm_server_php/index.php from a browser. I keyed in a message and click send button.
However, my device not getting a message sent. Can some help… what is my problem here. Note I have api key, sender id, url already and been keyed in accordingly.

IrsHaD

same here ?? any solution..

Alika Demon

same here, help plz???

Devendra Kumar Singh

same here please help, what is the problem ???

Shovon

( No reply from anyone? ) Hi, Could you fix it/make it working?

akshay

I’m facing the same problem.. please answer

ani

Guys the problem is with the key.. please generate new key and try works fine 🙂
thanks ravi 🙂

Fernando Ybus

I am getting
Unauthorized
Error 401
on the php and I the php scripts are not saving the data on the DB.
Can you help?

Fernando Ybus

I got the wrong API. I was using an old one for the Google Maps

Ali Arasteh

That seems really good, but the problem is that GCM needs at least one google account already set on devices below android v 4. many of my users are having old android versions and they do not have google account. is there any alternative?

IrsHaD

registered to GCM but unable to get push notifications ?? @ravi

Alika Demon

i have same problem device added successfully, but can’t get push notification. Heelp men. I’m using emulator API 4.4.2

IrsHaD

@Alika – may be itz the API key I guess causing error !!

i am using server key n u ?? can u tell me how u are creating API key.. mine also not working 🙁

Alika Demon

@IrsHaD tried many ways but still no result..
I used both server key and browse key, but not working…

Alika Demon

If you find the method plz tell me!!

ani

Please try to generate new key and make corresponding changes and try 🙂 works 🙂

Vikas Mittal

You have to use the Server key – just for testing purpose leave the IP address blank – it will work.

Later on you might want to insert your IP address where you have hosted the PHP files – that will resolve the issue as well

Nice Tutorial but one problem i have fetch.
how to open specific activity .

my gcm perfect work but by default one activity open.when push notification on my phone come.

i want to open categories wise activity.

Hari krishna

Hi I have a problem with the above implementation,that is Registration gets expired in 7 days, again i need to reinstall the app when this problem occurs. Can u please tell me how to overcome it from the above code.

PHP 4.x has been dropped , so all mysql functions must be rewritten in mysqli or PDO, I’m trying to do that but some errors still appear !
Can you help us to rewrite it please ?

jj

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

Umesh Pol

Hi, Thank you for sharing. I want to add profile photo as well with the registration form. Can you let me know best way to do this, because by using above code if i send image file in string format, it is not working.

Guest

So the summary is, we cannot send message to the device with this code (I tried, no luck) And this code is not for latest google play. Correct me if I am wrong.

Shovon

Hi,
Unfortunately I have tried this example. I could not manage to send push to the device.
And each time I click register on the android device, it registers for 4 times on the server.
What should I do? Thank you.

kapil

hey do you running sample code of GCM notification?

Shovon

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

Hari Babu

I am trying this exaple.i found a problem.you are using
PROPERTY_ON_SERVER_EXPIRATION_TIME = “onServerExpirationTime”;
and
PROPERTY_ON_SERVER_LIFESPAN = “onServerLifeSpan”;
first time when i rigistered It was not inseted into database but updataed into shared prefs.

when i am trying to register again you are already registered message is coming.
the insrt call back nad saving in shared prefs are not synchronized i hink.

No wi could not know when the time expires, and there is no option to unregistered even if i want to use this in a real project the unregistered code is very important!

how much time I need to wait for next trial?
how could i unrigister the user after the temporaray service broken for the user?

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

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

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

Vishal gadhiya

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

jj

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

Jahanvi

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

Safaa Frewan

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

Mohamed Arif

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

Mohamed Arif

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

SatishKumar Gollapudi

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

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

Guest

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

AgorApps Apps

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

Am

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

mojtaba

Hi Ravi .
Thank you for your knowledge sharing .
Dear Ravi i followed your tutorial and another tutorials of other Blogs same as (http://www.androidbegin.com/tutorial/android-google-cloud-messaging-gcm-tutorial/)
i create push notification with GCM and Parse .
But always I had a specific problem 🙁 .
I have 2 mobile . One of them always is OKay with GCM,parse , ….
But another one always DOES NOT display notification :
server say to me :
{“multicast_id”:6605469723439838980,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1428139906268067%a08c77f7f9fd7ecd”}]}

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

But WHY in only one device i have problem ?

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

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

mojtaba

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

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

Sourabh Rustagi

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

sudo apt-get install php5-curl

sudo service apache2 restart

Guest

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

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

gun

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

NItesh Kumar

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

Sandeep Gupta

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

Sandeep Gupta

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

Sandeep Gupta

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

Ankit Varia

What if the app is uninstalled from the phone ?

RevHacker

GCMRegisterar is deprecated, what to do?

jj

Hello sir,

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

Deni Firdaus Waruwu

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

Can you help me please?

zero

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

rokon

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

Frank Lin

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

infotech

Dear Sir I get the following problem

infotech

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

Thanks
Please revert me. ASAP i am in trouble…

despiyado

successful working.I congratulate you are.

Ajay Parashar

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

Ranjith Kumar

Hello Ajay Parashar,

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

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

;extension=php_curl.dll

After that it will look something like something below-

extension=php_curl.dll

Step 3:

Restart your Apache server.

Ajay Parashar

Hello Ranjith Kumar,

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

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

How to solve this ?…

Krishan

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

Sanjiv

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

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

chand becse

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

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

Prasanna Davu

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

xyz

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

Mahdi Kenji

i’ts not work on api 9 why?

jerom

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

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

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

Josh Holiday

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

Mannu

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

Momina Nisar

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

Kumar

nice explanation

Danial Habibi

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

gaganpreet singh

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

Devendra Mahajan

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

I tried to use the key for server applications, for android applications and for browser applications and I always get a success message like
{“multicast_id”:4834811390816509486,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1434224528310781%2a748ce7f9fd7ecd”}]}

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

parakh singhal

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

gaganpreet singh

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

latiful anwar

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

Nagesh Chinna

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

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

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

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

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

Huy Hóm Hỉnh

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

Karishma

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

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

gaganpreet singh

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

Akshobhya Aksho

HI I’m not that greatly exposed to the ecllipse IDE but i started learning in android studio and in that the packages that are being imported in this program (com.google.android.gcm.GCMRegistrar) are not working they have been deprecated 🙁

Chethan Sreenivasa

First I appreciate Ravi For sharing his knowledge…

When the I run the PHP file using wamp in browser http://localhost/gcm_server_php/….. I am getting the error like…1.Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:wampwwwgcm_server_phpdb_connect.php on line 19
2. Warning: mysql_connect(): in C:wampwwwgcm_server_phpdb_connect.php on line 19
3. Deprecated: mysql_select_db(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:wampwwwgcm_server_phpdb_connect.php on line 21

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

Shubham Tile

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

Thanks for the post 🙂 , can you please update the post with new Google Cloud Messaging?

Android Example

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

ratt

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

Ravneet

same here

Harshal Pathak

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

Dimas Andrianto Setiawan

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

Dimas Andrianto Setiawan

i got an error when running php please help me

Harry Smith

Nice article thanks ravi.

Dimas Andrianto Setiawan

do you use anddroid studio? or eclips??

Harry Smith

Android studio

Nurrochman Ferdiansyah

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

Anyone here use android studio to create this tutorial????
i have problem when trying to import GCM. It’s like android studio didn’t recognize :
import com.google.android.gcm.GCMBaseIntentService;
Please Help 🙁

Madson Gr

did you try to compile on gradle? add this on the dependencies: compile ‘com.google.android.gms:play-services-gcm:8.1.0’

and this one at the top: apply plugin: ‘com.google.gms.google-services’

Nurrochman Ferdiansyah

Thanks for your response.
i have solve it, when i add this on dependencies : ‘compile ‘com.google.android.gms:play-services-gcm:8.1.0’ . It’s still have same error.
so i add gcm.jar manually then call it on gradle.

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

Bhavik Shah

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

Ricky sharma

i have not RECIVE subscribe MAIL

John Adjognidje

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

Mohammed Almihdar

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

Nishant Meena

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

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

Atish Agrawal

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

Alvaro Rivera

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

Christian

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

Christian

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

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

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

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

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

Akash kumar

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

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

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

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

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

Thanks in advance!
-Shijin Krishna

Naina Jain

I had issue clicking on notification on notification bar which is not opening desired Activity of that particular android application. how to do please share the code i have implemented gcm in my android application using this link :-http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/. thanks

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

Vaibhav Kadam

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

Vaibhav Kadam

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

Rishab Ghanti

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

Arhaan Khan

Where is test.php..??

Fabi

I hope you can update this topic 🙁 didn’t worked for me..

Sahil

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

Serious Sam

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

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

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

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

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

Ibrahim Samad

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

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

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

Alzahrani Abdullah

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

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

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

Alzahrani Abdullah

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

Loki

Hello Ravi,

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

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

Loki

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

shoaibfarhan

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

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

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

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

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

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

Shivakumar

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

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

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

Kumar Bharani

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

Sharath

Hi Ravi, am new to this concept, thanks for providing this tutorial it helped me alot, But am getting error as Connot resolve method ‘setLatestEventInfo(Context, String,String,Pending Intent) inside 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.

Alfian Hidayat

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

{

multicast_id: 9004810007812981000,

success: 0,

failure: 1,

canonical_ids: 0,

results: [

{

error: “InvalidRegistration”

}

]

}

can you help me. thank you !

parminder

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

vivekvyas

add GCM.jar file and import …..

Akshay Ram

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

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

Ahmed Fahmy

( ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:wampwwwgcm_server_phpdb_connect.php on line 19

can u help me !!

Mesut Dönmez

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

Ahmed Fahmy

hey Ravi , i have proplem in

( ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:wampwwwgcm_server_phpdb_connect.php on line 19
can u help me !!

RAHUL PAWAR

instead of mysql_connect() use mysqli_connect()

Mohab Youssef

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

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

Thanks

jérôme le champion

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

New Message: From Demo Server: successfully added device!

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

New Message: Your device registered whith GCM

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

Thank you

jérôme le champion

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

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

vinod

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

syed muhammad awais

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

Android_Rocks

Ravi sir ,

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

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

Maamoon Yaghi

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

Arish

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

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

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

Michael Magdy

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

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

Michael Magdy

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

Michael Magdy

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

bhavin

can anyone write a code for test.php

syed muhammad awais

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

Mukesh Joshi

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

Venugopal

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

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

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

Thank you.

Hari Krishnan

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

shivani garg

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

Chandan Sharma

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

Stephen

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

Amelia Abdullah

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

Amir Kotb

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

Concetto Developer

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

Yazdan

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

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

Dhaval Tailor

hii
please solve this problem
GCMRegistrar cannot resolve symbol

niteen bhende

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

Gowtham Nimmagadda

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

Devi Septian II

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

AI DA

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

AI DA

From GCM: error
(AUTHENTICATION_FAILED).

Soft Fudge

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

Adedara Klever Olanrewaju

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

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

Adedara Klever Olanrewaju

Alright I will be waiting..Thanks

Soft Fudge

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

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

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

AbelardoLG

Hello world,

I’m back.

At the time, I have the following errors:
> “Could not find com.google.firebase:firebase-core:9.6.0.”
> “Could not find com.google.firebase:firebase-messaging:9.6.0.”

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

A great tutorial!

Best regards and thanks you for your help,

Abelardo.

AbelardoLG

Hi Ravi,

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

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

Thanks in advance and for your time&support.

Best regards,

Abelardo.

AbelardoLG

Hi Ravi,

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

Best regards.

AbelardoLG

Hi Ravi,

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

Yes, my problem was solved.

All the best,

Abelardo.

AbelardoLG

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

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

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

Kiny

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

Vaibhav Purohit

hello ravi Sir,

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

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

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

Arbaz Alam

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

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

Regards,
Yair

ABY MATHEW

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

Salin

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

thanks

Chaitanya Dharmale

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

saurabh sarpotdar

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

Viswanathan G

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

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

theP

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

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

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

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

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

Yes it’s work…I can send up to 3000 ,server stop working after 2 min bcz it’s take too much time to send a message …now problem with time or php file have issues that I don’t know..if u have any solution then guide me…..

Babin Raj M

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

ARASHI Funsho

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

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

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

gautam kumar

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

saurabh sarpotdar

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

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

Geraldo K Fillipus

Awesome

Andrew Buchan

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

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

saeed

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

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

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

Paritosh Chaudhary

Hi Ravi..!!

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

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

PINKesh Darji

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

Suraj Patil

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

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