Get data from GCM notification

2020-05-18 17:20发布

问题:

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.

回答1:

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);          
   }
}


回答2:

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);


回答3:

<receiver android:name=".beforelogin.GcmBroadcastReceiver"
          android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="android.intent.category.TAB" />
    </intent-filter>
</receiver>
<service android:name=".beforelogin.GcmIntentService" />
<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />