Android – how to count android gcm payload length

androidgoogle-cloud-messagingpayloadpush-notification

In the android GCM document, it is said the payload has a limit of 4096 bytes.

However, I found that I can send a payload with 16834 byes.

Did I make a mistake? I computed the length as follows:


Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
setJsonField(jsonRequest, GCMConstants.PARAM_TIME_TO_LIVE, message.getTimeToLive());
setJsonField(jsonRequest, GCMConstants.PARAM_COLLAPSE_KEY, message.getCollapseKey()); 
setJsonField(jsonRequest, GCMConstants.PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle());
jsonRequest.put(GCMConstants.JSON_REGISTRATION_IDS, registrationIds); 
Map<String, Object> payload = message.getData(); 
if (!payload.isEmpty()) { 
    jsonRequest.put(GCMConstants.JSON_PAYLOAD, payload);
}  
String requestBody = gson.toJson(jsonRequest); 
System.out.println(requestBody.getBytes("UTF-8").length);

Furthermore, what's the response from GCM if the payload is too long?

Best Answer

If the payload is too big, you'll get "MessageTooBig" in the error message. The part of the payload that must not exceed 4096 is all the custom keys and values in the payload. You don't count the registration ids and you don't count predefined keys such as time to live and collapse key. By the way, I found out that even though the documentation says the payload must not exceed 4096 bytes, they accept larger payloads as long as they don't exceed 4096 characters (i.e. you can send a 4096 characters string that contains characters encoded into more than one byte, so the length of the payload in bytes will exceed 4096).