【问题标题】:Error in remoteMessage.getNotification().getBody()remoteMessage.getNotification().getBody() 中的错误
【发布时间】:2016-06-02 06:54:42
【问题描述】:

我在我的应用程序中实现了 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 中的通知对象在哪里?
  • @sinense 我没有notification 对象,我认为data 就足够了,因为notification 是可选的。我应该将它添加到我的$message 中吗?我应该在notification 对象中添加什么?
  • 是的,通知对象默认是可选的。但是在您的 onMessageReceived() 上,您正在调用 remoteMessage.getNotification() 但您没有要解析的通知对象。
  • @sinense 现在可以使用了,谢谢! :)

标签: android firebase firebase-cloud-messaging


【解决方案1】:

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

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

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

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

查看Documentation for Advanced Messaging Options 以供参考。

【讨论】:

  • 你太棒了
【解决方案2】:
if (remoteMessage.getNotification() != null) {
   sendNotification(remoteMessage.getNotification().getBody());
}

【讨论】:

  • 人们对此投了反对票,但这是一个实际的答案,您只想检查 getNotification() 是否返回 null,如果不是,您可以请求正文。
【解决方案3】:
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;
    }

【讨论】:

    【解决方案4】:

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

    我正在使用 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多