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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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);
回答2:
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