當前位置: 首頁>>代碼示例>>Java>>正文


Java Sender.send方法代碼示例

本文整理匯總了Java中com.google.android.gcm.server.Sender.send方法的典型用法代碼示例。如果您正苦於以下問題:Java Sender.send方法的具體用法?Java Sender.send怎麽用?Java Sender.send使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.android.gcm.server.Sender的用法示例。


在下文中一共展示了Sender.send方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: sendNotifications

import com.google.android.gcm.server.Sender; //導入方法依賴的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;
}
 
開發者ID:tranquang9a1,項目名稱:ECRM,代碼行數:24,代碼來源:GCMService.java

示例2: sendNotification

import com.google.android.gcm.server.Sender; //導入方法依賴的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());
    }
}
 
開發者ID:tranquang9a1,項目名稱:ECRM,代碼行數:21,代碼來源:GCMService.java

示例3: sendNotification

import com.google.android.gcm.server.Sender; //導入方法依賴的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";
	}
 
開發者ID:WELTEN,項目名稱:dojo-ibl,代碼行數:21,代碼來源:GoogleCloadMessaging.java

示例4: sendGCMNotificationAsJson

import com.google.android.gcm.server.Sender; //導入方法依賴的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();
        }
    }
 
開發者ID:WELTEN,項目名稱:dojo-ibl,代碼行數:21,代碼來源:NotificationDelegator.java

示例5: sendGcmAlert

import com.google.android.gcm.server.Sender; //導入方法依賴的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));
  }
}
 
開發者ID:googlesamples,項目名稱:io2014-codelabs,代碼行數:27,代碼來源:ProspectiveSearchServlet.java

示例6: requestSubscription

import com.google.android.gcm.server.Sender; //導入方法依賴的package包/類
public static void requestSubscription(long id, String subUsername, String pubGcmToken) throws IOException {
			
	Sender sender = new Sender(API_KEY);
	Message msg = new Message.Builder()
			.addData(MESSAGE_TYPE, SUBSCRIPTION_REQUEST)
			.addData(SUBSCRIBER_ID, id + "")
			.addData(SUBSCRIBER_USERNAME, subUsername)
			.build();
	Result result = sender.send(msg, pubGcmToken, 1);
	System.out.println(msg.toString());
	System.out.println(result.toString());		
}
 
開發者ID:kflauri2312lffds,項目名稱:Android_watch_magpie,代碼行數:13,代碼來源:GcmSender.java

示例7: sendMessage

import com.google.android.gcm.server.Sender; //導入方法依賴的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) + "[...]";
    }
    Sender sender = new Sender(API_KEY);
    Message msg = new Message.Builder().addData("message", message).build();
    List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(10).list();
    for(RegistrationRecord record : records) {
        Result result = sender.send(msg, record.getRegId(), 5);
        if (result.getMessageId() != null) {
            log.info("Message sent to " + record.getRegId());
            String canonicalRegId = result.getCanonicalRegistrationId();
            if (canonicalRegId != null) {
                // if the regId changed, we have to update the datastore
                log.info("Registration Id changed for " + record.getRegId() + " updating to " + canonicalRegId);
                record.setRegId(canonicalRegId);
                ofy().save().entity(record).now();
            }
        } else {
            String error = result.getErrorCodeName();
            if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
                log.warning("Registration Id " + record.getRegId() + " no longer registered with GCM, removing from datastore");
                // if the device is no longer registered with Gcm, remove it from the datastore
                ofy().delete().entity(record).now();
            }
            else {
                log.warning("Error when sending message : " + error);
            }
        }
    }
}
 
開發者ID:scarrupt,項目名稱:Capstone-Project,代碼行數:42,代碼來源:MessagingEndpoint.java

示例8: run

import com.google.android.gcm.server.Sender; //導入方法依賴的package包/類
public void run() {
	Sender sender = new Sender(SENDER_ID);

	Message message = new Message.Builder()
			// If multiple messages are sent while device is offline,
			// only receive the latest message is received.
			.collapseKey(COLLAPSE_KEY + "_" + p.getId())
			// TTL = 6 hours (if scheduled at 9h, push is received until
			// 15h)
			.timeToLive(21600).delayWhileIdle(true).addData("title", p.getTitle())
			.addData("numberOfRestaurants", restaurantsForPushCount.toString())
			.addData("longitude", String.valueOf(p.getLongitude()))
			.addData("latitude", String.valueOf(p.getLatitude())).addData("radius", String.valueOf(p.getRadius()))
			.addData("kitchenTypeIds", pushKitchenTypeIds.toString()).addData("pushId", String.valueOf(p.getId()))
			.build();

	try {

		Result result = sender.send(message, p.getGcmToken(), NUMBER_OF_RETRIES);

		if (result.getErrorCodeName() == null) {
			LOGGER.info(
					LogUtils.getDefaultSchedulerMessage(Thread.currentThread().getStackTrace()[1].getMethodName(),
							"GCM Notification was sent successfully: " + message.toString()));
		} else if (result.getErrorCodeName().equals("InvalidRegistration")) {
			pushRepo.delete(p);
			LOGGER.error(LogUtils.getErrorMessage(Thread.currentThread().getStackTrace()[1].getMethodName(),
					"GCM Token invalid: Push-Notification is deleted."));
		} else {
			LOGGER.error(LogUtils.getErrorMessage(Thread.currentThread().getStackTrace()[1].getMethodName(),
					"Error occurred while sending push notification :" + result.getErrorCodeName()));
		}

	} catch (Exception e) {
		LOGGER.error(LogUtils.getExceptionMessage(Thread.currentThread().getStackTrace()[1].getMethodName(), e));
	}

	return;
}
 
開發者ID:andju,項目名稱:findlunch,代碼行數:40,代碼來源:PushNotificationScheduledTask.java

示例9: sendMessage

import com.google.android.gcm.server.Sender; //導入方法依賴的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) + "[...]";
    }
    Sender sender = new Sender(API_KEY);
    Message msg = new Message.Builder().addData("message", message).build();
    List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(10).list();
    for (RegistrationRecord record : records) {
        Result result = sender.send(msg, record.getRegId(), 5);
        if (result.getMessageId() != null) {
            log.info("Message sent to " + record.getRegId());
            String canonicalRegId = result.getCanonicalRegistrationId();
            if (canonicalRegId != null) {
                // if the regId changed, we have to update the datastore
                log.info("Registration Id changed for " + record.getRegId() + " updating to " + canonicalRegId);
                record.setRegId(canonicalRegId);
                ofy().save().entity(record).now();
            }
        } else {
            String error = result.getErrorCodeName();
            if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
                log.warning("Registration Id " + record.getRegId() + " no longer registered with GCM, removing from datastore");
                // if the device is no longer registered with Gcm, remove it from the datastore
                ofy().delete().entity(record).now();
            } else {
                log.warning("Error when sending message : " + error);
            }
        }
    }
}
 
開發者ID:JimSeker,項目名稱:googleplayAPI,代碼行數:41,代碼來源:MessagingEndpoint.java

示例10: sendMessage

import com.google.android.gcm.server.Sender; //導入方法依賴的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) + "[...]";
    }
    Sender sender = new Sender(API_KEY);
    Message msg = new Message.Builder().addData("message", message).build();
    List<RegistrationRecord> records = ofy().load().type(RegistrationRecord.class).limit(10).list();
    for (RegistrationRecord record : records) {
        Result result = sender.send(msg, record.getToken(), 5);
        if (result.getMessageId() != null) {
            log.info("Message sent to " + record.getToken());
            String canonicalRegId = result.getCanonicalRegistrationId();
            if (canonicalRegId != null) {
                // if the regId changed, we have to update the datastore
                log.info("Registration Id changed for " + record.getToken() + " updating to " + canonicalRegId);
                record.setToken(canonicalRegId);
                ofy().save().entity(record).now();
            }
        } else {
            String error = result.getErrorCodeName();
            if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
                log.warning("Registration Id " + record.getToken() + " no longer registered with GCM, removing from datastore");
                // if the device is no longer registered with Gcm, remove it from the datastore
                ofy().delete().entity(record).now();
            } else {
                log.warning("Error when sending message : " + error);
            }
        }
    }
}
 
開發者ID:tjyu1040,項目名稱:GallyShuttle,代碼行數:41,代碼來源:MessagingEndpoint.java

示例11: send

import com.google.android.gcm.server.Sender; //導入方法依賴的package包/類
private static void send(final String topic) throws IOException {
    final Sender sender = new Sender(getApiKey());
    final Message msg = new Message.Builder()
            .collapseKey(COLLAPSE_KEY_ALARM)
            .priority(Message.Priority.HIGH)
            .timeToLive(TTL_SECONDS)
            .build();
    final Result result = sender.send(msg, topic, NUM_RETRIES);
    if (result.getMessageId() != null) {
        log.fine("Message sent to " + topic);
    } else {
        log.warning("Error when sending message: " + result.getErrorCodeName());
    }
}
 
開發者ID:meisteg,項目名稱:RaspberryPiTempAlarm,代碼行數:15,代碼來源:Gcm.java

示例12: sendMessage

import com.google.android.gcm.server.Sender; //導入方法依賴的package包/類
/**
 * Send to the first 10 devices
 *
 * @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) + "[...]";
    }
    Sender sender = new Sender(API_KEY);
    Message msg = new Message.Builder().addData("message", message).build();
    List<RegistrationRecord> records =
            ofy().load().type(RegistrationRecord.class).limit(10).list();
    for(RegistrationRecord record : records) {
        Result result = sender.send(msg, record.getRegId(), 5);
        if (result.getMessageId() != null) {
            log.info("Message sent to " + record.getRegId());
            String canonicalRegId = result.getCanonicalRegistrationId();
            if (canonicalRegId != null) {
                // if the regId changed, we have to update the datastore
                log.info("Registration Id changed for " + record.getRegId()
                        + " updating to " + canonicalRegId);
                record.setRegId(canonicalRegId);
                ofy().save().entity(record).now();
            }
        } else {
            String error = result.getErrorCodeName();
            if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
                log.warning("Registration Id " + record.getRegId()
                        + " no longer registered with GCM, removing from datastore");
                // if the device is no longer registered with Gcm, remove it from the datastore
                ofy().delete().entity(record).now();
            }
            else {
                log.warning("Error when sending message : " + error);
            }
        }
    }
}
 
開發者ID:vaektor,項目名稱:Loqale,代碼行數:45,代碼來源:MessagingEndpoint.java

示例13: doSendViaGcm

import com.google.android.gcm.server.Sender; //導入方法依賴的package包/類
/**
 * Sends the message using the Sender object to the registered device.
 * 
 * @param message
 *            the message to be sent in the GCM ping to the device.
 * @param sender
 *            the Sender object to be used for ping,
 * @param deviceInfo
 *            the registration id of the device.
 * @return Result the result of the ping.
 */
private static Result doSendViaGcm(String message, Sender sender,
		DBObject deviceInfo, DBCollection coll) throws IOException {
	// Trim message if needed.
	if (message.length() > 1000) {
		message = message.substring(0, 1000) + "[...]";
	}

	// This message object is a Google Cloud Messaging object, it is NOT 
	// related to the MessageData class
	Message msg = new Message.Builder().addData("message", message).build();
	Result result = sender.send(msg, (String) deviceInfo.get("_id"),
			5);
	if (result.getMessageId() != null) {
		String canonicalRegId = result.getCanonicalRegistrationId();
		if (canonicalRegId != null) {
			// same device has more than on registration ID: update database
			coll.save(deviceInfo);
		}
	} else {
		String error = result.getErrorCodeName();
		if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
			// application has been removed from device - unregister database
			coll.remove(deviceInfo);
		}
	}

	return result;
}
 
開發者ID:johan12345,項目名稱:vertretungsplan-server,代碼行數:40,代碼來源:ParseThread.java

示例14: sendGcmNotification

import com.google.android.gcm.server.Sender; //導入方法依賴的package包/類
void sendGcmNotification(final PatientEntity p, final String title, final String msg) {
	if (!p.isGcmUser()) {
		throw new IllegalStateException(
				"User is not an Android user. We should never attempt to send a GCM message if we don't have a valid GCM registration id");
	}

	final String regId = p.getProperties().get("c2dmRegistrationId");

	try {
		Sender sender = new Sender(this.gcmAuthKey);
		Message message = new Message.Builder().addData("title", title).addData("message", msg)
				.addData("timestamp", String.valueOf(System.currentTimeMillis())).build();

		Result result = sender.send(message, regId, 5);

		if (result.getMessageId() != null) {
			String canonicalRegId = result.getCanonicalRegistrationId();
			if (canonicalRegId != null) {
				// same device has more than on registration ID: update
				// database
				getLog().debug(
						"Google indicates that the device has more than one registration id. Update to the correct one");
				p.getProperties().put("c2dmRegistrationId", canonicalRegId);
			}
		} else {
			String error = result.getErrorCodeName();

			if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
				// application has been removed from device - unregister
				// database
				getLog().debug(
						"Google indicates that the registration id has been removed from the device. Remove from our database.");
				p.getProperties().remove("c2dmRegistrationId");
			}
		}
	} catch (final IOException e) {
		e.printStackTrace();
		getLog().warn("Could not send push through the GCM network. Error was: " + e.getMessage());
	}
}
 
開發者ID:MinHalsoplan,項目名稱:netcare-healthplan,代碼行數:41,代碼來源:PushNotificationServiceImpl.java

示例15: push

import com.google.android.gcm.server.Sender; //導入方法依賴的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);
	}
}
 
開發者ID:interdroid,項目名稱:cuckoo-library,代碼行數:33,代碼來源:RemoteMonitorThread.java


注:本文中的com.google.android.gcm.server.Sender.send方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。