Android应用在C#中收到FCM推送通知时崩溃

时间:2016-12-31 20:33:55

标签: android firebase firebase-cloud-messaging

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

 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 :(得分: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();