2014-10-16 59 views
5

我想使用解析推送通知服務發送自定義數據,但從包中提取時始終返回空值。無法讀取解析推送通知包數據

自定義廣播接收器:

@Override 
public void onReceive(Context context, Intent intent) { 
    Log.e("Receiver","Invoked"); 
    Bundle bundle = intent.getExtras(); 
    Intent contentIntent = new Intent(context, MainPage.class); 
    String alertMsg = bundle.getString("heading"); //never get this value 
    String urlString = bundle.getString("dataString"); //never get this value 
    contentIntent.putExtra(EXTRA_URL, urlString); 
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 
      NOTIFY_REQUEST_CODE, contentIntent, PendingIntent.FLAG_ONE_SHOT); 
    showNotification(context, notificationId, alertMsg, pendingIntent); 
} 

艙單申報:

 <receiver 
     android:name=".receiver.NotificationReceiver" 
     android:exported="false"> 
     <intent-filter> 
      <action android:name="link_notification"/> 
     </intent-filter> 
    </receiver> 

,我從parse儀表盤發出以下JSON:

{ "dataString": "objectId", "heading": "type", "action": "link_notification" } 

當我記錄捆綁數據時,我能夠看到標題dataString,但無法訪問它。該包總是返回null。

請幫忙! 謝謝。

回答

16

的JSON將是額外的字符串com.parse.Data

@Override 
public void onReceive(Context context, Intent intent) { 
    Bundle extras = intent.getExtras(); 
    String jsonData = extras.getString("com.parse.Data"); 
    JSONObject jsonObject; 
    try { 
     jsonObject = new JSONObject(jsonData); 
     String heading = jsonObject.getString("heading"); 
     String dataString = jsonObject.getString("dataString"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
} 
0

這是因爲包數據包含json對象作爲字符串可檢索與您可以檢查解析的密鑰。只有這樣你才能用gson解析這個字符串來獲取Java對象。

+0

什麼是在其中與json字符串配對的鍵的名稱? – AabidMulani 2014-10-17 14:05:53

3

好吧,現在我明白了。爲了讓您的JSON字符串,你需要這樣做:

public void onReceive(Context context, Intent intent) { 
    // TODO Auto-generated method stub 
    Bundle extra = intent.getExtras(); 
    String json = extra.getString("com.parse.Data"); 
}