2016-12-31 83 views
0

我试图使用以下代码从C#控制台程序向Android应用程序发送推送通知。但应用程序在接收到消息时崩溃,但可以成功地将推送通知发送到设备FCM Web控制台。我试过这个C#程序,但很难找到我在邮件正文中犯的错误。Android应用程序在C#中收到FCM推送通知时崩溃

public void SendGCMNotification(string apiKey,string senderId, string deviceId) 
     { 

      string postDataContentType = "application/json"; 

      string message = "Your text"; 
      string tickerText = "example test GCM"; 
      string contentTitle = "content title GCM"; 
      String postData = 
      "{ \"registration_ids\": [ \"" + deviceId + "\" ], " + 
       "\"data\": {\"tickerText\":\"" + tickerText + "\", " + 
         "\"contentTitle\":\"" + contentTitle + "\", " + 
         "\"message\": \"" + message + "\"}}"; 


      //ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate); 

      // 
      // MESSAGE CONTENT 
      byte[] byteArray = Encoding.UTF8.GetBytes(postData); 

      // 
      // CREATE REQUEST 
      HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send"); 
      Request.Method = "POST"; 
      Request.KeepAlive = false; 
      Request.ContentType = postDataContentType; 
      Request.Headers.Add(string.Format("Authorization: key={0}", apiKey)); 
      Request.Headers.Add(string.Format("Sender: id={0}", senderId)); 
      Request.ContentLength = byteArray.Length; 

      Stream dataStream = Request.GetRequestStream(); 
      dataStream.Write(byteArray, 0, byteArray.Length); 
      dataStream.Close(); 

      // 
      // SEND MESSAGE 
      try 
      { 
       WebResponse Response = Request.GetResponse(); 
       HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode; 
       if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden)) 
       { 
        var text = "Unauthorized - need new token"; 
       } 
       else if (!ResponseCode.Equals(HttpStatusCode.OK)) 
       { 
        var text = "Response from web service isn't OK"; 
       } 

       StreamReader Reader = new StreamReader(Response.GetResponseStream()); 
       string responseLine = Reader.ReadToEnd(); 
       Reader.Close(); 

       // return responseLine; 
      } 
      catch (Exception e) 
      { 
      } 

     } 

Android应用程序代码:

@Override 
public void onMessageReceived(RemoteMessage message){ 
    Intent intent = new Intent(this,MainActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT); 

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this); 
    notificationBuilder.setContentTitle("Test Notification"); 
    notificationBuilder.setContentText(message.getNotification().getBody()); 
    notificationBuilder.setAutoCancel(true); 
    notificationBuilder.setSmallIcon(R.mipmap.ic_launcher); 
    notificationBuilder.setContentIntent(pendingIntent); 

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    notificationManager.notify(0,notificationBuilder.build()); 

} 

崩溃报告:

E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-1 
       Process: com.example.mani_pc7989.jappnotificationsample, PID: 8505 
       java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference 
        at com.example.mani_pc7989.jappnotificationsample.FireBaseMessagingService.onMessageReceived(FireBaseMessagingService.java:27) 
        at com.google.firebase.messaging.FirebaseMessagingService.zzo(Unknown Source) 
        at com.google.firebase.messaging.FirebaseMessagingService.zzn(Unknown Source) 
        at com.google.firebase.messaging.FirebaseMessagingService.zzm(Unknown Source) 
        at com.google.firebase.iid.zzb$2.run(Unknown Source) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
        at java.lang.Thread.run(Thread.java:761) 
V/FA: Activity paused, time: 46609836 
D/FirebaseApp: Notifying background state change listeners. 
D/FA: Application backgrounded. Logging engagement 
+1

请分享崩溃信息 –

+0

添加的致命异常 – Manikanta

+1

异常状态有包含在消息对象没有收到通知。请确保您以正确的方式发送通知 – NightFury

回答

0

解决它。

String title = remoteMessage.getData().values().toArray()[0].toString(); 
    String message = remoteMessage.getData().values().toArray()[1].toString(); 
    String tickerText = remoteMessage.getData().values().toArray()[2].toString(); 
相关问题