本文整理汇总了Java中com.google.android.gcm.server.Message类的典型用法代码示例。如果您正苦于以下问题:Java Message类的具体用法?Java Message怎么用?Java Message使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Message类属于com.google.android.gcm.server包,在下文中一共展示了Message类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendMessage
import com.google.android.gcm.server.Message; //导入依赖的package包/类
public void sendMessage(List<String> registrationIds, Message message) throws IOException {
mLog.info("Sending to " + registrationIds.size() + " clients message " + message);
for (String registrationId : registrationIds) {
// sendNoReply otherwise a device switched off will receive the message the same
Result result = mSender.sendNoRetry(message, registrationId);
if (result.getMessageId() != null) {
mLog.info("Message sent to " + registrationId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// if the regId changed, we have to update the datastore
mLog.info("Registration Id changed for " + registrationId + " updating to " + canonicalRegId);
mRegistrationDao.updateRegistrationId(registrationId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
mLog.warning("Registration Id " + registrationId + " no longer registered with GCM, removing from datastore");
// if the device is no longer registered with Gcm, remove it from the datastore
mRegistrationDao.removeByRegistrationId(registrationId);
} else {
mLog.warning("Error when sending message : " + error);
}
}
}
}
示例2: sendNotifications
import com.google.android.gcm.server.Message; //导入依赖的package包/类
public Result sendNotifications(String msg, String listUser) {
Result result = null;
String[] users = listUser.split(",");
try {
for (int i = 0; i < users.length; i++) {
String deviceId = userDAO.getDeviceId(users[i]);
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(120)
.delayWhileIdle(false).addData(MESSAGE_KEY, msg).build();
System.out.println("User: " + users[i] + " - regId: " + deviceId);
result = sender.send(message, deviceId, 1);
}
return result;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
示例3: sendNotification
import com.google.android.gcm.server.Message; //导入依赖的package包/类
public void sendNotification(String msg, String deviceId) {
System.out.println("Start send notification" + deviceId);
Result result = null;
try {
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(120)
.delayWhileIdle(false).addData(MESSAGE_KEY, msg).build();
result = sender.send(message, deviceId, 1);
System.out.println("Send Notification Success: " + result.toString());
System.out.println("RegID: " + deviceId);
System.out.println("End send notification");
} catch (IOException ioe) {
ioe.printStackTrace();
System.out.println("Error when send notification " + ioe.toString());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error when send notification " + e.toString());
}
}
示例4: searchForPlayers
import com.google.android.gcm.server.Message; //导入依赖的package包/类
/**
* Starts to ask for players for a new game
*
* @param ownerId the user id that asked for the new game
* @param roomId the room id of the new game
*
* @return
*/
@ApiMethod(name = "searchForPlayers")
public GameResult searchForPlayers(
@Named("ownerId") String ownerId,
@Named("roomId") String roomId
) throws IOException {
// Stores the new game request
GameRecord game = new GameRecord()
.setOwnerId(ownerId)
.setRoomId(roomId);
mGameDao.save(game);
mLog.info("Saved new game request with game id " + game.getId());
// Alerts other players for then new game request
Message message = new Message.Builder()
.addData(Bag.EXTRA_GCMACTION_TYPE, Bag.GCMACTION_SEARCH_FOR_PLAYERS)
.addData(Bag.EXTRA_PLAYER_ID, game.getOwnerId())
.addData(Bag.EXTRA_ROOM_ID, game.getRoomId())
.addData(Bag.EXTRA_GAME_ID, String.valueOf(game.getId()))
.build();
//TODO filters by room
mGcmMessageHelper.sendMessage(message);
return new GameResult(game.getId());
}
示例5: sendMessage
import com.google.android.gcm.server.Message; //导入依赖的package包/类
/**
* Send to the first 10 devices (You can modify this to send to any number of devices or a specific device)
*
* @param message The message to send
*/
public void sendMessage(@Named("message") String message) throws IOException {
if (message == null || message.trim().length() == 0) {
log.warning("Not sending message because it is empty");
return;
}
// crop longer messages
if (message.length() > 1000) {
message = message.substring(0, 1000) + "[...]";
}
Message msg = new Message.Builder()
.addData(Bag.EXTRA_MESSAGE, message)
.addData(Bag.EXTRA_GCMACTION_TYPE, Bag.GCMACTION_SEARCH_FOR_PLAYERS)
// 113100264827945975278 - Play Together
// 108670469644954045753 - User test 1
// 108659852221654912818 - User test 2 cool
.addData(Bag.EXTRA_PLAYER_ID, "108670469644954045753")
.build();
GcmMessageHelper messageHelper = new GcmMessageHelper();
messageHelper.sendMessage(msg);
}
示例6: sendNotification
import com.google.android.gcm.server.Message; //导入依赖的package包/类
@POST
@Path("/sendNotification/user/{account}")
public String sendNotification(@HeaderParam("Authorization") String token, String text,
@PathParam("account") String account,
@DefaultValue("application/json") @HeaderParam("Content-Type") String contentType,
@DefaultValue("application/json") @HeaderParam("Accept") String accept) {
if (!validCredentials(token))
return serialise(getInvalidCredentialsBean(), accept);
// (new ApplePushNotificationDelegator(token)).sendNotification(account, text);
Sender sender = new Sender("AIzaSyBBHzixGmnJnu8YhZS44zCObl85JTspo_Q");
Message message = new Message.Builder().addData("runId", "1234").build();
try {
Result result = sender.send(message, "APA91bFDiScakJJnxA9LfFNknB965TdghV5ep7w5ZGwOG51JJF_X3MBy3_set6mPPaYRK_ceWcK00JF9x6vW-vuDGB4dYqgevukafBYq8VgovwG8dyLK4QtbT123N_8_hmACIJ185JztOBvVLb-8AlDLJPG_I3gldQ", 5);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "sent";
}
示例7: 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();
}
}
示例8: sendMessageToDevice
import com.google.android.gcm.server.Message; //导入依赖的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;
}
示例9: sendGcmAlert
import com.google.android.gcm.server.Message; //导入依赖的package包/类
private void sendGcmAlert(String subId, String regId)
throws IOException {
String gcmKey = backendConfigManager.getGcmKey();
boolean isGcmKeySet = !(gcmKey == null || gcmKey.trim().length() == 0);
// Only attempt to send GCM if GcmKey is available
if (isGcmKeySet) {
Sender sender = new Sender(gcmKey);
Message message = new Message.Builder().addData(SubscriptionUtility.GCM_KEY_SUBID, subId)
.build();
Result r = sender.send(message, regId, GCM_SEND_RETRIES);
if (r.getMessageId() != null) {
log.info("ProspectiveSearchServlet: GCM sent: subId: " + subId);
} else {
log.warning("ProspectiveSearchServlet: GCM error for subId: " + subId +
", senderId: " + gcmKey + ", error: " + r.getErrorCodeName());
ArrayList<String> deviceIds = new ArrayList<String>();
deviceIds.add(regId);
SubscriptionUtility.clearSubscriptionAndDeviceEntity(deviceIds);
}
} else {
// Otherwise, just write a log entry
log.info(String.format("ProspectiveSearchServlet: GCM is not sent: GcmKey: %s ",
isGcmKeySet));
}
}
示例10: processFCM
import com.google.android.gcm.server.Message; //导入依赖的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);
}
}
示例11: testGcmSuccess
import com.google.android.gcm.server.Message; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void testGcmSuccess() throws Exception {
new Expectations() {{
gcmService.send((Message) any, (List) any, anyInt); result = gcmMulticastResult;
gcmMulticastResult.getResults(); result = Arrays.asList(gcmResult);
gcmResult.getMessageId(); result = "someMessageId";
}};
sender.onNewDataStart();
sender.onNewDataItem(new ObjectNode(JsonNodeFactory.instance));
sender.onNewDataComplete();
Assert.assertEquals(SenderResult.Status.SUCCESS, sender.getSenderResult().getStatus());
new Verifications() {{
Message message;
List<String> devices;
gcmService.send(message = withCapture(), devices = withCapture(), anyInt);
Assert.assertEquals(sourceId, message.getCollapseKey());
Assert.assertEquals(sourceId, message.getData().get("source"));
Assert.assertEquals(1, devices.size());
Assert.assertTrue(devices.contains(gcmDeviceId));
}};
}
示例12: testGcmUpdate
import com.google.android.gcm.server.Message; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void testGcmUpdate() throws Exception {
final String newDeviceId = "someNewDeviceId";
new Expectations() {{
gcmService.send((Message) any, (List) any, anyInt); result = gcmMulticastResult;
gcmMulticastResult.getResults(); result = Arrays.asList(gcmResult);
gcmResult.getMessageId(); result = "someMessageId";
gcmResult.getCanonicalRegistrationId(); result = newDeviceId;
}};
sender.onNewDataComplete();
Assert.assertEquals(SenderResult.Status.UPDATE_CLIENT, sender.getSenderResult().getStatus());
Assert.assertEquals(newDeviceId, ((GcmClient) sender.getSenderResult().getNewClient()).getGcmClientId());
}
示例13: reviewUpdateReceived
import com.google.android.gcm.server.Message; //导入依赖的package包/类
/**
* Received a new review: send GCM message
* @param review
*/
@POST
@Path("/review/created")
public void reviewUpdateReceived(Review review) {
LOGGER.info("Syncing Review Id: " + String.valueOf(review.getId()));
try {
GCMMessageService messageService = new GCMMessageService(new GaspGCMServlet().getKey());
Message message = new Message.Builder()
.delayWhileIdle(true)
.addData("table", "reviews")
.addData("id", String.valueOf(review.getId()))
.build();
messageService.sendMessage(message);
} catch (IOException e) {
LOGGER.error("Error sending GCM message", e);
}
}
示例14: restaurantUpdateReceived
import com.google.android.gcm.server.Message; //导入依赖的package包/类
/**
* Received a new restaurant notification: send GCM message
* @param restaurant
*/
@POST
@Path("/restaurant/created")
public void restaurantUpdateReceived(Restaurant restaurant) {
LOGGER.info("Syncing Restaurant Id: " + String.valueOf(restaurant.getId()));
try {
GCMMessageService messageService = new GCMMessageService(new GaspGCMServlet().getKey());
Message message = new Message.Builder()
.delayWhileIdle(true)
.addData("table", "restaurants")
.addData("id", String.valueOf(restaurant.getId()))
.build();
messageService.sendMessage(message);
} catch (IOException e) {
LOGGER.error("Error sending GCM message",e);
}
}
示例15: userUpdateReceived
import com.google.android.gcm.server.Message; //导入依赖的package包/类
/**
* Received a new user notification: send GCM message
* @param user
*/
@POST
@Path("/user/created")
public void userUpdateReceived(User user) {
LOGGER.info("Syncing User Id: " + String.valueOf(user.getId()));
try {
GCMMessageService messageService = new GCMMessageService(new GaspGCMServlet().getKey());
Message message = new Message.Builder()
.delayWhileIdle(true)
.addData("table", "users")
.addData("id", String.valueOf(user.getId()))
.build();
messageService.sendMessage(message);
} catch (IOException e) {
LOGGER.error("Error sending GCM message",e);
}
}