本文整理汇总了Java中com.google.android.gcm.server.Message.Builder方法的典型用法代码示例。如果您正苦于以下问题:Java Message.Builder方法的具体用法?Java Message.Builder怎么用?Java Message.Builder使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.android.gcm.server.Message
的用法示例。
在下文中一共展示了Message.Builder方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendGCMNotificationAsJson
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
public void sendGCMNotificationAsJson(String account, String registrationId, HashMap<String, Object> valueMap, String packageIdentifier) {
if (packageIdentifier == null || "".equals(packageIdentifier)) return;
// log.log(Level.WARNING, "gcm key " + ConfigurationManager.getValue(GCM_KEY+packageIdentifier));
// log.log(Level.WARNING, "packageIdentifier " + packageIdentifier);
// log.log(Level.WARNING, "regId " + registrationId);
Sender sender = new Sender(ConfigurationManager.getValue(GCM_KEY+packageIdentifier));
Message.Builder builder = new Message.Builder();
for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
builder.addData(entry.getKey(), "" + entry.getValue());
}
Message message = builder.build();
try {
Result result = sender.send(message, registrationId, 5);
log.log(Level.WARNING, "sent " + message.toString());
log.log(Level.WARNING, "result " + result);
} catch (IOException e) {
log.log(Level.SEVERE, "errr", e);
e.printStackTrace();
}
}
示例2: push
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
public final void push(String registrationId, String apiKey,
Map<String, Object> args, boolean delayWhileIdle)
throws IOException {
Sender sender = new Sender(apiKey);
Message.Builder builder = new Message.Builder();
builder.timeToLive(60 * 60).collapseKey("MAGIC_STRING")
.delayWhileIdle(delayWhileIdle);
for (String key : args.keySet()) {
builder.addData(key, "" + args.get(key));
}
Message message = builder.build();
Result result = sender.send(message, registrationId, 5);
if (result.getMessageId() != null) {
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration ID: update database
System.out
.println("same device has more than on registration ID: update database");
} else {
System.out.println("ok");
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister
// database
System.out
.println("application has been removed from device - unregister database");
}
System.out.println("ok 2: " + error);
}
}
示例3: sendAndroidInvitationNotification
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
/**
* Sends an invitation notification to Android devices.
*
* @param androidDevices the list of Android devices to send the notification to.
* @param invitee the Player who has been invited.
* @param invitationId the invitation id.
* @param gameId the game id.
* @param messageText invitationText to be sent.
* @throws IOException if an error occurred while sending Android push notifications.
*/
private void sendAndroidInvitationNotification(List<DeviceEntity> androidDevices,
PlayerEntity invitee, long invitationId, long gameId, String messageText) throws IOException {
Builder builder = new Message.Builder();
builder.addData("messageText", messageText);
builder.addData("invitationId", String.valueOf(invitationId));
builder.addData("gameId", String.valueOf(gameId));
builder.addData("playerId", String.valueOf(invitee.getId()));
builder.addData("nickName", invitee.getNickname());
Message message = builder.build();
AndroidNotificationService notificationService = new AndroidNotificationService();
notificationService.sendMessage(androidDevices, message, invitee.getKey());
}
开发者ID:GoogleCloudPlatform,项目名称:solutions-griddler-sample-backend-java,代码行数:24,代码来源:InvitationService.java
示例4: process
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
@Override
public void process(Exchange exchange) throws Exception {
final GcmConfiguration configuration = getEndpoint().getConfiguration();
final Sender sender = new Sender(configuration.getApiKey());
final Message.Builder messageBuilder = new Message.Builder();
final String collapseKey = configuration.getCollapseKey();
if (collapseKey != null) {
messageBuilder.collapseKey(collapseKey);
}
final Integer timeToLive = configuration.getTimeToLive();
if (timeToLive != null) {
messageBuilder.timeToLive(timeToLive.intValue());
}
final Boolean delayWhileIdle = configuration.isDelayWhileIdle();
if (delayWhileIdle != null) {
messageBuilder.delayWhileIdle(delayWhileIdle.booleanValue());
}
final String restrictedPackageName = configuration.getRestrictedPackageName();
if (restrictedPackageName != null) {
messageBuilder.restrictedPackageName(restrictedPackageName);
}
final Boolean dryRun = configuration.isDryRun();
if (dryRun != null) {
messageBuilder.dryRun(dryRun.booleanValue());
}
final Object bodyObject = exchange.getIn().getBody();
if (bodyObject instanceof String) {
messageBuilder.addData(configuration.getStringBodyDataKey(), (String) bodyObject);
} else {
@SuppressWarnings("unchecked")
final Map<Object, Object> map = exchange.getIn().getBody(Map.class);
if (map != null) {
for (Map.Entry<Object, Object> entry : map.entrySet()) {
final Object key = entry.getKey();
final Object value = entry.getValue();
if (key != null && value != null) {
messageBuilder.addData(key.toString(), value.toString());
}
}
}
}
final Message message = messageBuilder.build();
final int retries = configuration.getRetries();
String to = exchange.getIn().getHeader(GcmConstants.TO, String.class);
if (to == null) {
to = getEndpoint().getName();
}
final Result result;
if (retries == 0) {
LOG.trace("Sending message [{}] from exchange [{}] to [{}] with no retries...",
new Object[] { message, exchange, to });
result = sender.sendNoRetry(message, to);
} else {
LOG.trace("Sending message [{}] from exchange [{}] to [{}] with {} retries...",
new Object[] { message, exchange, to, retries });
result = sender.send(message, to, retries);
}
LOG.trace("Received result [{}]", result);
}
示例5: sendOverGCM
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
private static void sendOverGCM(final String fromRegistrationId,
final String toRegistrationId, final String expressionId,
final String action, final String data) {
Sender sender = new Sender(SwanGCMConstants.API_KEY);
Message.Builder builder = new Message.Builder();
builder.timeToLive(60 * 60).collapseKey("MAGIC_STRING")
.delayWhileIdle(true);
if (fromRegistrationId != null) {
// from is not allowed and results in InvalidDataKey, see:
// http://developer.android.com/google/gcm/gcm.html
builder.addData("source", fromRegistrationId);
}
builder.addData("action", action);
builder.addData("data", data);
builder.addData("id", expressionId);
Message message = builder.build();
try {
Result result = sender.send(message, toRegistrationId, 5);
if (result.getMessageId() != null) {
String canonicalRegId = result
.getCanonicalRegistrationId();
if (canonicalRegId != null) {
Log.d(TAG,
"same device has more than on registration ID: update database");
} else {
Log.d(TAG,
"successfully sent push message for id: "
+ expressionId + ", type: "
+ action + ", data: " + data);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
Log.d(TAG,
"application has been removed from device - unregister database");
} else {
Log.d(TAG, "no message id, error: " + error);
}
}
} catch (IOException e) {
Log.d(TAG,
"failed to deliver push message: " + e.toString());
}
}
示例6: sendGcmMessageToUser
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
/**
* Sends a gcm message to a specific user passing a certain message type and multiple messages with it
* @param receiver the user that should receive the messageu
* @param messageType the type of the message (see {@link org.croudtrip.api.gcm.GcmConstants})
* @param messageData multiple instances {@link org.croudtrip.utils.Pair} that contain several messages that should be sent with the gcm
* @throws IOException IOException if the connection to Google was not successful and msg could not be sent
* @throws java.lang.IllegalArgumentException if the receiver is not valid or not registered.
*/
public void sendGcmMessageToUser(User receiver, String messageType, Pair<String, String>... messageData) {
try {
if (receiver == null) {
logManager.e("SendToUser failed, because user is null");
return;
// throw new IllegalStateException("Receiver not specified");
}
GcmRegistration gcmRegistration = findRegistrationByUser(receiver).orNull();
if (gcmRegistration == null) {
logManager.e("User " + receiver.getId() + " (" + receiver.getFirstName() + " " + receiver.getLastName() + ") is not registered.");
return;
// throw new IllegalStateException("Receiver is not registered");
}
final List<String> devices = new ArrayList<>();
devices.add(gcmRegistration.getGcmId());
// send
Message.Builder builder = new Message.Builder();
builder.addData(GcmConstants.GCM_TYPE, messageType);
for (Pair<String, String> p : messageData)
builder.addData(p.getKey(), p.getValue());
MulticastResult multicastResult = sender.send(builder.build(), devices, 5);
// analyze the results
List<Result> results = multicastResult.getResults();
for (int i = 0; i < devices.size(); i++) {
String gcmId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
logManager.d("send msg to " + gcmId + " with msg id " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
// update gcm id
if (canonicalRegId != null) {
logManager.i("updating gcmId from " + gcmId + " to " + canonicalRegId);
register(gcmRegistration.getUser(), new GcmRegistrationDescription(canonicalRegId));
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
unregister(gcmRegistration);
} else {
// unknown error
logManager.e("unknown gcm error " + error);
}
}
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
示例7: sendPayloadToDevices
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
/**
* Handles sending cloud notifications to devices
*
* @param payload
* @param registrationIds
* @return MulticastResult of delivered notifications
*/
private MulticastResult sendPayloadToDevices(String jsonPayload,
String[] registrationIds) {
Message.Builder builder = new Message.Builder();
try {
// Rebuild JSON payload
JSONObject json = new JSONObject(jsonPayload);
// builder.addData("content_available", "true");
String purpose = json.getString("purpose");
builder.addData("purpose", purpose);
if (purpose.equals("zeppaNotification")) {
builder.addData("id",json.getString("id"));
builder.addData("title", json.getString("title"));
builder.addData("message", json.getString("message"));
builder.addData("type", json.getString("type"));
builder.addData("expires", json.getString("expires"));
if (json.getString("eventId").equals("-1")) {
builder.collapseKey(json.getString("senderId"));
} else {
builder.collapseKey(json.getString("eventId"));
}
} else if (purpose.equals("userRelationshipDeleted")) {
builder.addData("senderId", json.getString("senderId"));
builder.addData("recipientId", json.getString("recipientId"));
} else if (purpose.equals("eventDeleted")) {
builder.addData("eventId", json.getString("eventId"));
builder.collapseKey(json.getString("eventId"));
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
Message message = builder.build();
MulticastResult result = cloudMessagingSender.sendMessageToDevice(
message, registrationIds);
// try {
// List<Result> results = result.getResults();
// for (Result r : results) {
// r.getCanonicalRegistrationId();
// }
//
// } catch (NullPointerException e) {
// // result == null
// }
return result;
}
示例8: sendMsg
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
public GcmResult sendMsg(String gcmId, Map<String, String> payload) {
final List<String> devices = new ArrayList<String>();
devices.add(gcmId);
// send
Message.Builder builder = new Message.Builder();
for (Map.Entry<String, String> e : payload.entrySet()) {
builder.addData(e.getKey(), e.getValue());
}
MulticastResult multicastResult;
try {
multicastResult = sender.send(builder.build(), devices, 5);
} catch (IOException io) {
return new GcmResult.Builder().exception(io).build();
}
// analyze the results
List<Result> results = multicastResult.getResults();
for (int i = 0; i < devices.size(); i++) {
String regId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
Log.info("Succesfully sent message to device: "
+ regId + "; messageId = " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
return new GcmResult.Builder().newGcmId(canonicalRegId).build();
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
return new GcmResult.Builder().notRegistered().build();
} else {
return new GcmResult.Builder().errorMsg(error).build();
}
}
}
return new GcmResult.Builder().build();
}
示例9: sendPushMessage
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
/**
* Sends FCM notifications ({@link UnifiedPushMessage}) to all devices, that are represented by
* the {@link List} of tokens for the given {@link AndroidVariant}.
*/
@Override
public void sendPushMessage(Variant variant, Collection<String> tokens, UnifiedPushMessage pushMessage, String pushMessageInformationId, NotificationSenderCallback callback) {
// no need to send empty list
if (tokens.isEmpty()) {
return;
}
final List<String> pushTargets = new ArrayList<>(tokens);
final AndroidVariant androidVariant = (AndroidVariant) variant;
// payload builder:
Builder fcmBuilder = new Message.Builder();
org.jboss.aerogear.unifiedpush.message.Message message = pushMessage.getMessage();
// add the "recognized" keys...
fcmBuilder.addData("alert", message.getAlert());
fcmBuilder.addData("sound", message.getSound());
fcmBuilder.addData("badge", String.valueOf(message.getBadge()));
/*
The Message defaults to a Normal priority. High priority is used
by FCM to wake up devices in Doze mode as well as apps in AppStandby
mode. This has no effect on devices older than Android 6.0
*/
fcmBuilder.priority(
message.getPriority() == Priority.HIGH ?
Message.Priority.HIGH :
Message.Priority.NORMAL
);
// if present, apply the time-to-live metadata:
int ttl = pushMessage.getConfig().getTimeToLive();
if (ttl != -1) {
fcmBuilder.timeToLive(ttl);
}
// iterate over the missing keys:
message.getUserData().keySet()
.forEach(key -> fcmBuilder.addData(key, String.valueOf(message.getUserData().get(key))));
//add the aerogear-push-id
fcmBuilder.addData(InternalUnifiedPushMessage.PUSH_MESSAGE_ID, pushMessageInformationId);
Message fcmMessage = fcmBuilder.build();
// send it out.....
try {
logger.debug("Sending transformed FCM payload: {}", fcmMessage);
final ConfigurableFCMSender sender = new ConfigurableFCMSender(androidVariant.getGoogleKey());
// send out a message to a batch of devices...
processFCM(androidVariant, pushTargets, fcmMessage , sender);
logger.debug("Message batch to FCM has been submitted");
callback.onSuccess();
} catch (Exception e) {
// FCM exceptions:
callback.onError(String.format("Error sending payload to FCM server: %s", e.getMessage()));
}
}
示例10: onNewDataComplete
import com.google.android.gcm.server.Message; //导入方法依赖的package包/类
@Override
public void onNewDataComplete() {
// gather data
Map<String,String> payload = new HashMap<>();
payload.put(DATA_KEY_SOURCE, source.getId());
payload.put(DATA_KEY_DEBUG, Boolean.TRUE.toString());
String collapseKey = source.getId();
final List<String> devices = new ArrayList<>();
devices.add(client.getGcmClientId());
// send
Message.Builder builder = new Message.Builder().collapseKey(collapseKey);
for (Map.Entry<String, String> e : payload.entrySet()) {
builder.addData(e.getKey(), e.getValue());
}
MulticastResult multicastResult;
try {
multicastResult = gcmSender.send(builder.build(), devices, 5);
} catch (IOException io) {
setErrorResult(io);
return;
}
// analyze the results
List<Result> results = multicastResult.getResults();
for (int i = 0; i < devices.size(); i++) {
String regId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
Log.info("Succesfully sent message to device: "
+ regId + "; messageId = " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
setUpdateClientResult(
client,
new GcmClient(client.getId(), canonicalRegId));
return;
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
setRemoveClientResult(client);
return;
} else {
setErrorResult(error);
return;
}
}
}
setSuccessResult();
}