At the Google IO 2012, the beta version of Android push notifications system called C2DM was replaced by Google Cloud Messaging (GCM). GCM has many new features over the existing system. Refer to this document for details of the differences and details about migrating your existing systems from C2DM to GCM.
To get started, download the Extras > Google Cloud Messaging for Android Library from the Android SDK.This library provides the jars to simplify the development on both the server side and client side.
From the Google API console page, create a new project and generate the API key. Refer this page for complete details.
Client Application
Create a new android project and add the GCM.jar to its buildpath.Generate the AndroidManifest.xml file as per the document. You can also verify that all the required parameters have been set in the manifest file by calling this function:
Once the app is created, run it on the android device and note the registrationId from the logs. Make sure that the device is having Android Market/Play Store installed and signed in using a Google Account. The code might not run on emulators.
Add a service to the project which would extend the GCMBaseIntentService and implement what needs to be done when on registration, de-registration, message receipt etc. On receiving a message, the data sent from server is in the form of an intent which can be resolved as :
Server Application
To test the push notifications, create a simple java project with a main function. Add the gcm-server.jar from the Android SDK extras folder to its build path.
Use the below code to send the notifications:
To add some payload data into the notification, create the message using the below code.This message is sent as an intent which can be resolved at the client end.
Message message = new Message.Builder()
ArrayList
Google provides the sample apps in the SDK by default, you may download a very basic version of them containing only the code discussed in this tutorial from here.
The same application is also available on play store here.
Few points to be taken care of:
1. If you use EmailId as the SENDER_ID, then you are actually registering for C2DM and not GCM. The notifications would not be received using this code although you. would be able to fetch the registrationId
2. In the above code, on receiving a notification,only a logcat entry is seen. You may edit the same to show the text on notification bar or perform any other action by editing the class which implements GCMBaseIntentService .
3.While uploading the application to Play Store, Navigate to "Services and API" section and Link the sender IDs to ensure proper functioning.
Updates:
1. Multicast Messages
2.Payload data from server
3.Receive Payload data and display as notificatoin
To get started, download the Extras > Google Cloud Messaging for Android Library from the Android SDK.This library provides the jars to simplify the development on both the server side and client side.
From the Google API console page, create a new project and generate the API key. Refer this page for complete details.
Client Application
Create a new android project and add the GCM.jar to its buildpath.Generate the AndroidManifest.xml file as per the document. You can also verify that all the required parameters have been set in the manifest file by calling this function:
GCMRegistrar.checkManifest(this);Create a new activity and add the following code to register. replace the SENDER_ID with the 12 digit project Id from the URL.
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, SENDER_ID);
} else {
Log.v(TAG, "Already registered");
}
Once the app is created, run it on the android device and note the registrationId from the logs. Make sure that the device is having Android Market/Play Store installed and signed in using a Google Account. The code might not run on emulators.
Add a service to the project which would extend the GCMBaseIntentService and implement what needs to be done when on registration, de-registration, message receipt etc. On receiving a message, the data sent from server is in the form of an intent which can be resolved as :
@Override
protected void onMessage(Context arg0, Intent arg1) {
Log.d("GCM", "RECIEVED A MESSAGE");
// Get the data from intent and send to notificaion bar
generateNotification(arg0, arg1.getStringExtra("message"));
}
In the generateNotification function, add the code that you need to do on receiving a message.In this example, I display the text in the notification bar.
Server Application
To test the push notifications, create a simple java project with a main function. Add the gcm-server.jar from the Android SDK extras folder to its build path.
Use the below code to send the notifications:
Sender sender = new Sender("AIzaXXXXXXXXXXXXXXXXXXXXXXXXX");
Message message = new Message.Builder().build();
Result result = sender.send(message,"device_token", 1);
System.out.println(result.toString());
To add some payload data into the notification, create the message using the below code.This message is sent as an intent which can be resolved at the client end.
Message message = new Message.Builder()
.collapseKey("1")
.timeToLive(3)
.delayWhileIdle(true)
.addData("message",
"this text will be seen in notification bar!!")
.build();
To multicast a message, use an List of device tokes. Use a MulticastResult Object in this case instead of the Result object as done earlier:ArrayList
devicesList = new ArrayList(); devicesList.add("device_token_1"); devicesList.add("device_token_2"); MulticastResult result = sender.send(message, devicesList, 1); sender.send(message, devicesList, 1);
The same application is also available on play store here.
Few points to be taken care of:
1. If you use EmailId as the SENDER_ID, then you are actually registering for C2DM and not GCM. The notifications would not be received using this code although you. would be able to fetch the registrationId
2. In the above code, on receiving a notification,only a logcat entry is seen. You may edit the same to show the text on notification bar or perform any other action by editing the class which implements GCMBaseIntentService .
3.While uploading the application to Play Store, Navigate to "Services and API" section and Link the sender IDs to ensure proper functioning.
Updates:
1. Multicast Messages
2.Payload data from server
3.Receive Payload data and display as notificatoin
how do i run both the android client and the server simultaneously?
ReplyDeleteBrilliant example.. really easy to implement and getting to work
ReplyDelete@gautam Install the client code on an android device.Run it to get the registrationID. Use this registrationID on the server code and run like a normal java program with a main function().
ReplyDeleteThanks a ton! It was a nice and precise tutorial. This is tutorial is going to get tons of hits in future. Kudos :)
ReplyDeletei am getting an error in java file "java.lang.UnsupportedClassVersionError: in/amolgupta/android/gcm/server/Notify : Unsupported major.minor version 51.0
Delete" how do i solve this?
Thanks
Boss i get this Exception
ReplyDeleteException in thread "main" java.lang.NoClassDefFoundError: org/json/simple/parser/ParseException
at sample.main(sample.java:10)
Caused by: java.lang.ClassNotFoundException: org.json.simple.parser.ParseException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
seems like u have to add json_simple-1.1.jar lib file to ur project lib folder or in add it into ur java buikd path!!
DeleteI get an Exclamation symbol on the java project.How do i set that right
ReplyDelete?
configure the buildpath properly.
DeleteDid you try GCM demo on ubuntu?
ReplyDeleteNope. I tried in Windows. I have some issue can you help me?
ReplyDeleteI was running in a emulator and so its was not working. When i tried in ma mobile its working.. but "regId" is null. In the Dashboard of Google API console page Project ID: and its not registered? do i need to register?? ther if so what do i give?
ReplyDeleteThere are two keys Browser key and Private Key which one to use and where i can use it?? in push-app?? exactly where?? i would also like to know what us the string, Do i need to give the same ,if not how to obtain that??
devicesList.add("APA91bH1cc67ghqwUcXyJieu1DLZ3AJ5L_dkNztzlT61I1KucnJiabzKEiOtE72NJAxK6cdSdAMUUmSMP8nhhn73usxITJZ-H49y_HO4ri67YlZqcwXYqW1-2LyQDl0rwfzF_eepwx7we8h9N8QgLfioDqH6R1xlaw");
please enlighten me?
Thanks and Regards,
Gautam B
Gautam,
DeleteI don't think that it would work on an Emulator. If you install it on a device and open the app, you would find the DeviceID written on the screen and also in the Logcat. You have to copy that and use it to call the DeviceList.add() function in this code.
Also the red exclamation mark is due to some error with android version installed with you. Consider upgrading the SDK and eclipse plugin and configuring buildpath properly.
GCM works on emulators with Google API sdk. Be sure to sign in to google account in the emulator.
Deletegreat! I did not test ....but its great to hear that since C2DM did not
Deletefor testing GCM on development environment. I can use Android mobile device emulator. Or need one physical device?
ReplyDeleteI am not sure but I don't think it would work on an Emulator. C2DM also did not work on emulators.
DeleteIt would give and exception about missing Google Services Framework (com.google.android.gsf)
Hi. I tried to toast the 'resId' but i am getting only null after registering, Where am i doing wrong?
ReplyDeleteProbably you need to check the code on an actual device instead of Emulator. Also make ure that your are logged in with a google account on that device as it uses google services framework.
DeleteI tried in ma android phone after logging into Google account.My code is as below which is yours,
ReplyDeletepublic void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GCMRegistrar.checkDevice(this);
GCMRegistrar.unregister(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "576574596410");
Log.d("info", GCMRegistrar.getRegistrationId(this));
Toast.makeText(this, regId+" INFO", Toast.LENGTH_LONG).show();
} else {
Log.d("info", "already registered as" + regId);
Toast.makeText(this,regId+" already registered as", Toast.LENGTH_LONG).show();
}
still i am only seening "INFO" in the toast.. plz address on this issue.
DeleteThanks and Regards,
Gautam B
i also have the same problem please help me out
Delete07-17 09:57:02.411: D/GCMBaseIntentService(20242): handleRegistration: registrationId = null, error = PHONE_REGISTRATION_ERROR, unregistered = null
ReplyDelete07-17 09:57:02.411: D/GCMBaseIntentService(20242): Registration error: PHONE_REGISTRATION_ERROR
can yu guess where am i going wrong? :)
thanks and regards,
Gautam B
Strange issue .... check out this conversation https://groups.google.com/forum/#!topic/android-gcm/UKwUPZMSqiM
DeleteSeems like GCM is having some issues and not your code.
Thanks for your Pointer.
ReplyDeletethe project ID in Google Console API page is blank do i need to register in that ?
yes definitely .
ReplyDeleteHello,Amol i migrade from C2DM to GCM successfully.But a problem i am facing there is still failing notification message.when i am running my app all time i am not getting notification.Sometimes its work frequenctly and sometimes it is being failed.
ReplyDeleteYou can not ensure 100% being delivered successfully.All you can do is make sure that your internet connectivity is proper on server and client.
Deletethanks a lot! i finally git it working! the issue is its not compatible with 2.2.
ReplyDeleteNeed help!!!
ReplyDeleteGet this error on the server side
java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.google.android.gcm.server.Sender.sendNoRetry(Sender.java:362)
at com.google.android.gcm.server.Sender.send(Sender.java:261)
at in.amolgupta.android.gcm.server.Notify.main(Notify.java:40)
Now getting this when i run Notify.java
Deletejava.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.google.android.gcm.server.Sender.sendNoRetry(Sender.java:362)
at com.google.android.gcm.server.Sender.send(Sender.java:261)
at in.amolgupta.android.gcm.server.Notify.main(Notify.java:40)
Do you find any way to solve problem. Kindly help me to fix it.
DeleteMulticastResult(multicast_id=8251043381382428038,total=2,success=0,failure=2,canonical_ids=0,results: [[ errorCode=MismatchSenderId ], [ errorCode=MismatchSenderId ]]
ReplyDeletewhen i run this java program got this error massage
please make sure that the senderID is same as what you have on the API console and device ID is also correct.
DeleteMulticastResult(multicast_id=6008403921588221372,total=1,success=0,failure=1,canonical_ids=0,results: [[ errorCode=MismatchSenderId ]]
DeleteI'm also getting this error....
here sender_id == #project_id given from google api console page, is't it?
its actually the id seen in the API console's URL
Deletewell, for single cast this is working
Deletebut for multicast message the following error is shown....why?
MulticastResult(multicast_id=6008403921588221372,total=1,success=0,failure=1,canonical_ids=0,results: [[ errorCode=MismatchSenderId ]]
i am also getting same issue for single cast this is working
Deletebut for multicast message the following error is shown....why?
MulticastResult(multicast_id=4859162719577270667,total=1,success=0,failure=1,canonical_ids=0,results: [[ errorCode=MismatchSenderId ]]
Hi Amol,
ReplyDeleteI can't send message to application, proxy blocks me.
How can i fix it?
How can i set sender.send or get over proxy?
Delete4 hours and I dint figure that it was the proxy which was blocking me. Thanks a lot guys.
Deleteyou can configure proxy settings from your code. refer http://stackoverflow.com/questions/120797/how-do-i-set-the-proxy-to-be-used-by-the-jvm
ReplyDeleteThank you, sender.send... line is executed, and i get a messageId, but now i want to show the message on my device with a toast.
DeleteI write that in the GCMIntentService
@Override
protected void onMessage(Context arg0, Intent arg1) {
Log.i(TAG, "new message= ");
Toast.makeText(this, arg1.getStringExtra("message"), Toast.LENGTH_SHORT).show();
}
but it is not working, can you help me about it.
Amol,
DeleteI run your project's GCMIntentService but i can't still get notification at application. How can i fix it?
Please post the errors from logcat.
DeleteI don't receive any errors from logcat. Also, I may use my phone without connecting it to my computer because the communication is done by using a web server(tomcat). I receive a message with status 0 but i don't see any notifications on my phone about this message. It seems google cloud receives the message but my phone can't get it from there. What are the possible causes for this? What do you think?
Deletei am getting an error:
ReplyDeleteVFY: unable to resolve static method 3058: Lcom/google/android/gcm/GCMRegistrar;.checkDevice (Landroid/content/Context;)V
shutting down VM
threadid=1 thread exiting with uncaught exception (group=0x40018578)
i have the gcm.jar imported as an external jar into the libraries in the projects java build path
i have also imported the com.google.android.gcm.GCMRegistrar; into the project.
this is being tested on an android device i recently bought running 2.3.6 and already logged into the Google Play store.
Any help you could give would be greatly appreciated!
resolved:
DeleteForgot to check the gcm.jar in the Order and Export tab of java build path
@the author: In the server code i am passing the api key generated as the parameter while creating the Sender instance. When i run the code i get this response: "errorCode=InvalidRegistration". Instead of passing the api key if i pass the registration id(that i got from android clint app) i get the 401 error. Kindly let me know where i am going wrong
ReplyDeleteI'm trying to deploy an application with push notifications. The problem is that I can not get it to work from a device. While using the emulator, everything is ok but when using a cell phone I get a log saying "AUTHENTICATION_FAILED".
ReplyDeleteI have checked and the Gmail account is synchronized but is always trying to check me out this error.
Could someone give me a hand?
I am getting [ errorCode=MismatchSenderId ] while sending message. Have anyone facing the same issue?? I am getting this result while sending the message to the client.
ReplyDelete@author:hey amol....what is the ("AIzaXXXXXXXXXXXXXXXXXXXXXXXXX");?.In the devicesList.add("device_token_1"); what is device_token?
ReplyDeleteit is the API key that you get from the google api console
Deletethanxs a lot....
Deletehey amol......This gcm is not working on GPRS ,only work with WIFI???so whats the problem?
Deletethat is strange!
DeleteSometimes the notifications get delayed but a 100% failure is a strange issue.
Hi amol,
ReplyDeleteI am getting error when i run the notify.java file
I am not able to find any message in my device from server.
This is the following error .
Please help me out.
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at com.google.android.gcm.server.Sender.post(Sender.java:468)
at com.google.android.gcm.server.Sender.sendNoRetry(Sender.java:360)
at com.google.android.gcm.server.Sender.send(Sender.java:261)
at in.amolgupta.android.gcm.server.Notify.main(Notify.java:38)
you need to check the internet connectivity on the machine. Probably your its your firewall blocking you or you are under a proxy.
ReplyDeleteHi Amol,
ReplyDeleteThanks for ans,
now should i change the proxy address.
Sir.
ReplyDeleteI appreciate your work.
when run the server code then show error in console view.
Please reply me......
Error on console view is:
Deletejava.lang.IllegalArgumentException: argument cannot be null
at com.google.android.gcm.server.Sender.nonNull(Sender.java:553)
at com.google.android.gcm.server.Sender.getString(Sender.java:534)
at com.google.android.gcm.server.Sender.sendNoRetry(Sender.java:365)
at com.google.android.gcm.server.Sender.send(Sender.java:261)
at com.vin.pushnotificationserver.Notify.main(Notify.java:42)
I think its a known issue and there is nothing much you can do about it :(
DeleteI downloaded the codes from the tutorial and ran the client on my Samsung Galaxy SII, Android version 2.3.6.
ReplyDelete1) For the Client Application, in the Console view:
Android Launch!
adb is running normally.
Performing com.example.checkoutandroid.GCMActivity activity launch
Uploading CheckoutAndroid.apk onto device '65f0660f'
Installing CheckoutAndroid.apk...
Success!
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
New package not yet registered with the system. Waiting 3 seconds before next attempt.
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.checkoutandroid/.GCMActivity }
New package not yet registered with the system. Waiting 3 seconds before next attempt.
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
New package not yet registered with the system. Waiting 3 seconds before next attempt.
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
New package not yet registered with the system. Waiting 3 seconds before next attempt.
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.checkoutandroid/.GCMActivity }
ActivityManager: Error type 3
ActivityManager: Error: Activity class {com.example.checkoutandroid/com.example.checkoutandroid.GCMActivity} does not exist.
a. Is 65f0660f device ID or Registration ID? If not, how can I find the Registration ID?
b. I saw this app is installed on my cell phone. I also entered *#*#CHECKIN#*#* on the cell phone's dialer and the notification area did indicate I was “checked in”. What are all those messages about?
2) For the Server Application:
a. In the codes:
devicesList = new ArrayList();
devicesList.add(“65f0660f”);
devicesList.add(“65f0660f”);
Is device_token_1 equal to 65f0660f?
b. In the Console View, I got:
Notify (1) [Java Application} C:\Program Files\Java\jre7\bin\javaw.exe
MulticastResult(multicast_id=7313135794926623592,total=1,success=0,failure=1,canonical_ids=0,results: [[ errorCode=InvalidRegistration ], [ errorCode=InvalidRegistration ]]
What are these messages about? I didn’t see any message sent to my cell phone.
Please advise. Thanks.
I downloaded the codes from the tutorial and ran the client on my Samsung Galaxy SII, Android version 2.3.6.
ReplyDelete1) For the Client Application, in the Console view:
Android Launch!
adb is running normally.
Performing com.example.checkoutandroid.GCMActivity activity launch
Uploading CheckoutAndroid.apk onto device '65f0660f'
Installing CheckoutAndroid.apk...
Success!
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
New package not yet registered with the system. Waiting 3 seconds before next attempt.
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.checkoutandroid/.GCMActivity }
New package not yet registered with the system. Waiting 3 seconds before next attempt.
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
New package not yet registered with the system. Waiting 3 seconds before next attempt.
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
New package not yet registered with the system. Waiting 3 seconds before next attempt.
Starting activity com.example.checkoutandroid.GCMActivity on device 65f0660f
ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.checkoutandroid/.GCMActivity }
ActivityManager: Error type 3
ActivityManager: Error: Activity class {com.example.checkoutandroid/com.example.checkoutandroid.GCMActivity} does not exist.
a. Is 65f0660f device ID or Registration ID? If not, how can I find the Registration ID?
b. I saw this app is installed on my cell phone. I also entered *#*#CHECKIN#*#* on the cell phone’s dialer and the notification area did indicate I was “checked in”. What are all those messages about?
2) For the Server Application:
a. In the codes:
devicesList = new ArrayList();
devicesList.add(“65f0660f”);
devicesList.add(“65f0660f”);
Is device_token_1 equal to 65f0660f?
b. In the Console View, I got:
Notify (1) [Java Application} C:\Program Files\Java\jre7\bin\javaw.exe
MulticastResult(multicast_id=7313135794926623592,total=1,success=0,failure=1,canonical_ids=0,results: [[ errorCode=InvalidRegistration ], [ errorCode=InvalidRegistration ]]
What are these message about? I didn’t see any message sent to my cell phone.
3) Can I see the message sent from the Server in the Google APIs Console?
Please advise. Thanks.
Hi Amol,
ReplyDeleteNice Tutorial. Works fine on Android 2.x devices but I am having problem running it on Android 4.x Samsung devices. Can u help me in resolving this issue?
Thanks in advance.
thank you!
ReplyDeletePlease post the exact issue that you are facing :)
Hi Amol,
ReplyDeleteWhen I install app on android 2.x devices and run the server code, I get a notification. But when I run it on Android 4.x Samsung device I get the following error :
MulticastResult(multicast_id=8302094760967998219,total=1,success=0,failure=1,canonical_ids=0,results: [[ errorCode=InvalidRegistration ]]
Can u help me regarding this issue?
please paste me full java server side code.
ReplyDeletePlease follow the download link in the article to get the complete server and client side code :)
DeleteHi Amol,
DeleteI strictly followed the tutorial but still not receiving the notification, neither on Phone nor on Emulator. When i run the server code, getting this result.
Result : MulticastResult(multicast_id=7477341139707957564,total=2,success=2,failure=0,canonical_ids=0,results: [[ messageId=0:1349533966095787%d689de2500000031 ], [ messageId=0:1349533966095783%d689de2500000031 ]]
Could you please help me at the earliest possible?
Puneet, in the response code , success=2 show that the notifications have been forwarded by google servers to the devices. You should check the connectivity of the devices and the code to receive/show the notification content.
ReplyDeletenice example.. and this is best resource. it works for me :-)
ReplyDeleteI have been looking for a tutorial on how to create the server, so far this looks promising and I can't wait to test it, but I will be creating a webapp to test it...
ReplyDeleteHi Amol,
ReplyDeleteI downloaded your SamplePush files and changed the package name.
I ran it in Samsung Galaxy SII device.
I got the error at the LogCat: E/dalvikvm(5303): Unable to open stack trace file '/data/anr/traces.txt': Permission denied.
In the mobile device, I got a "Sorry!' message": The application SamplePush has stopped unexpectedly. Please try again. "Force close"
Please advise.
This logcat snippet does not indicate much although I suggest if you have changed the package names, make sure the manifest entries have also been fixed.
DeleteHi Amol,
DeleteNow I used your package name "in.amolgupta.android.gcm" to try it out in my Samsung Galaxy SII device and got the following errors from LogCat:
10-19 10:33:14.369: I/dalvikvm(3719): Could not find method com.google.android.gcm.GCMRegistrar.checkDevice, referenced from method in.amolgupta.android.gcm.SamplePushActivity.onCreate
10-19 10:33:14.369: W/dalvikvm(3719): VFY: unable to resolve static method 3023: Lcom/google/android/gcm/GCMRegistrar;.checkDevice (Landroid/content/Context;)V
10-19 10:33:14.369: D/dalvikvm(3719): VFY: replacing opcode 0x71 at 0x0010
10-19 10:33:14.369: D/dalvikvm(3719): VFY: dead code 0x0013-0060 in Lin/amolgupta/android/gcm/SamplePushActivity;.onCreate (Landroid/os/Bundle;)V
10-19 10:33:14.449: D/dalvikvm(3719): GC_EXTERNAL_ALLOC freed 50K, 43% free 3075K/5379K, external 0K/0K, paused 56ms
10-19 10:33:14.469: D/AndroidRuntime(3719): Shutting down VM
10-19 10:33:14.469: W/dalvikvm(3719): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
10-19 10:33:14.469: E/AndroidRuntime(3719): FATAL EXCEPTION: main
10-19 10:33:14.469: E/AndroidRuntime(3719): java.lang.NoClassDefFoundError: com.google.android.gcm.GCMRegistrar
10-19 10:33:14.469: E/AndroidRuntime(3719): at in.amolgupta.android.gcm.SamplePushActivity.onCreate(SamplePushActivity.java:17)
10-19 10:33:14.469: E/AndroidRuntime(3719): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-19 10:33:14.469: E/AndroidRuntime(3719): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
10-19 10:33:14.469: E/AndroidRuntime(3719): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
10-19 10:33:14.469: E/AndroidRuntime(3719): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-19 10:33:14.469: E/AndroidRuntime(3719): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
10-19 10:33:14.469: E/AndroidRuntime(3719): at android.os.Handler.dispatchMessage(Handler.java:99)
10-19 10:33:14.469: E/AndroidRuntime(3719): at android.os.Looper.loop(Looper.java:130)
10-19 10:33:14.469: E/AndroidRuntime(3719): at android.app.ActivityThread.main(ActivityThread.java:3691)
10-19 10:33:14.469: E/AndroidRuntime(3719): at java.lang.reflect.Method.invokeNative(Native Method)
10-19 10:33:14.469: E/AndroidRuntime(3719): at java.lang.reflect.Method.invoke(Method.java:507)
10-19 10:33:14.469: E/AndroidRuntime(3719): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
10-19 10:33:14.469: E/AndroidRuntime(3719): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
10-19 10:33:14.469: E/AndroidRuntime(3719): at dalvik.system.NativeStart.main(Native Method)
10-19 10:33:16.471: I/dalvikvm(3719): threadid=4: reacting to signal 3
10-19 10:33:16.471: E/dalvikvm(3719): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
10-19 10:35:30.482: I/dalvikvm(3999): threadid=4: reacting to signal 3
10-19 10:35:30.482: E/dalvikvm(3999): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
10-19 10:35:44.876: I/Process(3999): Sending signal. PID: 3999 SIG: 9
10-19 10:35:48.690: I/dalvikvm(4126): threadid=4: reacting to signal 3
10-19 10:35:48.700: E/dalvikvm(4126): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
In the mobile device, I got a "Sorry!' message": The application SamplePush has stopped unexpectedly. Please try again. "Force close"
What is the "regID" supposed to look like?
Please advise. Thanks.
ohh...got it! You need to fix the buildpath and include the jar file provided in the lib folder.
DeleteIt works now. Thanks so much.
DeleteHi Amol,
ReplyDeleteCan I send message from the client/mobile device to the 3rd party server? Any example codes?
Please advise. Thanks
use webservices.
DeleteHi Amol,
DeleteCan you refer me some reading materials for sending message from client/mobile device to 3rd party server using webservices?
Can we use GCM service to send message from client/mobile device (Android phone to 3rd party server? Any reading material on this topices? Which helper class from the GCM library?
Thanks.
Hi Amol,
ReplyDeleteWhile running the regID is printed on the logs, but setText() is empty
While we run it second time then it sets the regID value in the textview.
Please can u suggest why is this so?
run the registration in and async task and update the textview on complete of the task.
DeleteHi Amol,
ReplyDeleteNice work brother.
I am getting below errors and app forcefully stopped. Can u plz help me....
10-31 17:29:17.044: WARN/dalvikvm(21744): threadid=1: thread exiting with uncaught exception (group=0x40015560)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): FATAL EXCEPTION: main
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): java.lang.RuntimeException: Unable to start activity ComponentInfo{in.amolgupta.android.gcm/in.amolgupta.android.gcm.SamplePushActivity}: java.lang.UnsupportedOperationException: Device does not have package com.google.android.gsf
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.os.Handler.dispatchMessage(Handler.java:99)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.os.Looper.loop(Looper.java:123)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at java.lang.reflect.Method.invokeNative(Native Method)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at java.lang.reflect.Method.invoke(Method.java:507)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at dalvik.system.NativeStart.main(Native Method)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): Caused by: java.lang.UnsupportedOperationException: Device does not have package com.google.android.gsf
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at com.google.android.gcm.GCMRegistrar.checkDevice(GCMRegistrar.java:83)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at in.amolgupta.android.gcm.SamplePushActivity.onCreate(SamplePushActivity.java:17)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
10-31 17:29:17.063: ERROR/AndroidRuntime(21744): ... 11 more
10-31 17:29:17.073: WARN/ActivityManager(61): Force finishing activity in.amolgupta.android.gcm/.SamplePushActivity
seems like you are using a rooted device. Are you able to use Gtalk on your device ?? google out "Device does not have package com.google.android.gsf" and you would know what I mean.
ReplyDeleteOR
If you are using an emulator, make sure the AVD is the one with Google APIs
we have a project with using GCM infrastructure.We want to control house automation system
ReplyDeletewith an adroid application and we have a local device that has android operating system.The aim of the local device is the datastorage about the house infos and status.Is that project achievable?
Hi amol,
ReplyDeleteI am an newbie in android........
I downloaded the demo from the link n wen i imported the project(SamplePush n Pushapp)in android it is displaying an error in console
"Project has no default.properties file"
Kindly provide a solution for dis problem
Thanks in advance
right click on the project name > Android Tools > Fix Project Properties.
DeleteHello Amol,
ReplyDeleteSome times i receive this kind of error
Activity com.package.camera.Login has leaked IntentReceiver com.google.android.gcm.GCMBroadcastReceiver@12323290 that was originally registered here. Are you missing a call to unregisterReceiver()?
Hey Amol,
ReplyDeleteThanx a lot.this help.
But what if I want to use web instead of this java project?
Vaibhav,
ReplyDeleteif u have a javaEE project then the same code can be used. There a several tut for integrating with php also.
awesome tutorial :)
ReplyDeletehi amol i was able to get the reg id from gcm...and trying to write server side..
ReplyDeleteas you said i just created java project in eclipse and pasted your code..but i m getting
result as [ messageId=0:1358511724948855%43363c5900000031 ] i printed result on console...
what is this msg id?
This message is just an acknowledgement from the google servers that they have received the message. You should check the device if the message has been delivered successfully there.
DeleteHi when i ran the sample code of GCM by android i got this message whenever i open my app "The application GCM Demo (process com.google.android.gcm.demo.app) has stopped unexpectedly. please try again" Can u pl help me out Amol Gupta Thanks in advance.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHi, I am only getting the message Id [ messageId=0:1359960161967667%2a05dc7900000031 ] but the notification has not been delivering to device. Please advice..
ReplyDeletethanks sir
ReplyDeletei got it. I left my onMessage() blank.
ReplyDeletei have this error :
ReplyDeleteCould not find method org.json.simple.JSONValue.toJSONString, referenced from method com.google.android.gcm.server.Sender.sendNoRetry
instead of hard coding the SENDER_ID, is there any way to generate dynamically during the initialization (using the email account configured in the mobile) ?
ReplyDeletei.e.
get the primary email account configured
use the gmail account to get the PROJECT Number i.e. SENDER_ID
using this generate regId.
anyway to do the above step?
Hi
ReplyDeleteI just studied your blog.
I need help in Google Cloud Messaging.
Can you just clear my funda how to actually integrate it mean to say in Detail..
Will be thankful to you.
U can leave me a message on my gmail id : tusharsahni50@gmail.com
Thanks
Tushar,
DeletePlease feel post any of your doubts here. Me and other readers would love to help you out :)
Will you please elaborate about how to run both application, I got Error in server side Application like "[ errorCode=InvalidRegistration ]"
ReplyDeleteand in Client Side I got nothing.
so please tell me about How to run step by step.
Hi Amol, Can U pls mail me the source code or working App folder to check this example to "aadarshgupta123@gmail.com"? Thanks!
ReplyDeleteHowever the code is running smoothinly. But why notification comes short ? Hardly one line ?
ReplyDeleteAnd when I click notification then opens blank page saying "GCM already registered"
I want to have whole content display what I send from send_message in notification, just one line is coming.
thanks
Hi, i'm newBee in here and your post was a great start for me. So thanks a lot !
ReplyDeleteJust, could you please give me some clarifications about the device_token in the devicesList.add() function and from where can i find them.
Thanks !
Unable to get the notification on Device.. after running the Notify class with the RegId from logcat.
ReplyDeleteThanks in advance.
thanks for the post... its WORKING !!
ReplyDeleteBut how to connect my code to the server ???