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) s. length() will give you the number of bytes. Since characters are one byte (at least in ASCII), the number of characters is the same as the number of bytes. Another way is to get the bytes themselves and count them s.
An empty String takes 40 bytes—enough memory to fit 20 Java characters.
Therefore, the maximum length of String in Java is 0 to 2147483647. So, we can have a String with the length of 2,147,483,647 characters, theoretically.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With