Reputation: 361
I am currently working on flutter notification using firebase messaging, I couldn't receive any notification. I sent the notification via server using curl
, I could get it work in native android app (Android Studio) but not in flutter, any help would be appreciated. Below is my code.
Flutter Notification code
class FirebaseNotifications {
FirebaseMessaging _firebaseMessaging;
void setUpFirebase() {
_firebaseMessaging = FirebaseMessaging();
firebaseCloudMessaging_Listeners();
}
void firebaseCloudMessaging_Listeners() {
if (Platform.isIOS) iOS_Permission();
_firebaseMessaging.getToken().then((token) {
print(token);
});
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('on message $message');
},
onResume: (Map<String, dynamic> message) async {
print('on resume $message');
},
onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
},
);
}
void iOS_Permission() {
_firebaseMessaging.requestNotificationPermissions(
IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}
}
Android Studio code
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
showNotification(remoteMessage);
}
private void showNotification(RemoteMessage remoteMessage) {
Map data = remoteMessage.getData();
String mesg = "New Notification";
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.GREEN);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{0, 250, 250, 250});
mNotificationManager.createNotificationChannel(mChannel);
builder = new NotificationCompat.Builder(this, id);
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentTitle(data.get("title").toString()) // required
//.setStyle(new
NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification()
.getBod
y().toString()))
.setStyle(new
NotificationCompat.BigTextStyle().bigText(mesg)) //custom data
.setSmallIcon(R.drawable.ic_stat_notification_icon4) //
required
.setContentText(mesg) // custom data
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{0, 250, 250, 250});
}
}
Server side code
function sendtoUser($sendingTarget, $acc_name, $type_message,
$type_of_transaction, $check_amount)
{
#API access key from Google API's Console
$API_ACCESS_KEY = "adazxc";
$registrationIds = $sendingTarget;
#prep the bundle
$fields = array(
'to' => $registrationIds,
'data' => array(
'title' => 'my title',
'keyValue' => true,
'receiverName' => $acc_name,
'transType' => $type_of_transaction,
'totalAmount' => $check_amount
),
);
$headers = array(
'Authorization: key=' . $API_ACCESS_KEY,
'Content-Type: application/json'
);
#Send Reponse To FireBase Server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
}
EDIT
I somehow can receive notification but I noticed that my status bar not receiving the notification but it is printed in the console, however, when I close the app I can get the notification. So how do I able to receive notification in both situation?
Upvotes: 12
Views: 26575
Reputation: 21
Most of the scenarios are already mentioned here. However, along with the checklist mentioned by @Zerj, I would like to add one more point.
google-services.json
file would reside in the respective folders (android/app/development
, etc) instead of at the android/app
level.MainActivity
file using FirebaseOptions
class. You can find the usage hereMore info about flavors - https://firebase.google.com/docs/projects/multiprojects
Upvotes: 0
Reputation: 81370
From the docs:
Depending on a devices state, incoming messages are handled differently.
State | Description |
---|---|
Foreground | When the application is open, in view & in use. |
Background | When the application is open, however in the background (minimised). This typically occurs when the user has pressed the "home" button on the device, has switched to another app via the app switcher or has the application open on a different tab (web). |
Terminated | When the device is locked or the application is not running. The user can terminate an app by "swiping it away" via the app switcher UI on the device or closing a tab (web). |
And this:
Notification messages which arrive whilst the application is in the foreground will not display a visible notification by default.
If your app is currently opened and in the foreground, the notification will not be shown even if it was sent successfully. You can confirm this by opening the snackbar in the notification event handler like below:
FirebaseMessaging.onMessage.listen((message) {
print('Got a message whilst in the foreground!');
if (message.notification != null) {
final snackBar = SnackBar(
content: Text(message.notification?.title ?? '', maxLines: 2),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
});
If you're working with android and you want to display notification when in the foreground, you can use flutter_local_notifications
package as suggested from the FCM docs here.
Upvotes: 5
Reputation: 7395
For what it's worth, I had an issue with receiving onMessage
notifications today (didn't try onResume
or onLaunch
) when it was working fine yesterday. No errors in the Functions logs and tokens were all the same.
Try restarting your device -- this seems to be the most consistent way to fix this if your functions were previously working.
Also, if the messaging seems slow at first, this may be due to cold starting when you aren't using the functions for a while (see this SO question for a bit more information).
Upvotes: 2
Reputation: 1503
data
tag only for transferring more information to app, like where it has to redirect, image etc.. you have to add notification
tag to display notification on status bar.
its seems you havent added notification content, please refer below sample message and configure same, it'll work
{
"notification": {
"body": "body",
"title": "title"
},
"priority": "high",
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"image": "https://ibin.co/2t1lLdpfS06F.png",
},
"to": <fcm_token>
}
Upvotes: 4
Reputation: 1708
Some checks (Version numbers may change):
In android/build.gradle:
In android/app/build.gradle:
Upvotes: 2
Reputation: 249
You may miss manual configuration for android (as well as ios if required), refer below link
http://myhexaville.com/2018/04/09/flutter-push-notifications-with-firebase-cloud-messaging/
Upvotes: -2