android - remoteMessage.getNotification().getBody() 出错

标签 android firebase firebase-cloud-messaging

我在我的应用程序中实现了 Firebase 云消息传递,并且在使用 Firebase 控制台时,我在 Android 和 iOS 中的应用程序收到了我的通知。但是因为我想每天推送通知,所以我创建了一个 cron 作业来在我的服务器端执行此操作。我注意到每次我触发我的 cron 时,我的应用程序都会崩溃

在我的 iOS 客户端中,它没有收到任何通知。

在我的 android 客户端中它显示错误:

java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' 在空对象引用上

它在我的 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() 返回null,因为您的 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供大家引用。

关于android - remoteMessage.getNotification().getBody() 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37584693/

相关文章:

Android:保持 fragment 运行

java - 如何在代码中的确切位置将数据从 firebase 提取到 android studio 中?

ios - 在运行时切换Firebase配置文件

android - Firebase 动态链接未打开应用

c# - Xamarin.iOS Firebase 未接收推送通知但接收 token

java - 是否可以代理传入的请求?

android - 如何正确使用Eclipse的Drawable文件夹?

android - FCM Token会像GCM注册ID一样周期性变化吗?

Android libstagefright_h264 ff_get_buffer is not declared in this scope 错误

node.js - 在每次执行时发送多个推送通知的 Firebase 函数中*返回*什么?