2

I am creating a project on Google Cloud Messaging (GCM) and am following this tutorial.

I am done with the client-side work and set up the device on the client side. Also I had registered the device using the following code.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    final String regId = GCMRegistrar.getRegistrationId(this);
    if (regId.equals("")) {
        GCMRegistrar.register(this, "483910217912");
        Log.d(tag, "Registered");
    }
    else {
        Log.v(tag, "Already registered");
    }
}

Now I am stuck at a point to create server for my GCM project. Note that I am creating a project to notify when a new message is received. However, I had not implemented the service to receive a message, but I will implement it when the server setting is finished.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100

6 Answers6

6

You can create a GCM server in Android using the blog post Google cloud Messaging (GCM) tutorial , but I would prefer to use PHP for server side code. You can create a GCM Server in cURL (PHP) in easy steps:

  1. Create a server key from the Google API console page.

  2. Identify the device token of a device for which this message is sent to.

You can find the easy steps in How to implement a GCM PHP push server for Android to implement the push server.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AppMobiGurmeet
  • 719
  • 3
  • 6
5

you can use this code

package yourpackage.android.gcm.server;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;

import java.util.ArrayList;

class Notify {
    public static void main(String args[]) {

        try {

            Sender sender = new Sender("AIzaSyCn3N2OIm-EDtiGwTyQfSIB8NRvDtIOx30");

            ArrayList<String> devicesList = new ArrayList<String>();
//add you deviceID
            devicesList.add("APA91bELVJbxB_NLnLbTkkkX87SDdkJc6OfCN2slhC9t4cLq-KA32eGgiW4-Gi--ZEsEMKIh0AtYJMs5rQGswfm3cH1qK853WcpV98bkaplAaC5AiycDmifuVFSRl21vgf-Rqj0dCrFF");
                        //devicesList.add("APA91bHIdM4XGqrjJLTuwCX5OOrTYG4ACXYEVkZDM1bPs5qFdzJP4Bpql-sZqyKB8BU7fDtdxB84aTygHLyASYg_XNY6lqrcA4wj4sZHJXGVFzz_0UEADMfFCx9NAfRZxunIYso_dkBa");
            //APA91bFA-i2l3iEMnIBs0JK80pTLHOsE7p1s-DysRpKGas1MQOVILyIs9xwY7soysSWGz5Uif68uXR6F5Xn0tCTYesv78uQZxhC310a1cvf8aFohhfMGY6awbOSg3t1GRz2i3U-8kVSF
            // Use this line to send message without payload data
            // Message message = new Message.Builder().build();

            // use this line to send message with payload data
            Message message = new Message.Builder()
                    //.collapseKey("message")
                    //.timeToLive(241000)
                    .delayWhileIdle(true)
                    .addData("message", "Your message send")
                    .build();


                   /**/
            // Use this code to send to a single device
            // Result result = sender
            // .send(message,
            // "APA91bGiRaramjyohc2lKjAgFGpzBwtEmI8tJC30O89C2b3IjP1CuMeU1h9LMjKhmWuZwcXZjy1eqC4cE0tWBNt61Kx_SuMF6awzIt8WNq_4AfwflaVPHQ0wYHG_UX3snjp_U-5kJkmysdRlN6T8xChB1n3DtIq98w",
            // 1);

            // Use this for multicast messages
            MulticastResult result = sender.send(message, devicesList, 1);
            //sender.send(message, devicesList, 0);

            System.out.println(result.toString());
            if (result.getResults() != null) {
                int canonicalRegId = result.getCanonicalIds();
                if (canonicalRegId != 0) {
                }
            } else {
                int error = result.getFailure();
                System.out.println(error);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
Jamshid
  • 340
  • 3
  • 12
  • thanx, it will definitely help me in the later part of the project to send messages. but now the point of concern is _how to create a server for the project_ . – Sahil Mahajan Mj Oct 11 '12 at 10:04
  • if i use this server side as android application ,, Does i need to merge the classes (client , server) together in one package ?? ----- And What is the best for the server side (Asp.net or this one) ?? – Loai Dec 15 '12 at 14:51
5

The com.google.android.gcm.server library is deprecated. Just encode your message to JSON object and POST it to GCM URL https://android.googleapis.com/gcm/send

JSON example:

 {
   "registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",...],
   "data" : {
     "Team" : "Portugal",
     "Score" : "3",
     "Player" : "Varela",
   },
 }

Here is more http://developer.android.com/google/gcm/http.html

Max
  • 4,292
  • 1
  • 20
  • 14
4

You can find sample code for gcm-client and gcm-server in the Android SDK directory. It is good point to get started. Directory is :

path_to_android_sdk/extras/google/gcm/samples

Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
  • I have created the client side app. but how to use the gcm-demo-server from the android samples. do i need to import the project to the netbeans. Also if there some requirements to install the server engine. – Sahil Mahajan Mj Oct 12 '12 at 10:35
  • use this tutorial to set up server side code.http://developer.android.com/guide/google/gcm/demo.html#server-setup – Parvin Gasimzade Oct 12 '12 at 10:40
  • i have gone through it. but i could not understand the 3rd and the 4th point. – Sahil Mahajan Mj Oct 12 '12 at 10:44
  • these steps is used to generate .war file in order to run it on the application server. Do you have server side experience? Otherwise it will be hard to develop it. – Parvin Gasimzade Oct 12 '12 at 10:51
  • I have studies about servelets a bit, though i dont have experience in developing server side applications. – Sahil Mahajan Mj Oct 12 '12 at 12:01
  • @parvin will u please explain where i will get the code path_to_android_sdk/extras/google/gcm/samples i am not getting this – Developer Sep 02 '13 at 07:03
  • @Gaurav You can find the code in the Android SDK directory.First find the directory where you installed Android SDK and inside it you can see the extras folder. – Parvin Gasimzade Sep 02 '13 at 07:09
  • fine thanks i got that. what i have to do on server side ..how i will broadcast the msg from there – Developer Sep 02 '13 at 07:14
  • 1
    I have downloaded the latest ADT (64) for Windows but this folder does not exist. Did they remove this? – ampofila Feb 25 '14 at 13:33
3
In your main function implement following code to send push notification to your app

final String apiKey = "specify your  api key generated by gcm";

To make http connection to gcm using following code

 URL url = new URL("https://android.googleapis.com/g...");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key="+apiKey);

        conn.setDoOutput(true);

JSON message format accepted by GCM

String input = "{\"registration_ids\" : [\"Specify token you got from GCM\"],\"data\" : {\"message\": \"hai  welcome\"},}";

To send notification

OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

In your client app you need to have proper BroadcastReceiver  class to receive the message sent from GCM
sathis
  • 251
  • 1
  • 3
  • 9
2

I would insist you to test the demo that is being provided on the develpers site. I had just created a demo sample based on that with all the steps that one should follow for executing the demo sample. You can check my blog and also find the source from my github.

Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242