Is there a way to get data from "GCM notification". Here is a part of my json string which I send with gcm: {"data":{"id":"123"}}
. I need get value of id in my app, but I don't know how ... thanks a lot.
If you are using the new GCM library, then you need to create a class that extends IntentService, this is where the GCM library will notify you when a GCM message is received. Please take a look at MyIntentService.java sample:
@Override
public final void onHandleIntent(Intent intent) {
try {
String action = intent.getAction();
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
handleRegistration(intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(intent);
}
} finally {
synchronized(LOCK) {
sWakeLock.release();
}
}
}
private void handleMessage(Intent intent) {
String id = intent.getExtra("id");
}
If you are not using the GCM library, then the GCM response is coming to you in an intent in your receiver, then you can use intent's getExtras().getString() to retrieve the key/value pair from your GCM notification. e.g.
// intent come in in your onReceive method of your BroadcastReceiver:
public onReceive(Context context, Intent intent) {
// check to see if it is a message
if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
String id = intent.getExtras().getString("id");
String other_key = intent.getExtras().getString("other_key");
// if your key/value is a JSON string, just extract it and parse it using JSONObject
String json_info = intent.getExtras().getString("json_info");
JSONObject jsonObj = new JSONObject(json_info);
}
}
The best way to get it as a json representation is adding your data as a json object.
{
"registration_ids" : [
"id1",
"id2"
],
"data" : {
"my_json_object": {
"text" :"This is my message",
"title":"Some title"
}
},
"collapse_key":"12345"
}
Then to parse your object just:
String json = getIntent().getExtras().getString("my_json_object");
JsonObject jObject = new JsonObject(json);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With