remoteMessage.getNotification().getBody() 出错

Error in remoteMessage.getNotification().getBody()

我在我的应用程序中实施了 Firebase 云消息传递,并且在使用 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());
} 

在我的服务器端

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;
}

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

尝试在您的 $message 上添加一个通知对象。您的 POST 请求的正文必须类似于:

{
    "to" : "aUniqueKey",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
}

您的 remoteMessage.getNotification() returnsnull 因为您的 POST 请求正文不包含通知对象。

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.

检查 Documentation for Advanced Messaging Options 供您参考。

if (remoteMessage.getNotification() != null) {
   sendNotification(remoteMessage.getNotification().getBody());
}
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,
        ),
     'notification' => array(
                "body" => "body of notification",
                "title" => "title for notification",
        )
    );


    $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;
    }

我遇到了同样的问题,通过几次实验找到了解决方案。

我正在使用 Node 后端,其中我的示例推送(取自 Google Firebase)如下所示:

const message = {
    data: {score: '850', time: '2:45'},
    tokens: nTokenArray
}


admin.messaging().sendMulticast(message)
  .then((response) => {
    if (response.failureCount > 0) {
      const failedTokens = [];
      response.responses.forEach((resp, idx) => {
        if (!resp.success) {
          console.log('resperrorresperrorresperrorresperror', resp.error);
          failedTokens.push(registrationTokens[idx]);
        }
      });
      console.log('List of tokens that caused failures: ' + failedTokens);
    }
  })
  .catch(fcmError => {
    console.log({'FCM Errors': fcmError});
  })

在Android侧:

Log.d(TAG, "BodyScore: " + remoteMessage.getData().get("score"));

NullPointerException 是因为当您在服务器端使用 Data Payload 而不是 Notification Payload 时,您使用 getNotification().getBody() 而不是 getData().get("score")

const message = {
    data: {score: '850', time: '2:45'},
    tokens: nTokenArray
}