GCM intent.getExtras - 如何只显示特定数据?

时间:2013-09-26 12:09:26

标签: android android-intent google-cloud-messaging

使用支持GCM的应用,我可以接收消息。但是格式显示为Message:Bundle [{message = test,android.support.content.wakelock = 3,collapse_key = do_not_collapes,from = 3423423}]

如何指定仅显示消息数据密钥对?

GCM收到消息意图

 protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM will be
             * extended in the future with new message types, just ignore any message types you're
             * not interested in, or that you don't recognize.
             */
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                for (int i = 0; i < 5; i++) {
                    Log.i(TAG, "Working... " + (i + 1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                sendNotification("Message: " + extras.toString());
                Log.i(TAG, "Message: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

3 个答案:

答案 0 :(得分:7)

extrasBundleBundle is a Java class,方法like getString()用于按键访问各个数据,非常类似于HashMap。如果您只想要message,请在getString("message")上致电extras

答案 1 :(得分:1)

是的,在GCMIntentService类中,您可以解析方法

中的所需键
@Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        String message =   intent.getExtras().getString("BUY");

        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

答案 2 :(得分:0)

它是一个json字符串,你可以解析并只获取“message”键。