Back to project page droidBBpush.
The source code is released under:
This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a co...
If you think the Android project droidBBpush listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.arg3.examples.push; // ww w. j av a2 s. c o m import com.arg3.examples.push.model.Device; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.util.List; import javax.inject.Inject; /** * Created by c0der78 on 2014-09-25. */ public class AndroidPushService { // The SENDER_ID here is the "Browser Key" that was generated when I // created the API keys for my Google APIs project. private static final String SENDER_ID = "YOUR_SENDER_ID"; @Inject AndroidPushService() { } public boolean sendMessage(Device device, String messageText) { // Instance of com.android.gcm.server.Sender, that does the // transmission of a Message to the Google Cloud Messaging service. Sender sender = new Sender(SENDER_ID); // This Message object will hold the data that is being transmitted // to the Android client devices. For this demo, it is a simple text // string, but could certainly be a JSON object. Message message = new Message.Builder() .timeToLive(30) .delayWhileIdle(true) .addData("message", messageText) .build(); try { Result result = sender.send(message, device.getToken(), 1); if (result != null) { String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { return true; } } else { String error = result.getErrorCodeName(); System.out.println("Broadcast failure: " + error); } } catch (Exception e) { e.printStackTrace(); } return false; } public boolean sendMessage(List<String> tokens, String messageText) { // Instance of com.android.gcm.server.Sender, that does the // transmission of a Message to the Google Cloud Messaging service. Sender sender = new Sender(SENDER_ID); // This Message object will hold the data that is being transmitted // to the Android client devices. For this demo, it is a simple text // string, but could certainly be a JSON object. Message message = new Message.Builder() .timeToLive(30) .delayWhileIdle(true) .addData("message", messageText) .build(); try { MulticastResult result = sender.send(message, tokens, 1); if (result != null && result.getResults() != null) { int canonicalRegId = result.getCanonicalIds(); if (canonicalRegId > 0) { return true; } } else { int error = result.getFailure(); System.out.println("Broadcast failure: " + error); } } catch (Exception e) { e.printStackTrace(); } return false; } }