我在我的应用程序中实现了 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.
关于android - remoteMessage.getNotification().getBody() 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37584693/