Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 763
boltup_im_coding Avatar asked Oct 18 '12 17:10

boltup_im_coding


People also ask

How do you determine string byte size?

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.

How many bytes does string take in Java?

An empty String takes 40 bytes—enough memory to fit 20 Java characters.

What is the size of string data type in Java?

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.


2 Answers

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.

like image 147
Raghav Sood Avatar answered Oct 14 '22 05:10

Raghav Sood


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
like image 39
Mohsen Afshin Avatar answered Oct 14 '22 05:10

Mohsen Afshin