8

アプリケーションに 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());
} 

そして、私のサーバー側で

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 を持っているのか、どうすれば解決できるのでしょうか?

4

4 に答える 4

29

$message に通知オブジェクトを追加してみてください。POST リクエストの本文は次のようにする必要があります。

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

POSTリクエストの本文に通知オブジェクトが含まれていないため、remoteMessage.getNotification()返されます。null

クライアント アプリに代わって FCM で通知の表示を処理する場合は、通知を使用します。アプリで Android クライアント アプリのメッセージの表示または処理を行う場合、または直接 FCM 接続がある場合に iOS デバイスにメッセージを送信する場合は、データ メッセージを使用します。

詳細なメッセージング オプションのドキュメントを参照してください。

于 2016-06-02T07:13:59.133 に答える
1
if (remoteMessage.getNotification() != null) {
   sendNotification(remoteMessage.getNotification().getBody());
}
于 2016-11-05T01:59:19.873 に答える