I have integrated Firebase Cloud Messaging to my Flutter mobile app with a plugin called flutter_local_notifications for showing heads-up notification in every state of the app. Everything is working fine until I created a Laravel project for sending notification to the specific device using device token.
I have integrated the Laravel project with Firebase Admin SDK and I follow the documentation for using Cloud Messaging. For now, the heads-up notification only showing in foreground state and not showing in background or terminated state.
Here is my testing laravel controller
public function sendFCM()
{
$deviceToken = 'device token';
$title = 'My Notification Title';
$body = 'My Notification Body';
$imageUrl = 'http://lorempixel.com/400/200/';
$notification = Notification::fromArray([
'title' => $title,
'body' => $body,
'image' => $imageUrl,
]);
$notification = Notification::create($title, $body);
$data = ['route' => 'resultipt'];
$message = CloudMessage::withTarget('token', $deviceToken)
->withNotification($notification)
->withData($data)
->withHighestPossiblePriority();
try {
$this->messaging->send($message);
return response()->json(['status' => 'Successfully sent']);
} catch (InvalidMessage $th) {
return response()->json(['status' => $th->getMessage()]);
}
}
I have solved my own problem.
I forgot to add my notification channel id to the android config.
$deviceToken = 'device token here';
$title = "My Notification Title";
$body = "My Notification Body";
$channel_id = "channel id here";
$notification = Notification::fromArray([
'title' => $title,
'body' => $body,
]);
$config = AndroidConfig::fromArray([
'priority' => 'high',
'notification' => [
'channel_id' => $channel_id,
'color' => '#42A5F5',
'sound' => 'default',
],
]);
$notification = Notification::create($title, $body);
$data = ['route' => 'resultipt'];
$message = CloudMessage::withTarget('token', $deviceToken)
->withAndroidConfig($config)
->withNotification($notification)
->withData($data);
try {
$this->messaging->send($message);
return response()->json(['status' => 'Successfully sent', 'message' => $message]);
} catch (InvalidMessage $th) {
return response()->json(['status' => $th->getMessage()]);
}