我如何知道我的GCM消息是否足够小(<4kb)发送? (如何获得字符串的大小?) [英] How do i know if my GCM Message is small enough (&lt; 4kb) to send? (How to get size of String?)

查看:116
本文介绍了我如何知道我的GCM消息是否足够小(<4kb)发送? (如何获得字符串的大小?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想直接在GCM(Google云端消息)中嵌入数据,以帮助我的应用程序跳过我的服务器。

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说总数据有效载荷需要适合4kb以内。数据使用[键,值]对发送。假设我做了这样的事情:

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);

如何知道字符串数据小于4kb?据我所知,没有办法真正做到 String.getSize()或类似的东西。

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.

链接到文档如果好奇:
http://developer.android.com/training/ cloudsync / gcm.html#embed

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

推荐答案

您可以使用以下命令获取字符串的字节:

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;

请确保您指定了 String ,因为不同的编码可能会占用相同字符串的不同字节数。在上面的例子中,使用 UTF-8 作为编码。

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.

要将字节转换为kB,除以 1024

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

编辑:这里是关于Java中不同编码的字节空间的一个很好和详细的答案,来自Geobits的评论。

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

这篇关于我如何知道我的GCM消息是否足够小(<4kb)发送? (如何获得字符串的大小?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆