Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Received GCM message shows with garbled text

I have a Servlet deployed on Google App Engine, which is playing the role of posting broadcast message to GCM. Android clients will receive that broadcast message from GCM. The Servlet extends BaseServlet with following snippet.

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  //when receiving a gcm broadcast request, send message to GCM
  Builder mb = new Message.Builder();
  mb.addData("message", "The message to send");
  Message message = mb.build();
  sender.sendNoRetry(message, regIds);
  ...
}

When "the message to send" is in English, all things fine. But if "the message to send" is replaced by other language such as Chinese, the Android client will receive a string of garbled text. On Android client, I use a class extends GCMBaseIntentService to deal with GCM broadcast.

@Override
protected void onMessage(Context context, Intent intent) {

        String message = "";
        message = intent.getStringExtra("message")!=null ? intent.getStringExtra("message") : "";
        doNotify(message);
}

I have tried to re-encode the message but doesn't work.

message = new String(message.getBytes("ISO-8859-1"), "UTF-8");

Have any idea about the problem? I need your help, Thanks.

like image 727
Shawn Lu Avatar asked Feb 18 '23 15:02

Shawn Lu


1 Answers

Try URLEncoder

mb.addData("message", URLEncoder.encode("世界","UTF-8");

another option:

mb.addData("message", new StringEntity("世界", "UTF-8");

After looking at the source code of GCM : com.google.android.gcm.server.Sender , it is useing HttpPost as json, and Java uses UTF-16 to internally so before you post, you will need to encode it properly.
And as comment stated, at client decode the String

String yourAwesomeUnicodeString=URLDecoder.decode(intent.getStringExtra("message"),"UTF-8");
like image 179
wtsang02 Avatar answered Feb 20 '23 04:02

wtsang02