当前位置: 首页>>代码示例>>Java>>正文


Java MulticastResult类代码示例

本文整理汇总了Java中com.google.android.gcm.server.MulticastResult的典型用法代码示例。如果您正苦于以下问题:Java MulticastResult类的具体用法?Java MulticastResult怎么用?Java MulticastResult使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


MulticastResult类属于com.google.android.gcm.server包,在下文中一共展示了MulticastResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: sendMessageToDevice

import com.google.android.gcm.server.MulticastResult; //导入依赖的package包/类
public MulticastResult sendMessageToDevice(Message message, String[] registrationIds) {

		// Build the message
		MulticastResult result = null;

		// Quick convert array to list
		List<String> registrationIdsList = new ArrayList<String>();
		for (int i = 0; i < registrationIds.length; i++)
			registrationIdsList.add(registrationIds[i]);

		try {
			result = sender.sendNoRetry(message, registrationIdsList);
			int success = result.getSuccess();
			int failed = result.getFailure();

			LOG.warning("Sent cloud messages: " + success + " Success/ " + failed + " Failed");

		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}
 
开发者ID:pschuette22,项目名称:Zeppa-AppEngine,代码行数:24,代码来源:CloudMessagingSender.java

示例2: processFCM

import com.google.android.gcm.server.MulticastResult; //导入依赖的package包/类
/**
 * Process the HTTP POST to the FCM infrastructure for the given list of registrationIDs.
 */
private void processFCM(AndroidVariant androidVariant, List<String> pushTargets, Message fcmMessage, ConfigurableFCMSender sender) throws IOException {


    // push targets can be registration IDs OR topics (starting /topic/), but they can't be mixed.
    if (pushTargets.get(0).startsWith(Constants.TOPIC_PREFIX)) {

        // perform the topic delivery

        for (String topic : pushTargets) {
            logger.info(String.format("Sent push notification to FCM topic: %s", topic));
            Result result = sender.sendNoRetry(fcmMessage, topic);

            logger.trace("Response from FCM topic request: {}", result);
        }
    } else {
        logger.info(String.format("Sent push notification to FCM Server for %d registrationIDs", pushTargets.size()));
        MulticastResult multicastResult = sender.sendNoRetry(fcmMessage, pushTargets);

        logger.trace("Response from FCM request: {}", multicastResult);

        // after sending, let's identify the inactive/invalid registrationIDs and trigger their deletion:
        cleanupInvalidRegistrationIDsForVariant(androidVariant.getVariantID(), multicastResult, pushTargets);
    }
}
 
开发者ID:aerogear,项目名称:aerogear-unifiedpush-server,代码行数:28,代码来源:FCMPushNotificationSender.java

示例3: notifyAlert

import com.google.android.gcm.server.MulticastResult; //导入依赖的package包/类
public static void notifyAlert(MobileClient publisher, GlucoseAlert alert,
		List<String> subGcmTokens) throws IOException {
	
	Sender sender = new Sender(API_KEY);
	Message msg = new Message.Builder()
			.addData(MESSAGE_TYPE, ALERT_NOTIFICATION)
			.addData(PUBLISHER_ID, publisher.getId() + "")
			.addData(PUBLISHER_USERNAME, publisher.getUsername())
			.addData(ALERT_TYPE, alert.getType().toString())
			.addData(ALERT_TIMESTAMP, alert.getTimestamp() + "")
			.build();
	MulticastResult result = sender.sendNoRetry(msg, subGcmTokens);
	System.out.println(msg.toString());
	System.out.println(result.toString());	
}
 
开发者ID:kflauri2312lffds,项目名称:Android_watch_magpie,代码行数:16,代码来源:GcmSender.java

示例4: send

import com.google.android.gcm.server.MulticastResult; //导入依赖的package包/类
@Override
public MulticastResult send(Message message, List<String> regIds, int retries) throws IOException {
  count++;
  //can't build a MulticastResult.
  //MulticastResult result =  new MulticastResult();
  return null;
}
 
开发者ID:magnetsystems,项目名称:message-server,代码行数:8,代码来源:GCMPushMessageSenderTest.java

示例5: sendMessage

import com.google.android.gcm.server.MulticastResult; //导入依赖的package包/类
/**
 * Sends a message to Android devices.
 *
 * @param devices the list of devices that the notification is sent to.
 * @param message the message to be sent.
 * @param playerKey the key of the player that the notification is sent to.
 * @throws IOException if there was IOException thrown by Google Cloud Messaging for Android.
 */
protected void sendMessage(List<DeviceEntity> devices, Message message, Key playerKey)
    throws IOException {
  List<String> androidDeviceIds = new ArrayList<String>();
  for (DeviceEntity device : devices) {
    androidDeviceIds.add(device.getDeviceId());
  }

  Sender messageSender = new Sender(Configuration.CLOUD_MESSAGING_API_KEY);
  MulticastResult messageResults =
      messageSender.send(message, androidDeviceIds, NUMBER_OF_RETRIES);

  if (messageResults != null) {
    DeviceService deviceService = new DeviceService();

    for (int i = 0; i < messageResults.getTotal(); i++) {
      Result result = messageResults.getResults().get(i);

      if (result.getMessageId() != null) {
        String canonicalRegId = result.getCanonicalRegistrationId();
        if (canonicalRegId != null) {
          deviceService.updateDeviceRegistration(devices.get(i), canonicalRegId);
        }
      } else {
        String error = result.getErrorCodeName();
        if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
          // The user has uninstalled the application or turned off notifications.
          // Remove the device from Griddler.
          deviceService.unregisterDevice(playerKey, devices.get(i).getKey());
        } else {
          logger.log(Level.INFO, "Error when sending Android push notification: " + error);
        }
      }
    }
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:solutions-griddler-sample-backend-java,代码行数:44,代码来源:AndroidNotificationService.java

示例6: 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);
}
  }
 
开发者ID:AMOS-2015,项目名称:amos-ss15-proj2,代码行数:68,代码来源:GcmManager.java

示例7: sendPayloadToDevices

import com.google.android.gcm.server.MulticastResult; //导入依赖的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;
}
 
开发者ID:pschuette22,项目名称:Zeppa-AppEngine,代码行数:67,代码来源:NotificationWorker.java

示例8: 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();
}
 
开发者ID:jvalue,项目名称:cep-service,代码行数:45,代码来源:GcmUtils.java

示例9: asyncSend

import com.google.android.gcm.server.MulticastResult; //导入依赖的package包/类
private void asyncSend(List<String> partialDevices) {
  // make a copy
  final List<String> devices = new ArrayList<String>(partialDevices);
  threadPool.execute(new Runnable() {

    public void run() {
      Message message = new Message.Builder().build();
      MulticastResult multicastResult;
      try {
        multicastResult = sender.send(message, devices, 5);
      } catch (IOException e) {
        logger.log(Level.SEVERE, "Error posting messages", e);
        return;
      }
      List<Result> results = multicastResult.getResults();
      // analyze the results
      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) {
          logger.fine("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
            logger.info("canonicalRegId " + canonicalRegId);
            Datastore.updateRegistration(regId, canonicalRegId);
          }
        } else {
          String error = result.getErrorCodeName();
          if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
            // application has been removed from device - unregister it
            logger.info("Unregistered device: " + regId);
            Datastore.unregister(regId);
          } else {
            logger.severe("Error sending message to " + regId + ": " + error);
          }
        }
      }
    }});
}
 
开发者ID:army-of-dumbledore,项目名称:pennappsF13,代码行数:43,代码来源:SendAllMessagesServlet.java

示例10: 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);
    }
}
 
开发者ID:aerogear,项目名称:aerogear-unifiedpush-server,代码行数:80,代码来源:FCMPushNotificationSender.java

示例11: 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();
}
 
开发者ID:jvalue,项目名称:open-data-service,代码行数:59,代码来源:GcmSender.java

示例12: 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++;
  }
}
 
开发者ID:larrytin,项目名称:realtime-server-appengine,代码行数:70,代码来源:GoogleCloudMessaging.java

示例13: 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();
        }
    }
}
 
开发者ID:lolletsoc,项目名称:dissertation-project,代码行数:63,代码来源:GcmHelper.java

示例14: 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();
        }
    }
}
 
开发者ID:lolletsoc,项目名称:dissertation-project,代码行数:54,代码来源:GcmHelper.java

示例15: sendMessageToDevice

import com.google.android.gcm.server.MulticastResult; //导入依赖的package包/类
private String sendMessageToDevice(String email, String input) throws ServerDAO.DAOException, IOException {

        Credentials user = getUserByEmail(dao,email);

        Sender sender = new Sender(keyManager.getPushKey());
        Message message = new Message.Builder().addData("body", input).build();

        MulticastResult result = sender.send(message, Arrays.asList(user.getPushMessagingKey()), 5);

        System.out.println("Result = " + result);
        return result.toString();
    }
 
开发者ID:williamwebb,项目名称:divide,代码行数:13,代码来源:PushEndpoint.java


注:本文中的com.google.android.gcm.server.MulticastResult类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。