I am implementing FCM notifications in Android, but how does notifications differ depending on the app status (background vs. foreground)?
I am sending the notification using the FCM API with Postman and this is the notification structure:
{ "notification": {
"title": "Notification title",
"body": "Notification message",
"sound": "default",
"color": "#53c4bc",
"click_action": "MY_BOOK",
"icon": "ic_launcher"
},
"data": {
"main_picture": "URL_OF_THE_IMAGE"
},
"to" : "USER_FCM_TOKEN"
}
The image to render is taken from data.main_picture
.
I have implemented my own FirebaseMessagingService
which makes the notifications display perfectly in foreground state. The notification code is the next:
NotificationCompat.BigPictureStyle notiStyle = new NotificationCompat.BigPictureStyle();
notiStyle.setSummaryText(messageBody);
notiStyle.bigPicture(picture);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(bigIcon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setStyle(notiStyle); code here
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
However, in background, the service is not even executed. In the AndroidManifest.xml
, Firebase services are declared as follow:
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
My problem is not the LargeIcon
or SmallIcon
but displaying the big picture.
Thanks for your support.
FCM notification messages
don't support the largeIcon or bigPicture.
if you need them while in background you can use a FCM data message
.
For data messages the onMessageReceived(message)
method is always called, so you can use the message.getData()
method and create your custom notification.
Read more about notification messages vs data messages here: https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages