Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data from GCM notification

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.

like image 699
mysho Avatar asked Jul 04 '12 08:07

mysho


2 Answers

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);          
   }
}
like image 143
azgolfer Avatar answered Oct 20 '22 18:10

azgolfer


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);
like image 27
Roberto B. Avatar answered Oct 20 '22 17:10

Roberto B.