Google cloud messaging: payload value is always string

I am working on integrating cloud cloud messaging for one of my applications. From the server, I send a pair of key values โ€‹โ€‹as:

'not_id' => 1000, 'title' => 'This is a title. title', 'vibrate' => 1, 'sound' => 1 

In android GCMIntentService:

 protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { int not_id=extras.getInt("not_id"); 

When retrieving the key value not_id (which is an integer), the following exceptions are thrown:

Key not_id expected Integer, but the value was java.lang.String.java.lang.ClassCastException: java.lang.String could not be pressed for java.lang.Integer

Does gcm convert all value to String?

Passed through documents, in vain. Am I doing something wrong?

+4
source share
1 answer

I had the same problem. The workaround I found is to generate the json we create and add all json as a pair of key values โ€‹โ€‹in the data object that we send to the gcm cloud server -

Usually we ship -

 myData: { 'title' : 'New Notification', 'myAge' : 25 } json: { 'to': to, 'data': myData } 

Thus, all values โ€‹โ€‹inside the data packet are converted to String. In the above data, 25 is converted to String.

How am i doing this -

 json: { 'to': to, 'data': {'myData' : myData} } 

Now 25 will remain intact.

Note Stroke the myData JsonObject before submitting it. In Javascript, I use JSON.stringify(myData);

Then at the end of Android we can get all json -

 @Override public void onMessageReceived(String from, Bundle data) { try { JSONObject myData = new JSONObject(data.getString("myData")); } catch (JSONException e){} } 

Now all the resulting values โ€‹โ€‹will be in their original types.

+1
source

All Articles