0
Я пытаюсь отправить уведомление Push для приложения Android из программы консоли C#, используя следующий код. Но приложение вылетает после получения сообщения, но может успешно отправлять уведомления на устройство с Веб-консоль FCM. Я пробовал эту программу на C#, но мне трудно найти, какую ошибку я делаю в теле сообщения.Android-приложение потерпело крах при получении уведомления об отправке FCM в 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 App код:
@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
пожалуйста, поделитесь аварии данные –
добавил неустранимое исключение – Manikanta
Исключение заявляет, что нет никакого уведомления не включается в объект сообщения получил. Пожалуйста, убедитесь, что вы отправляете уведомление правильно – NightFury