Wednesday, July 4, 2012

Google cloud Messaging (GCM) tutorial

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

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

109 comments:

  1. how do i run both the android client and the server simultaneously?

    ReplyDelete
  2. Brilliant example.. really easy to implement and getting to work

    ReplyDelete
  3. @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().

    ReplyDelete
  4. Thanks a ton! It was a nice and precise tutorial. This is tutorial is going to get tons of hits in future. Kudos :)

    ReplyDelete
    Replies
    1. i am getting an error in java file "java.lang.UnsupportedClassVersionError: in/amolgupta/android/gcm/server/Notify : Unsupported major.minor version 51.0
      " how do i solve this?


      Thanks

      Delete
  5. Boss i get this Exception

    Exception 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

    ReplyDelete
    Replies
    1. 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!!

      Delete
  6. I get an Exclamation symbol on the java project.How do i set that right
    ?

    ReplyDelete
    Replies
    1. configure the buildpath properly.

      Delete
  7. Nope. I tried in Windows. I have some issue can you help me?

    ReplyDelete
  8. I 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?

    There 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

    ReplyDelete
    Replies
    1. Gautam,
      I 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.

      Delete
    2. GCM works on emulators with Google API sdk. Be sure to sign in to google account in the emulator.

      Delete
    3. great! I did not test ....but its great to hear that since C2DM did not

      Delete
  9. for testing GCM on development environment. I can use Android mobile device emulator. Or need one physical device?

    ReplyDelete
    Replies
    1. I am not sure but I don't think it would work on an Emulator. C2DM also did not work on emulators.
      It would give and exception about missing Google Services Framework (com.google.android.gsf)

      Delete
  10. Hi. I tried to toast the 'resId' but i am getting only null after registering, Where am i doing wrong?

    ReplyDelete
    Replies
    1. Probably 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.

      Delete
  11. I tried in ma android phone after logging into Google account.My code is as below which is yours,

    public 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();

    }

    ReplyDelete
    Replies
    1. still i am only seening "INFO" in the toast.. plz address on this issue.

      Thanks and Regards,
      Gautam B

      Delete
    2. i also have the same problem please help me out

      Delete
  12. 07-17 09:57:02.411: D/GCMBaseIntentService(20242): handleRegistration: registrationId = null, error = PHONE_REGISTRATION_ERROR, unregistered = null
    07-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

    ReplyDelete
    Replies
    1. Strange issue .... check out this conversation https://groups.google.com/forum/#!topic/android-gcm/UKwUPZMSqiM

      Seems like GCM is having some issues and not your code.

      Delete
  13. Thanks for your Pointer.
    the project ID in Google Console API page is blank do i need to register in that ?

    ReplyDelete
  14. Hello,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.

    ReplyDelete
    Replies
    1. You can not ensure 100% being delivered successfully.All you can do is make sure that your internet connectivity is proper on server and client.

      Delete
  15. thanks a lot! i finally git it working! the issue is its not compatible with 2.2.

    ReplyDelete
  16. Need help!!!
    Get 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)

    ReplyDelete
    Replies
    1. Now getting this when i run Notify.java

      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)

      Delete
    2. Do you find any way to solve problem. Kindly help me to fix it.

      Delete
  17. MulticastResult(multicast_id=8251043381382428038,total=2,success=0,failure=2,canonical_ids=0,results: [[ errorCode=MismatchSenderId ], [ errorCode=MismatchSenderId ]]


    when i run this java program got this error massage

    ReplyDelete
    Replies
    1. please make sure that the senderID is same as what you have on the API console and device ID is also correct.

      Delete
    2. MulticastResult(multicast_id=6008403921588221372,total=1,success=0,failure=1,canonical_ids=0,results: [[ errorCode=MismatchSenderId ]]

      I'm also getting this error....
      here sender_id == #project_id given from google api console page, is't it?

      Delete
    3. its actually the id seen in the API console's URL

      Delete
    4. well, for single cast this is working
      but 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 ]]

      Delete
    5. i am also getting same issue for single cast this is working
      but 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 ]]

      Delete
  18. Hi Amol,
    I can't send message to application, proxy blocks me.
    How can i fix it?

    ReplyDelete
    Replies
    1. How can i set sender.send or get over proxy?

      Delete
    2. 4 hours and I dint figure that it was the proxy which was blocking me. Thanks a lot guys.

      Delete
  19. you 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

    ReplyDelete
    Replies
    1. Thank 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.

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

      Delete
    2. Amol,
      I run your project's GCMIntentService but i can't still get notification at application. How can i fix it?

      Delete
    3. Please post the errors from logcat.

      Delete
    4. I 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?

      Delete
  20. i am getting an error:

    VFY: 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!

    ReplyDelete
    Replies
    1. resolved:

      Forgot to check the gcm.jar in the Order and Export tab of java build path

      Delete
  21. @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

    ReplyDelete
  22. I'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".

    I have checked and the Gmail account is synchronized but is always trying to check me out this error.

    Could someone give me a hand?

    ReplyDelete
  23. 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
  24. @author:hey amol....what is the ("AIzaXXXXXXXXXXXXXXXXXXXXXXXXX");?.In the devicesList.add("device_token_1"); what is device_token?

    ReplyDelete
    Replies
    1. it is the API key that you get from the google api console

      Delete
    2. hey amol......This gcm is not working on GPRS ,only work with WIFI???so whats the problem?

      Delete
    3. that is strange!
      Sometimes the notifications get delayed but a 100% failure is a strange issue.

      Delete
  25. Hi amol,

    I 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)

    ReplyDelete
  26. you need to check the internet connectivity on the machine. Probably your its your firewall blocking you or you are under a proxy.

    ReplyDelete
  27. Hi Amol,
    Thanks for ans,
    now should i change the proxy address.

    ReplyDelete
  28. Sir.
    I appreciate your work.
    when run the server code then show error in console view.
    Please reply me......

    ReplyDelete
    Replies
    1. Error on console view is:
      java.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)

      Delete
    2. I think its a known issue and there is nothing much you can do about it :(

      Delete
  29. I downloaded the codes from the tutorial and ran the client on my Samsung Galaxy SII, Android version 2.3.6.
    1) 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.

    ReplyDelete
  30. I downloaded the codes from the tutorial and ran the client on my Samsung Galaxy SII, Android version 2.3.6.

    1) 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.

    ReplyDelete
  31. Hi Amol,
    Nice 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.

    ReplyDelete
  32. thank you!
    Please post the exact issue that you are facing :)

    ReplyDelete
  33. Hi Amol,

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

    ReplyDelete
  34. please paste me full java server side code.

    ReplyDelete
    Replies
    1. Please follow the download link in the article to get the complete server and client side code :)

      Delete
    2. Hi Amol,
      I 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?

      Delete
  35. 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.

    ReplyDelete
  36. nice example.. and this is best resource. it works for me :-)

    ReplyDelete
  37. I 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...

    ReplyDelete
  38. Hi Amol,

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

    ReplyDelete
    Replies
    1. 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.

      Delete
    2. Hi Amol,

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

      Delete
    3. ohh...got it! You need to fix the buildpath and include the jar file provided in the lib folder.

      Delete
    4. It works now. Thanks so much.

      Delete
  39. Hi Amol,

    Can I send message from the client/mobile device to the 3rd party server? Any example codes?

    Please advise. Thanks

    ReplyDelete
    Replies
    1. Hi Amol,

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

      Delete
  40. Hi Amol,

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

    ReplyDelete
    Replies
    1. run the registration in and async task and update the textview on complete of the task.

      Delete
  41. Hi Amol,
    Nice 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

    ReplyDelete
  42. 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.
    OR
    If you are using an emulator, make sure the AVD is the one with Google APIs

    ReplyDelete
  43. we have a project with using GCM infrastructure.We want to control house automation system
    with 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?

    ReplyDelete
  44. Hi amol,
    I 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

    ReplyDelete
    Replies
    1. right click on the project name > Android Tools > Fix Project Properties.

      Delete
  45. Hello Amol,

    Some 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()?

    ReplyDelete
  46. Hey Amol,
    Thanx a lot.this help.
    But what if I want to use web instead of this java project?

    ReplyDelete
  47. Vaibhav,
    if u have a javaEE project then the same code can be used. There a several tut for integrating with php also.

    ReplyDelete
  48. hi amol i was able to get the reg id from gcm...and trying to write server side..
    as 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?

    ReplyDelete
    Replies
    1. 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.

      Delete
  49. Hi 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.

    ReplyDelete
  50. This comment has been removed by the author.

    ReplyDelete
  51. Hi, I am only getting the message Id [ messageId=0:1359960161967667%2a05dc7900000031 ] but the notification has not been delivering to device. Please advice..

    ReplyDelete
  52. i got it. I left my onMessage() blank.

    ReplyDelete
  53. i have this error :
    Could not find method org.json.simple.JSONValue.toJSONString, referenced from method com.google.android.gcm.server.Sender.sendNoRetry

    ReplyDelete
  54. 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) ?

    i.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?

    ReplyDelete
  55. Hi

    I 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


    ReplyDelete
    Replies
    1. Tushar,
      Please feel post any of your doubts here. Me and other readers would love to help you out :)

      Delete
  56. Will you please elaborate about how to run both application, I got Error in server side Application like "[ errorCode=InvalidRegistration ]"

    and in Client Side I got nothing.

    so please tell me about How to run step by step.

    ReplyDelete
  57. Hi Amol, Can U pls mail me the source code or working App folder to check this example to "aadarshgupta123@gmail.com"? Thanks!

    ReplyDelete
  58. However the code is running smoothinly. But why notification comes short ? Hardly one line ?
    And 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

    ReplyDelete
  59. Hi, i'm newBee in here and your post was a great start for me. So thanks a lot !
    Just, could you please give me some clarifications about the device_token in the devicesList.add() function and from where can i find them.
    Thanks !

    ReplyDelete
  60. Unable to get the notification on Device.. after running the Notify class with the RegId from logcat.
    Thanks in advance.

    ReplyDelete
  61. thanks for the post... its WORKING !!
    But how to connect my code to the server ???

    ReplyDelete