【发布时间】:2012-07-04 08:49:51
【问题描述】:
有没有办法从“GCM 通知”中获取数据。这是我用 gcm 发送的 json 字符串的一部分:{"data":{"id":"123"}}。我需要在我的应用程序中获取 id 的值,但我不知道如何......非常感谢。
【问题讨论】:
标签: android notifications google-cloud-messaging
有没有办法从“GCM 通知”中获取数据。这是我用 gcm 发送的 json 字符串的一部分:{"data":{"id":"123"}}。我需要在我的应用程序中获取 id 的值,但我不知道如何......非常感谢。
【问题讨论】:
标签: android notifications google-cloud-messaging
如果您使用的是新的 GCM 库,那么您需要创建一个扩展 IntentService 的类,这是 GCM 库在收到 GCM 消息时通知您的地方。请看一下 MyIntentService.java 示例:
@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");
}
如果您没有使用 GCM 库,那么 GCM 响应会以您的接收器中的意图发送给您,那么您可以使用意图的 getExtras().getString() 从您的 GCM 通知中检索键/值对.例如
// 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);
}
}
【讨论】:
将其作为 json 表示的最佳方式是将数据添加为 json 对象。
{
"registration_ids" : [
"id1",
"id2"
],
"data" : {
"my_json_object": {
"text" :"This is my message",
"title":"Some title"
}
},
"collapse_key":"12345"
}
然后只解析你的对象:
String json = getIntent().getExtras().getString("my_json_object");
JsonObject jObject = new JsonObject(json);
【讨论】:
String json = gson.toJson([YOUR_OBJECT]); Message msg = new Message.Builder().addData("message", json).build(); gcmresult = sender.send(msg, [YOUR GCM CLIENT REG ID],5);
<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" />
【讨论】: