本文整理汇总了Java中com.google.android.gcm.server.MulticastResult.getResults方法的典型用法代码示例。如果您正苦于以下问题:Java MulticastResult.getResults方法的具体用法?Java MulticastResult.getResults怎么用?Java MulticastResult.getResults使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.android.gcm.server.MulticastResult
的用法示例。
在下文中一共展示了MulticastResult.getResults方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendGcmMessageToUser
import com.google.android.gcm.server.MulticastResult; //导入方法依赖的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);
}
}
示例2: sendMsg
import com.google.android.gcm.server.MulticastResult; //导入方法依赖的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();
}
示例3: cleanupInvalidRegistrationIDsForVariant
import com.google.android.gcm.server.MulticastResult; //导入方法依赖的package包/类
/**
* <p>Walks over the {@code MulticastResult} from the FCM call and identifies the <code>index</code> of all {@code Result} objects that
* indicate an <code>InvalidRegistration</code> error.
*
* <p>This <code>index</code> is used to find the matching <code>registration ID</code> in the List of all used <code>registrationIDs</code>.
*
* <p>Afterwards all 'invalid' registration IDs for the given <code>variantID</code> are being deleted from our database.
*
* @param variantID id of the actual {@code AndroidVariantEntity}.
* @param multicastResult the results from the HTTP request to the Google Cloud.
* @param registrationIDs list of all tokens that we submitted to FCM.
*/
private void cleanupInvalidRegistrationIDsForVariant(String variantID, MulticastResult multicastResult, List<String> registrationIDs) {
// get the FCM send results for all of the client devices:
final List<Result> results = multicastResult.getResults();
// storage for all the invalid registration IDs:
final Set<String> inactiveTokens = new HashSet<>();
// read the results:
for (int i = 0; i < results.size(); i++) {
// use the current index to access the individual results
final Result result = results.get(i);
final String errorCodeName = result.getErrorCodeName();
if (errorCodeName != null) {
logger.info(String.format("Processing [%s] error code from FCM response, for registration ID: [%s]", errorCodeName, registrationIDs.get(i)));
}
//after sending, lets find tokens that are inactive from now on and need to be replaced with the new given canonical id.
//according to fcm documentation, google refreshes tokens after some time. So the previous tokens will become invalid.
//When you send a notification to a registration id which is expired, for the 1st time the message(notification) will be delivered
//but you will get a new registration id with the name canonical id. Which mean, the registration id you sent the message to has
//been changed to this canonical id, so change it on your server side as well.
//check if current index of result has canonical id
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than one registration id: update it, if needed!
// let's see if the canonical id is already in our system:
Installation installation = clientInstallationService.findInstallationForVariantByDeviceToken(variantID, canonicalRegId);
if (installation != null) {
// ok, there is already a device, with newest/latest registration ID (aka canonical id)
// It is time to remove the old reg id, to avoid duplicated messages in the future!
inactiveTokens.add(registrationIDs.get(i));
} else {
// since there is no registered device with newest/latest registration ID (aka canonical id),
// this means the new token/regId was never stored on the server. Let's update the device and change its token to new canonical id:
installation = clientInstallationService.findInstallationForVariantByDeviceToken(variantID,registrationIDs.get(i));
installation.setDeviceToken(canonicalRegId);
//update installation with the new token
logger.info(String.format("Based on returned canonical id from FCM, updating Android installations with registration id [%s] with new token [%s] ", registrationIDs.get(i), canonicalRegId));
clientInstallationService.updateInstallation(installation);
}
} else {
// is there any 'interesting' error code, which requires a clean up of the registration IDs
if (FCM_ERROR_CODES.contains(errorCodeName)) {
// Ok the result at INDEX 'i' represents a 'bad' registrationID
// Now use the INDEX of the _that_ result object, and look
// for the matching registrationID inside of the List that contains
// _all_ the used registration IDs and store it:
inactiveTokens.add(registrationIDs.get(i));
}
}
}
if (! inactiveTokens.isEmpty()) {
// trigger asynchronous deletion:
logger.info(String.format("Based on FCM response data and error codes, deleting %d invalid or duplicated Android installations", inactiveTokens.size()));
clientInstallationService.removeInstallationsForVariantByDeviceTokens(variantID, inactiveTokens);
}
}
示例4: onNewDataComplete
import com.google.android.gcm.server.MulticastResult; //导入方法依赖的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();
}
示例5: pushAll
import com.google.android.gcm.server.MulticastResult; //导入方法依赖的package包/类
/**
* This accepts a message and persists it in the AppEngine datastore, it will also broadcast the
* message to upto 10 registered android devices via Google Cloud Messaging
*
* @param message the entity to be inserted.
* @return
* @throws IOException
*/
@Override
@ApiMethod(path = "pushAllToGcm")
public void pushAll(@Named("documentId") String docId, @Named("messageType") String messageType,
@Named("message") String message) {
// Trim message if needed.
if (message.length() > 1000) {
log.warning(docId + ": Message too large (" + message.length() + " chars), not publishing: "
+ message);
return;
}
Sender sender = new Sender(API_KEY);
// ping a max of 10 registered devices
Set<String> subscriptions = presence.listDocumentSubscriptions(docId, Platform.ANDROID.name());
if (subscriptions == null || subscriptions.isEmpty()) {
return;
}
List<String> ids = new ArrayList<String>();
for (String subscription : subscriptions) {
String token = util.get().channelTokenFor(subscription);
if (token == null) {
continue;
}
ids.add(token);
}
if (ids.isEmpty()) {
return;
}
MulticastResult results = null;
try {
Message msg = new Message.Builder().addData(messageType, message).timeToLive(0).build();
results = sender.sendNoRetry(msg, ids);
} catch (IOException e) {
log.log(Level.SEVERE, "Error when send message to Google Cloud Messaging Service", e);
return;
}
if (results.getFailure() == 0 && results.getCanonicalIds() == 0) {
return;
}
int i = 0;
for (Result result : results.getResults()) {
if (result.getMessageId() != null) {
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
DeviceInfo deviceInfo = endpoint.getDeviceInfo(ids.get(i));
endpoint.removeDeviceInfo(ids.get(i));
deviceInfo.setId(canonicalRegId);
endpoint.insertDeviceInfo(deviceInfo);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
endpoint.removeDeviceInfo(ids.get(i));
} else {
log.log(Level.WARNING, "Error occur when trying to send a message to android device:"
+ ids.get(i));
}
}
i++;
}
}
示例6: sendWholeCompletionNotification
import com.google.android.gcm.server.MulticastResult; //导入方法依赖的package包/类
/**
* An entirely "fire and forget" function used to inform clients of a
* DataWholes completion. It will attempt a retry of 5 times but will not
* attempt any further validation apart from any Canonical IDs sent back
* from GCM. These IDs must be updated to reflect GCM's DB.
*
* @param {@link DataWhole} to inform clients about
* @param {@link List} of {@link DeviceInfo} objects that contain device
* registration IDs
*/
public static void sendWholeCompletionNotification(final DataWhole dataWhole) {
if (null != dataWhole) {
logger.log(Level.INFO, "Sending GCM completion message for DataWhole " + dataWhole.getKey());
Sender sender = new Sender(Constants.GCM_API_KEY);
Message message = buildCompletionMessage(dataWhole);
final Collection<DeviceInfo> devices = ofy().load().keys(dataWhole.getDeviceInfoKeyList()).values();
final List<String> deviceRegistrations = new ArrayList<String>(devices.size());
for (DeviceInfo device : devices) {
deviceRegistrations.add(device.toString());
}
try {
MulticastResult multicastResult = sender.send(message, deviceRegistrations, 5);
/* An error has occurred */
if (deviceRegistrations.size() != multicastResult.getSuccess()) {
Iterator<DeviceInfo> deviceIter = devices.iterator();
for (Result result : multicastResult.getResults()) {
DeviceInfo deviceInfo = deviceIter.next();
if (null != result.getMessageId()) {
if (null != result.getCanonicalRegistrationId()) {
/*
* Update the DeviceInfo with the new ID and
* post to DB
*/
deviceInfo.setDeviceRegistrationId(result.getCanonicalRegistrationId());
deviceEndpoint.updateDeviceInfo(deviceInfo);
logger.log(Level.INFO, "Updated device with new GCM ID: " + deviceInfo);
}
} else {
logger.log(Level.WARNING, "GCM returned result " + result.getErrorCodeName());
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
示例7: sendPieceRequest
import com.google.android.gcm.server.MulticastResult; //导入方法依赖的package包/类
public static void sendPieceRequest(final DataPiece dataPiece, final DataWhole dataWhole) {
if (null != dataPiece && null != dataWhole) {
logger.log(Level.INFO, "Sending GCM completion message for DataWhole " + dataPiece.getKey());
Sender sender = new Sender(Constants.GCM_API_KEY);
Message message = buildRequestMessage(dataWhole, dataPiece);
final Collection<DeviceInfo> devices = ofy().load().keys(dataWhole.getDeviceInfoKeyList()).values();
final List<String> deviceRegistrations = new ArrayList<String>(devices.size());
for (DeviceInfo device : devices) {
deviceRegistrations.add(device.toString());
logger.log(Level.INFO, "Sending request to Device " + device.getServerRegistrationId());
}
try {
MulticastResult multicastResult = sender.send(message, deviceRegistrations, 5);
/* An error has occurred */
if (deviceRegistrations.size() != multicastResult.getSuccess()) {
Iterator<DeviceInfo> deviceIter = devices.iterator();
for (Result result : multicastResult.getResults()) {
DeviceInfo deviceInfo = deviceIter.next();
if (null != result.getMessageId()) {
if (null != result.getCanonicalRegistrationId()) {
/*
* Update the DeviceInfo with the new ID and
* post to DB
*/
deviceInfo.setDeviceRegistrationId(result.getCanonicalRegistrationId());
deviceEndpoint.updateDeviceInfo(deviceInfo);
logger.log(Level.INFO, "Updated device with new GCM ID: " + deviceInfo);
}
} else {
logger.log(Level.WARNING, "GCM returned result " + result.getErrorCodeName());
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}