FCM push notifications do not work when the application is closed on Android
Well, I searched everywhere but couldn’t find an answer.
I’ve implemented push notifications in my Android app, everything works fine when the app is in the active state (foreground or background), but if I close the app, I will stop receiving notifications.
Here is the php code I sent the notification.
public static function sendNotification($token){
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'notification' => array("title" => "Test","body" => "Test Message","icon" => "default","sound" => "default"),
"data" => "test message",
'to' => $token
);
$headers = array(
'Authorization:key = AIzaSyAKHM3MoMACjmeVK46TDg8-rTj1KoVjzWs',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($ch);
if($result === FALSE) {
throw new errorSendingNotification();
}
curl_close($ch);
Result returns this
{"multicast_id":8978533958735781479,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1468627796530714%7c0e4bee7c0e4bee"}]}
return $result;
}
Solution
I’m having the same issue. This is very helpful to me.
Remove the Notification key from the payload and provide only the Data key.
The application processes notification messages only when the application is in the
foreground, but it processes data messages even if the application is in the background or closed.
If the application is foreground, onMessageReceived processes data and notification messages. If the application is closed or in the background, only data messages are delivered to onMessageReceived. Notification The message was not delivered to onMessageReceived. So you can’t customize the message.
It is better to remove the notification key from the payload.