GCM java server example

2019-01-23 05:29发布

Does anyone have a link to GCM java 3rd Party Server example? I can't understand how to implement it. In http://developer.android.com/google/gcm/server.html, I could not find a complete example.

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-23 05:57

The easiest way is to use gcm-server.jar (which you can get from here).

Then the code you'll need to send a GCM message will look like this :

Sender sender = new Sender(apiKey);
Message message = new Message.Builder()
    .addData("message", "this is the message")
    .addData("other-parameter", "some value")
    .build();
Result result = sender.send(message, registrationId, numOfRetries);
查看更多
放荡不羁爱自由
3楼-- · 2019-01-23 06:09

I would like to share a more better approach which confirms message delivered successfully or not. We can do this using RestTemplate and HTTPPost.

I will show how we can do it using gcm.jar

public class GCMJarGCM {
    public static final String GCM_API_KEY = "Get this API key from Google Developer Console";
    public static final String MESSAGE_VALUE = "Hello, Sending Notifications using GCM";    
    public static final String MESSAGE_KEY = "message";
    public static final String REG_ID = "This you'll get once you register on GCM";

    public static void main(String[] args) throws IOException {
        Sender sender = new Sender(GCM_API_KEY);

        ArrayList<String> devicesList = new ArrayList<String>();
        devicesList.add(REG_ID);

        Message message = new Message.Builder().timeToLive(30)
                .delayWhileIdle(true).addData(MESSAGE_KEY, MESSAGE_VALUE).build();

        MulticastResult result = sender.send(message, devicesList, 1);
        sender.send(message, devicesList, 1);
        System.out.println(result.toString());
    }
}

The output you'll see like below:

MulticastResult(multicast_id=4951949299732552396,total=1,success=1,failure=0,canonical_ids=0,results: [[ messageId=0:1445408305351488%2a748ce7f9fd7ecd ]]

If you want to use HTTPPost or RestTemplate then you need to use EndPoint: https://android.googleapis.com/gcm/send

查看更多
登录 后发表回答