Sahil Mahajan Mj
Sahil Mahajan Mj

Reputation: 11141

How to create server for GCM project in Android

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.

Upvotes: 2

Views: 18719

Answers (6)

Max
Max

Reputation: 4620

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

Upvotes: 5

sathis
sathis

Reputation: 251

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

Upvotes: 3

AppMobiGurmeet
AppMobiGurmeet

Reputation: 719

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.

Upvotes: 6

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

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

Upvotes: 4

Jamshid
Jamshid

Reputation: 340

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

    }
}

Upvotes: 5

Lalit Poptani
Lalit Poptani

Reputation: 67286

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.

Upvotes: 2

Related Questions