2017-04-25 69 views
0

我試圖在我的應用中實現FCM通知。我已閱讀FCM數據報文類型將收到通知,即使應用程序在後臺所以我試圖實現在onMessageRecieved方法我越來越喜歡這個意外的響應:如何從Android中的FCM數據消息中獲取價值?

{title =2, message={"Status":"UNASSIGNED","CompanyName":"gd","LastModifiedDateTime":"2017-04-25 18:59:41","IsPartRequired":false,"ProblemCategory":"CONFIGURATION","IsGeneralClaim":false,"RegistrationID":1057,"IncidentCode":"INS\/2017\/04\/25-0010","StatusID":0,"CreatedDateTime":"2017-04-25 18:59:41","IsInstallationCall":false}} 

不知道如何解析這個獲得單獨的值從標題和消息讓我發表我的火力消息代碼:

public class FireBaseMessage extends FirebaseMessagingService { 
    private static final String TAG = "MyFirebaseMsgService"; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     super.onMessageReceived(remoteMessage); 
     Map<String,String> data = remoteMessage.getData(); 
     Log.d(TAG, "From: " + data.toString()); 
// 
} 
} 

在此日誌消息我得到的反應一樣,如何從該值嘗試像:

int title=data.get("title"); 

獲取空指針,因爲這不是有效的格式。在我的服務器端,我試圖發佈像這樣的json格式:

{ 
    "to":"es_OToDkj00:APA91bFqxbVMAaXy5fPtDbNVAkIwyVrPCmfGci2otHZPvdRoXPv-oDdjgtLR92Nqe8w6f57nCVceLbc3_zBWsInG9g1Pfdp3LvsMKyuaiYps0L1y3tn0N0XbzGseEI6jyiqs1r-sT9lb", 
    "data":{ 
     "message":{ 
     "RegistrationID":1057, 
     "IncidentCode":"INS/2017/04/25-0010", 
     "CompanyName":"ABM INFOTECH", 
     "StatusID":5, 
     "Status":"ASSIGNED", 
     "CreatedDateTime":"2017-04-25T12:03:45", 
     "LastModifiedDateTime":"2017-04-25T18:59:41", 
     "ProblemCategory":"CONFIGURATION", 
     "IsPartRequired":false, 
     "IsInstallationCall":false, 
     "IsGeneralClaim":false 
     }, 
     "title ":"1" 
    } 

不知道我在哪裏犯了一個錯誤。誰能幫我?提前致謝!

+0

多貼問題。從[這裏](http://stackoverflow.com/q/43613369/4625829)。 –

回答

1

拿到冠軍:從消息負載

使用:

@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 


    Log.d(TAG, "From: " + remoteMessage.getFrom()); 

    // Check if message contains a data payload. 
    if (remoteMessage.getData().size() > 0) { 
     Log.d(TAG, "Message data payload: " + remoteMessage.getData()); 
    } 

    String title = remoteMessage.getData().get("title").toString(); 
} 

編輯

檢查,如果你remoteMessage包含特定的鍵:

for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) { 
    String key = entry.getKey(); 
    String value = entry.getValue(); 
    Log.d(TAG, "key, " + key + " value " + value); 
} 
+0

但看看json響應得到像這樣{title = 2,message = {「Status」:「UNASSIGNED」,「CompanyName」:「gd」,「LastModifiedDateTime」:「2017-04-25 18:59:41 」, 「IsPartRequired」:假的, 「ProblemCategory」: 「配置」, 「IsGeneralClaim」:假的, 「RegistrationID」:1057, 「IncidentCode」: 「INS \/2017年\/04 \/25-0010」, 「StatusID」 :0,「CreatedDateTime」:「2017-04-25 18:59:41」,「IsInstallationCall」:false}} –

+0

空指針異常,當我嘗試執行您的代碼 –

+0

nullpointer異常...在哪個對象? – rafsanahmad007

0

你有額外的空格字符"title"參數:

"title ":"1" 

很難看到,因爲它只是一個空間。它應該是:

"title":"1" 

的原因,您注意到得到任何價值,因爲從技術上講,發送的關鍵是"title "(中間有空格),而在你的客戶端代碼,你只使用「title」 (沒有空間)。

刪除多餘的空間後,您應該能夠正確接收它。