How do i know if my GCM Message is small enough (< 4kb) to send? (How to get size of String?)

a 夏天 提交于 2019-12-22 07:12:46

问题


I want to embed data directly inside of a GCM (Google Cloud Message) in order to help my application skip a round trip to my server.

Google says the total data payload needs to fit inside 4kb. Data is sent using [key,value] pairs. Assuming I did something like this:

 String key = "key";
 String data = "data";
 Message message = new Message.Builder().addData(key, data).build();
 sender.send(message, regId, 5);

How can I know if the String data is less than 4kb? To my knowledge there's no way to really do a String.getSize() or similar.

Link to the documentation if curious: http://developer.android.com/training/cloudsync/gcm.html#embed


回答1:


You can use the following to get the bytes of a String:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");
int bytes = b.length;

Make sure that you specify the encoding of the String, as different encodings may take up a different number of bytes for the same String. In the above example, UTF-8 is used as the encoding.

To convert the bytes into kB, just divide by 1024.

EDIT: Here's a nice and detailed answer on the byte space of different encodings in Java from Geobits' comment.




回答2:


int byteSize = data.length() * 2  // each char is 2 byte

Updated

int byteSize = data.getBytes("UTF-8").length // if you want to know the size in your desired encoding



回答3:


I run a couple of tests locally, seems like on the application side you can send a bundle that contains a key + value pair of about 4020 bytes before you start getting an error from gcm, while on the server side it's a bit more, about 4100 bytes. Given this, to play safe we have decided to go with 4,000 bytes on either side.



来源:https://stackoverflow.com/questions/12960641/how-do-i-know-if-my-gcm-message-is-small-enough-4kb-to-send-how-to-get-siz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!