remoteMessage.getNotification()中的错误.getBody()

nat*_*iyu 8 android firebase firebase-cloud-messaging

我在我的应用程序中实施了Firebase Cloud Messaging,在使用Firebase控制台时,Android和iOS中的应用程序收到了我的通知.但是因为我想每天推送通知,所以我在服务器端创建了一个cron作业.我注意到每次触发我的cron时我的应用程序崩溃了

在我的iOS客户端中,它不会收到任何通知.

在我的Android客户端,它显示一个错误:

java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' on a null object reference

在我FirebaseMessagingService这里的地方是我的代码

public class MyFirebaseMessagingService  extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

    sendNotification(remoteMessage.getNotification().getBody());
} 
Run Code Online (Sandbox Code Playgroud)

在我的服务器端

function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {


$headers = array(
    'Content-Type:application/json',
    'Authorization:key=' . $apiKey
);

$message = array(
    'registration_ids' => $registrationIDs,
    'data' => array(
            "message" => $messageText,
            "id" => $id,
    ),
);


$ch = curl_init();

curl_setopt_array($ch, array(
    CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => json_encode($message)
));

$response = curl_exec($ch);
curl_close($ch);

return $response;
}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么我有NPE,我该如何解决?

mgc*_*ioa 27

尝试在$ message上添加通知对象.POST请求的正文必须是:

{
    "to" : "aUniqueKey",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
}
Run Code Online (Sandbox Code Playgroud)

您的remoteMessage.getNotification()返回null是因为POST请求的正文不包含通知对象.

当您希望FCM处理代表客户端应用程序显示通知时使用通知.当您希望应用程序处理显示或处理Android客户端应用程序上的消息时,或者如果您希望在存在直接FCM连接时向iOS设备发送消息,请使用数据消息.

查看高级消息传递选项文档以供参考.