Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCM push message encoding

I am trying to send push notifications using following code:

    Message message = new Message.Builder().addData("appName", appData.name)
.addData("message", pushData.message).build();

On the receiving side my code is:

String message = intent.getStringExtra("message");

When the message is in English, latin charset, everything works. However, when I try other languages or the character ç, they arrive as question marks or are deleted from the string.

Note: it's encoded in utf-8

like image 967
hungary54 Avatar asked Nov 05 '12 09:11

hungary54


2 Answers

Java server

Message messagePush = new Message.Builder().addData("message", URLEncoder.encode("your message éèçà", "UTF-8")))

Android application

String message = URLDecoder.decode(intent.getStringExtra("message"), "UTF-8");
like image 190
Anthone Avatar answered Sep 23 '22 13:09

Anthone


I was having the same issue. Non ASCII characters where corrupted when received on the Android client. I personally believe this is a problem within the Google GCM server library implementation.

In the Android GCM library I see the method:

com.google.android.gcm.server.Sender.sendNoRetry(Message, List<String>) 

That method does the following

HttpURLConnection conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody) 

They should atleast specify "application/json; charset=utf-8" or whatever encoding they used or better yet force it to UTF-8. Isn't this is a BIG problem?

Digging even deeper I find the method:

com.google.android.gcm.server.Sender.post(String, String, String) 

which does:

byte[] bytes = body.getBytes()

Why do they use the platform default charset? Especially since it is not likely to align with the devices default charset.

Work Around

Pass the following property as an argument to the JVM "-Dfile.encoding=UTF-8" This instructs Java to use UTF-8 as the platform default charset when doing things like "blah".getBytes(). This is bad practice but what can you do when it is someone else's library?

like image 21
Yepher Avatar answered Sep 23 '22 13:09

Yepher