2

在启用 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);
    }
4

3 回答 3

7

extras是一个BundleBundle是一个 Java 类,具有通过键访问单个数据的方法,很像getString()HashMap. 如果您只想要,message请致电getString("message")extras

于 2013-09-26T12:20:40.797 回答
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);
    }
于 2013-09-27T06:00:14.110 回答
0

它是一个 json 字符串,您可以解析并仅获取“消息”键。

于 2013-09-26T12:48:14.457 回答