mys*_*sho 15 notifications android google-cloud-messaging
有没有办法从"GCM通知"获取数据.这是我用gcm发送的json字符串的一部分:{"data":{"id":"123"}}.我需要在我的应用程序中获取id的值,但我不知道如何...非常感谢.
azg*_*fer 26
如果您正在使用新的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");
}
Run Code Online (Sandbox Code Playgroud)
如果您没有使用GCM库,那么GCM响应将在您的接收器中以您的意图出现,然后您可以使用intent的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);
}
}
Run Code Online (Sandbox Code Playgroud)
将其作为json表示形式的最佳方法是将数据添加为json对象.
{
"registration_ids" : [
"id1",
"id2"
],
"data" : {
"my_json_object": {
"text" :"This is my message",
"title":"Some title"
}
},
"collapse_key":"12345"
}
Run Code Online (Sandbox Code Playgroud)
然后解析你的对象:
String json = getIntent().getExtras().getString("my_json_object");
JsonObject jObject = new JsonObject(json);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30565 次 |
| 最近记录: |