2013-09-26 15 views
1

使用支持GCM的應用程序,我可以接收消息。但是格式顯示爲消息:Bundle [{message = test,android.support.content.wakelock = 3,collapse_key = do_not_collapes,from = 3423423}]GCM intent.getExtras - 如何只顯示特定的數據?

如何指定只顯示消息數據密鑰對?意圖

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

回答

7

extras

GCM接收的消息是BundleBundle is a Java class,方法like getString()用於通過密鑰訪問各個數據段,很像HashMap。如果您只想要message,請致電getString("message"),電話extras

+0

這是它,謝謝所需的關鍵。 – Gary

0

它是一個json字符串,你可以解析並獲得唯一的「消息」鍵。

+2

服務器發送JSON字符串時,該JSON字符串中的名稱/值對將轉換爲GCM客戶端代碼所看到的「Bundle」中的條目。 – CommonsWare

+0

是內部GCMIntentService類可以解析內部方法所需的鍵 @覆蓋 \t保護無效的onMessage(上下文範圍內,意圖意圖){ \t \t Log.i(TAG, 「接收消息」); \t \t String message = intent.getExtras()。getString(「BUY」); \t \t \t \t displayMessage(context,message); \t \t //通知用戶 \t \t generateNotification(context,message); \t} – Swetank

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); 
    } 
相關問題