Quickstart-android: Custom Notifications when app is in background or killed

Created on 19 May 2016  Β·  139Comments  Β·  Source: firebase/quickstart-android

Hi,

I'd like to implement custom notification styles when app is in background or is killed. Is there a Firebase broadcast receiver class one could extend to implement the same? Would be very helpful. Thanks.

Most helpful comment

@samtstern Both comments are incorrect.

Custom messaging service is only called when the app is in the foreground.

Android does not turn the icon white. It keeps its color.

I've already implemented FirebaseMessagingService for my app when it's in the foreground.
What we are asking for is how to handle it when it's in the background.

I don't understand why the notification is created automatically when FCM is meant to replace GCM. It is totally incompatible with the current flow.

All 139 comments

@ckarthikv could you clarify this question a little bit? Are you trying to show different notification styles when your app is in the background versus when your app is running in the foreground?

Hi,
When i tried to implement this notification i get error like
Error:(28, 0) Plugin with id 'com.google.gms.google-services' not found.

@samtstern - Yes, we wanted to implement custom notification styles like Big Picture style, etc, when the app is in background or when the app is killed. I believe the notifications would be working through a broadcast receiver?

Would be great if you could point me in the right direction so that one could intercept all kinds of messages (probably by extending the FirebaseBroadcastReceiver class) - whether the app is in background or killed, so that we could customize every aspect of the notification styles immaterial of the app state.

Same problem. The icon being used is not what I want.
It is using the launcher icon while but the new guidelines require that we use a white on transparent icon. Also, the color is wrong.
I can't seem to find any way to customize this looking at the available methods.

Any help?

@ckarthikv you can see this example of FirebaseMessagingService which is where your app can receive FCM messages and react. This is a good place to create notifications.

Telling if your Activity is in the foreground (and reacting differently) can be a little tricky. My favorite way is to register a local BroadcastReceiver in the Activity and then do a sendBroadcast from the service. You will get true from that method if your receiver is running (meaning your app is in the foreground), and false otherwise.

You can see an example of this (using GCM, but the logic is the same for FCM) here.

@frostymarvelous when you send a notification from the Firebase console is uses your app icon by default, and the Android system will turn that icon solid white when in the notification bar.

If you are unhappy with that result you should implement FirebaseMessagingService and create the notifications manually when you receive a message. We are working on a way to improve this but for now that's the only way.

@samtstern Both comments are incorrect.

Custom messaging service is only called when the app is in the foreground.

Android does not turn the icon white. It keeps its color.

I've already implemented FirebaseMessagingService for my app when it's in the foreground.
What we are asking for is how to handle it when it's in the background.

I don't understand why the notification is created automatically when FCM is meant to replace GCM. It is totally incompatible with the current flow.

@frostymarvelous the behavior you are seeing sounds like a bug, in my apps the FirebaseMessagingService is definitely called when the app is in the background.

As far as the icon color, on recent versions of Android the system applies a white mask to the icon. What sort of device do you have and what version of Android is it running?

An S6 running 5.1.1.

I think your behavior is the bug.

From the docs

"When your app is in the background on a user's device, notifications are
delivered to the system tray. When a user clicks on the notification, the
app launcher opens your app. If you want, you can also add client message
handling to receive notifications in your app when it is already in the
foreground on the user's device."

On Fri, May 20, 2016, 7:29 PM Sam Stern [email protected] wrote:

@frostymarvelous https://github.com/frostymarvelous the behavior you
are seeing sounds like a bug, in my apps the FirebaseMessagingService is
definitely called when the app is in the background.

As far as the icon color, on recent versions of Android the system applies
a white mask to the icon. What sort of device do you have and what version
of Android is it running?

β€”
You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub
https://github.com/firebase/quickstart-android/issues/4#issuecomment-220697618

Sorry @frostymarvelous I misunderstood your situation, you are correct. When you send a notification from the Firebase console and your app is in the background it cannot be customized.

If you want custom background notifications you should use the FCM API to send data messages to your app and handle them in the FirebaseMessagingService where you can decide how the notification should look.

If that works, then I'm good.
I thought it behaved the same across.

Thanks a lot for your help.
If you're part of the team, then thanks for your hard work as well.

On Fri, May 20, 2016, 8:30 PM Sam Stern [email protected] wrote:

Sorry @frostymarvelous https://github.com/frostymarvelous I
misunderstood your situation, you are correct. When you send a notification _from
the Firebase console_ and your app is in the background it cannot be
customized.

If you want custom background notifications you should use the FCM API to
send data messages to your app and handle them in the
FirebaseMessagingService where you can decide how the notification should
look.

β€”
You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub
https://github.com/firebase/quickstart-android/issues/4#issuecomment-220710992

@frostymarvelous ok thanks for your patience while I figured out what was going on.

Please feel free to open issues if you try this approach and have questions. Good luck!

@samtstern I can't find an example of FCM API and how to manage the custom icon.
Do you have an example of this? I'm new to cloud messaging and I only find that there is a parameter icon, but no details how to implement it in my app
Thank you!

Here is the documentation for sending Notification messages.

The icon parameter can be used to specify a drawable within your app. If you want to use R.drawable.foo, just pass foo.

@samtstern thank you for the doc link, really helpfull.

Console has custom params when sending a message,
must the custom icon work there too? ( In my test this is still the app icon, but I can do something wrong)

It will only work if your app is in the foreground. Otherwise, you have to
use the the api.

On Tue, May 24, 2016, 7:48 PM Artem Osipov [email protected] wrote:

@samtstern https://github.com/samtstern thank you for the doc link,
really helpfull.

Console has custom params when sending a message,
must the custom icon work there too? ( In my test this is still the app
icon, but I can do something wrong)

β€”
You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub
https://github.com/firebase/quickstart-android/issues/4#issuecomment-221375176

As far as I am aware it is not possible to customize the icon through the
console right now, but that is a high-priority feature for us going forward.

On Tue, May 24, 2016 at 12:48 PM Artem Osipov [email protected]
wrote:

@samtstern https://github.com/samtstern thank you for the doc link,
really helpfull.

Console has custom params when sending a message,
must the custom icon work there too? ( In my test this is still the app
icon, but I can do something wrong)

β€”
You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub
https://github.com/firebase/quickstart-android/issues/4#issuecomment-221375176

The key value pairs currently available in the Firebase composer are for data message values only.

Do we need to customize it through console? Can't we just add it as a
config parameter? Thanks would be better
Don't forget the colors as well please?

Once again, thanks for the great job you all are doing!

On Tue, May 24, 2016, 8:47 PM Sam Stern [email protected] wrote:

As far as I am aware it is not possible to customize the icon through the
console right now, but that is a high-priority feature for us going
forward.

On Tue, May 24, 2016 at 12:48 PM Artem Osipov [email protected]
wrote:

@samtstern https://github.com/samtstern thank you for the doc link,
really helpfull.

Console has custom params when sending a message,
must the custom icon work there too? ( In my test this is still the app
icon, but I can do something wrong)

β€”
You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub
<
https://github.com/firebase/quickstart-android/issues/4#issuecomment-221375176

β€”
You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub
https://github.com/firebase/quickstart-android/issues/4#issuecomment-221385340

It would have to be through the console since the client side handler does not reference any of your specified remote config parameters.

Well, I thought that would work through the Configuration in the
Application class. I wonder how that would work since we can't tell the
value of whatever R.drawable.foo will be.

On Tue, May 24, 2016, 9:51 PM Arthur Thompson [email protected]
wrote:

It would have to be through the console since the client side handler does
not reference any of your specified remote config parameters.

β€”
You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub
https://github.com/firebase/quickstart-android/issues/4#issuecomment-221410342

I'm having a similar issue getting the notifications customized. I'm not using the console at all - only making API calls. When app is in foreground notifications get handled by my custom FirebaseMessagingService, but when app is in the background notification displays solid white icon and ignores any specified payload support parameters (icon, color etc).

Please advise whether this is expected as the behaviour appears to contradict comments made in this thread as well as https://github.com/firebase/quickstart-android/issues/8

@despisedIcon I had the similar problem, but it was my mistake I set it in the data section and it must be in the notification.
Like this:

'to' => '_PHONE_ID_', "notification"=>array( 'title'=>"Test", 'body'=>"Test2", "icon"=>"ic_stat_ic_notification" // R.drawable.ic_stat_ic_notification )

@Svoka Thanks for the tip. I've moved the icon parameter into the notification and now I'm getting the message

W/FirebaseMessaging: Icon resource icon ic_stat_logo not found. Notification will use app icon.

This same icon (R.drawable.ic_stat_logo) is being used for foreground notification builder without any issues.

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_logo)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))

Any idea why Firebase cannot resolve the icon for background notification?

@despisedIcon could you add your http request here maybe there is an issue with the formatting.

@kroikie You were right. I've tracked down this issue to malformed notification data in the request. Icon and color working correctly now. Thanks

@Svoka thats work form me... but only for small icon... any idea for large icon?
(This method is not the desired way... y don't need to send a custom "icon" parameter for iOS)

@sir-gon if you don't specify the custom icon, FCM will use the app icon.
I'm agree, if we can just set the default icon in some settings file, it'd be more convenient.

I'd prefer we simply got the opportunity to handle all notifications if
possible like we did with GCM.
It can be a configuration item as well.

I'm currently not using FCM to push notifications due to it being
unpredictable atm.

On Fri, May 27, 2016 at 9:24 AM, Artem Osipov [email protected]
wrote:

@sir-gon https://github.com/sir-gon if you don't specify the custom
icon, FCM will use the app icon.
I'm agree, if we can just set the default icon in some settings file, it'd
be more convenient.

β€”
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/firebase/quickstart-android/issues/4#issuecomment-222101230,
or mute the thread
https://github.com/notifications/unsubscribe/AA4XZcaeLgZSGWEWC7nuNovN3nQiTZswks5qFrhWgaJpZM4IiXTl
.

Regards,
Stefan Froelich.

@frostymarvelous but when app in background GCM also send it to notification tray, not in app.

@frostymarvelous to be clear @Svoka is correct, FCM handles messages in the exact same way as GCM. Notification messages have always been handled in this way. If you always want to handle all notifications then you should send data only messages and handle the creation and display of notifications yourself. Note however that messages from the Firebase console are notification messages.

Thanks for clarifying that. Again.
I will give it another spin this weekend!

The problem of using data notification instead of notification message is that it is not compatible with iOS. For exemple, if you want to send a message to a topic to both iOS and Android it's hard to find way to be compatible to the both platforms :
Send only data payloads -> message is not sent to iOS,
Send notification payloads (with or without data payloads) -> white icon on android.

The tip of @Svoka solves the bug for now, but it's quite a hack!...

@antoineF thanks for the feedback however:

  • Data only payloads can be sent to iOS, see the content_available field in the reference docs. Also when the iOS app is connected to FCM (in the foreground) data messages are sent through the FCM connection and through APNs otherwise.
  • The white icon on Android is a known issue, the FCM team is working on a fix.

Sending notifications from console is really powerful feature thanks for that, but since it is not possible to customize notifications when application is in background, as @frostymarvelous said would it be possible to create a configuration item or something like that and handle it in FCM? And maybe we could have previews of notification how would it be seen on devices?

Setting a bigImage, defining action buttons, small icon, and even wear optimisations... by this configuration item.

Then it would be an amazing feature to use, but right now it forces not to use :(
(Because you know customer NEVER gets enough with default behaviours and they ALWAYS need custom stuff :))

Thanks for the feedback @yayaa it is noted!

Couldn't have said it better myself.
The dashboard is a really powerful tool and I'm currently not even attempting to use it.

@kroikie Can you please clarify when we can expect a fix? Sending notifications through the Firebase console was the main reason for us to jump on the Firebase train.

Also, I want to point out that I'm not able to fully customize a notification inside onMessageReceived callback. What I do is simple: build a notification with NotificationCompat with title, body and a small icon from my drawables. When the notification gets shown, the icon is transparent. If I use the launcher icon instead it shows up as expected.

I am developing movie review app where I need to push a message with movie title and movie poster so for that I need to implement NotificationCompat.BigPictureStyle regardless of app state(Foreground /Background) BUT i found that this could not happen when app is in the background with firebase cloud messaging.

There must be some mechanism like this:
public void onMessageReceived(RemoteMessage remoteMessage) {
// Determine app state (foreground/background)
// if(foreground){
// use notification style 1
//}
//else(){
// use notification style 2
// }
}

After reading entire page I have decided NOT to use firebase as of now, I will implement GCM again. I hope this gets resolved as soon as possible.I am big fan of firebase.

I'm still such a noob, but via Raspberry Pi, Node-red and Firebase I now receive a notification on my phone when someone presses my doorbell. Helped by this page, even when the notification sample app is in the background, I get vibs or a tone. What I prefer though is, when the app is in the background and someone presses my doorbell I get a continuing ringtone, just like when someone would call me. This would be 'easy' when the app is in the foreground, but how to do it when it's in the background? From reading above I believe this cant be done yet, right?

@AndreasZeiser While I'm not able to give you a date for the fix to the icon issue, I can say that this is a high priority for the FCM team, and a solution will be released ASAP. I'm not sure why your notification icon is coming up transparent, once you receive the onMessageReceived callback you should be able to create and show notifications in the standard way, using NotificationCompat like you are.

@pinkeshdarji It may be worth noting that FCM and GCM receive notification messages the same way. So the foreground/background logic (which only applies to notification messages) will apply whether you are using FCM or GCM. I think that using FCM with data only messages will accomplish what you want since data only messages result in onMessageReceived being called whether the app is in the foreground or the background. The app being in the foreground or the background is only an issue when sending/receiving notification messages.

@NL-Splinter In cases when you want to have a callback to onMessageReceived whether the app is in the foreground or background then you should send data only messages.

Hi Arthur,

Thanks to your comment I now understand how to send a data only message, and the example app is indeed responding accordingly.

The only thing I don’t understand is:

the data payload is delivered in the extras of the intent of your launcher Activity

This kind of language is beyond my current Android skills :(

And this is not the way right? (I’m getting null as a msg)

private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
Log.d(TAG, "Msg: " + intent.getStringExtra("score"));

…

In other words: where and how do I pick up the (key/)value pair sent via the data?

I’m guessing it’s just 1 line of code, which I hope isn’t too much asked.

Thanks anyway for your help sofar!!

Regards, Jan

Van: Arthur Thompson [mailto:[email protected]]
Verzonden: woensdag 1 juni 2016 22:26
Aan: firebase/quickstart-android [email protected]
CC: NL-Splinter [email protected]; Mention [email protected]
Onderwerp: Re: [firebase/quickstart-android] Custom Notifications when app is in background or killed (#4)

@AndreasZeiser https://github.com/AndreasZeiser While I'm not able to give you a date for the fix to the icon issue, I can say that this is a high priority for the FCM team, and a solution will be released ASAP. I'm not sure why your notification icon is coming up transparent, once you receive the onMessageReceived callback you should be able to create and show notifications in the standard way, using NotificationCompat like you are.

@pinkeshdarji https://github.com/pinkeshdarji It may be worth noting that FCM and GCM receive notification messages the same way. So the foreground/background logic (which only applies to notification messages) will apply whether you are using FCM or GCM. I think that using FCM with data only messages will accomplish what you want since data only messages result in onMessageReceived being called whether the app is in the foreground or the background. The app being in the foreground or the background is only an issue when sending/receiving notification messages.

@NL-Splinter https://github.com/NL-Splinter In cases when you want to have a callback to onMessageReceived whether the app is in the foreground or background then you should send data only messages.

β€”
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub https://github.com/firebase/quickstart-android/issues/4#issuecomment-223113956 , or mute the thread https://github.com/notifications/unsubscribe/AFqfSgm0rzEqP2kVtNeYCpKbQHR05yc-ks5qHeregaJpZM4IiXTl .

Thanks @kroikie,
onMessageReceived being called whether the app is in the foreground or the background by just passing data only messages as you suggested.

Now I can handle data like this-
public void onMessageReceived(RemoteMessage remoteMessage) {
String topic = remoteMessage.getFrom();
String movieId = remoteMessage.getData().get("movieId");
String title = remoteMessage.getData().get("title");
String details = remoteMessage.getData().get("details");
String movieUrl = remoteMessage.getData().get("movieUrl");

    sendNotification(movieId,title,details,movieUrl);

}

In sendNotification I can create custom notification.
Thanks Once again.

Super, helped me a lot!

I'm using this now to get the whole key/value set:

        for (String key : remoteMessage.getData().keySet()) {
            Log.d(TAG, key + ": " + remoteMessage.getData().get(key));
        }

Does data only message means the message text on the top has to remain empty and only key value pairs in advanced options are to be filled? I am still getting a totally white color icon on lollipop and above.

screen shot 2016-06-03 at 7 43 58 am

@swatijiet you can't send data-only messages from Console at the moment. You need to use API

Hi, does the click_action work from the console when app is in background? Or the APIs need to be used for that also? It works perfectly in foreground case, but not able to get it work in background. Is it a bug or behavior?

I have same problem. I tried to use different android service that only get fcm message body string to create custom notification but the same behavior appeared. My notification icon turned to white icon at the background.

Please fix the issue asap. :)

I had the same issue (the blank icon).

So I tried to use a POST request to https://fcm.googleapis.com/fcm/send through cURL in this way:

curl -i -H "Authorization: key=MY_SERVER_KEY" -H "Content-Type: application/json" -d @nt.json https://fcm.googleapis.com/fcm/send

Now I want to send the notification to all the devices, without specifying the token of each user. However if I don't specify the "to" element in the JSON file, I get error 400.

How can I send my data to all users without specifying their token?

I have the same problem. I need to store notification in db for late use and also change the notification style and couple of more works on the received notification which is not possible. Please fix this issue as soon as possible.

Can any1 guild me how to send multiple push notification via push API???

Hello ,

some time ago published in

http://stackoverflow.com/questions/38020348/send-a-notification-background-firebase-android

a problem that I have with the push notification in foreground and backgrand FCM after you read the link sugueris me to look at my app android?

backgrand foreground and take different style.

Regards,

Can anyone please provide some example how can i use the api to send data only messages (php), currently i am using console to send notification and data, but it acts differently when app is in background or foreground..

I have the same question. Is there any simple way to send the data only messages?

@xainbutt it's really simple, you can adapt the following code:

`$toWhom = '';
$serverKey = '';
$serverFrom = '';

// The data to send to the API
$postData = array(
'to' => $toWhom,
"notification"=>array(
'title'=>"Test",
'body'=>"Test2",
"icon"=>"ic_stat_ic_notification"
)
);

// Setup cURL
$ch = curl_init('https://fcm.googleapis.com/fcm/send');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER=>false,
CURLOPT_HTTPHEADER => array(
'Authorization:key='.$serverKey,
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
die(curl_error($ch));
}

print '

' . print_r($response, true) . '
';`

Just want to leave my feedback about the notification framework:
We as developers should have full control of the notifications. I never wanted FCM to auto-notify my system bar for me and i should ALWAYS receive the "onMessageReceived" callback, doesn't matter in foreground or background.

Pehaps we could have a checkbox on the Firebase Notification console indicating "Auto-notify". If unchecked, we get the "onMessageReceived" callback. Otherwise, it notifies the system bar.

Agreed

On Thu, Jul 14, 2016, 18:43 shinayser [email protected] wrote:

Just want to leave my feedback about the notification framework:
We as developers should have full control of the notifications. I never
wanted FCM to auto-notify my system bar for me and i should ALWAYS receive
the "onMessageReceived" callback, doesn't matter in foreground or
background.

Pehaps we could have a checkbox on the Firebase Notification console
indicating "Auto-notify". If unchecked, we get the "onMessageReceived"
callback. Otherwise, it notifies the system bar.

β€”
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/firebase/quickstart-android/issues/4#issuecomment-232704454,
or mute the thread
https://github.com/notifications/unsubscribe/ACtEJrpZWE717XEPnLr1NxigCL6Mly-cks5qVlk9gaJpZM4IiXTl
.

Have a nice day
Yishai Levenglick
Android developer
+972-54-520-9569

@shinayser I think you just misunderstood how android notifications is working.
This is the CORRECT behavior

@Svoka No, I did not. When in background, the Firebase Notifications (in Console) doesn't have data-only notifications. So, we can't customize it when app is in background.

@shinayser Why don't just use CURL or something instead? They'll be done with the console and data notifications soon.

@Svoka you used "notification" as the key, wouldn't it be "data..??
I got this from docs..

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

@xainbutt yes, you're right. This code needs to to do a little modification if you want to send data-messages.

I wonder if we don't face a very recent problem on Android about the ability to receive data-messages while the application is in background.
It worked, for sure as I have a published application built 07/08/16 which perfectly receives data-message sent via API even if it's in background.

But I currently realize that the same project I rebuild now after some updates asked by Google within Studio, cause my application to not receive any data-message anymore while in background.

And that's very new. Could anyone confirm it or not?

I am still looking for a way to Customize the notification message , specifically changing the style to BigTextStyle when the app is in the background. I have a relatively large message which gets ellipsized and more often than not the app is in the background when the user receives a notification from our server.

@2ndGAB Using Firebase 9.2.1 and Play services 9.2.1 notifications arrive in background.

@hossein-85 use the notification fields inside the data field for notifying Android users and then you can make your custom notifications (if you use the notification field you won't get the background notification in your declared Messaging service on Android). Unfortunately this does not work for iOS users, so you have to send separate requests to the Firebase messaging service.

Kind of pain in the ass right now as the behaviour in Android & iOS are different. Android developer unable to make customization in Notification message. It's difficult to show something like (5 new messages from somebody) unless the app server do the calculation which is NOT a good way. Is there any better way other than sending (Data only message to Android & Notification message to iOS)?

@howyongjun if you want full control of the notification on Android then you should send a data-message and since data messages cannot be received while an iOS app is in the background, you need a notification-message for that, so you would have to send two different notifications to each platform.

I understand the desire to send the same message to both iOS and Android as you would not have to keep track of the platforms, thanks for the feedback on this.

@kroikie I got some question about the collapsible. The problem I'm having is I sent 4 different notification message with 4 different collapse_key while the device is offline, then i reconnect to Internet & ONLY receive the last notification message. Is this an issue or i misunderstood the meaning of collapsible?

Using Firebase 9.2.1 and Play services 9.2.1 notifications arrive in background.

@Gloix Do you mean data-only messages or are notifications created from Console working for you? Tested latest Firebase on Android and my app doesn't seem to receive notifications created in Console while in background.

@howyongjun what platform are you checking? collapse_key will not work if you are sending messages to iOS FCM does not hold on to messages sent to iOS devices.

@kroikie i'm using collapse_key for Android only. It seems that some of the behaviour are not the same as what mentioned in the document. For instance, disconnect device from Internet connection --> send different messages with different collapse_key --> reconnect device with Internet connection --> receive only the last message sent. Any idea on this behaviour?

@Gloix did you very recently build a project to verify it still work because It worked for me until begining of july but it don't work anymore for me after recent development environment updates.

Since i am not able to create a custom notification -as talked above- we decided to implement data-only messages via FCM API, and not use console -even though how powerful it is.

But just out of curiosity is there a way that FCM console messages displayed by using colorPrimary | colorAccent or any of resources? And also if the notification gets icon from R.mipmap.ic_launcher or it gets icon from application's icon?

Because i can't know how that automated notification is built, i just wanted to know if there is any resources that build configuration is currently getting data from? So that i may try a work around on those values to get a good look in case of we consider send notification from console in future.
(Right now we do not even mention about it, because it displays a notification with gray background and a white rounded square icon)

@2ndGAB @tiagoshibata I'm sorry for the delayed response. I just tested with Firebase library 9.2.1 through the Firebase console and I received the notification in background.

@Gloix That's a good news.
Can you tell me which Android Studio version do you use?

Edit
But when you say that you receive notification in background, you mean the notification is received in System tray because AFAIK, Firebase console only send Notification message, maybe with data payload, I don't remember well and so, when the app is in background, notification is received by the system tray and data payload is passed to the application by an Intent when you tap the notification right?

@2ndGAB Android Studio 2.1.2. Maybe I should also mention that I included a title, a message and that the target was a single user. The target user was running Android Marshmallow.

@Gloix ok so no data payload message

@2ndGAB Exactly. No data message. I actually didn't include any additional fields in the Firebase console form. Only title, message (I included a message tag as well (the second field in the form) ) and the single target user. App was in background (closed, not open in background), but phone screen turned on.

halo i have same problem , my icon not show on background notifcation just show white background in bar and not popup like foreground notification
i tested on lollipop device
here is my http request

{
"collapse_key" : "demo",
"priority" : "high",
"data": {
"id" : 123,
"message": "kirim data pakan Kolam Siapapuns",
"title": "Log Pakan",
"type": "feed_log",
"content":
{
"pond_id": 5,
"pond_name": "Kolam Siapapun"
},
},
"notification" : {
"title" : "Title"
"body" : "Haloooooo",
"icon" : "myicon",
"sound" : "default",
"click_action" : "FISH_LOGS"
},
"to" : "el4ol2TYUyg:APA91bG6YrtvgAdNHxLxxxXX"
}

whats wrong with my request ?

@abdymalikmulky Are you supposed to receive your data message in onMessageReceive()?

@2ndGAB i have created my onMessageReceive() , that method just call when app in foreground
this is my screenshoot

foreground notification (notification that i want)
photo264167697778059618

background notification

  1. Just show the white background icon (even though my color parameter is works)
  2. not showing notification like in foreground
    photo264167697778059620

photo264167697778059619

i just confuse of FCM behavior , Would be very helpful. Thanks.

@abdymalikmulky ok so if I understand well, when the application is in background, the Notification is received by the system tray and not your application.
I never tried it so I cannot help you about the problem you have with your icon. I'm really sorry.

I'm not so experienced with FCM but the basics are the following.

When your application is in foreground, the notification and the data payload is received by onMessageReceive() as you do.
When the applicaton is in background, there are 2 situations:

  • You send a Notification only message and it's received in the system tray and displayed as you observe but your application is not informed about it.
  • You send a Notification with a data payload like you do and the behavior is the one explained just above except that the data payload is passed to your application via the Intent you receive in your main activity when the user tap the notification which cause your app to be started.

But if you have time, I would be very interested that you try to create your notification in your application, based on data message only.
That suppose to send the message from Google Advanced REST Client Google Advanced REST Client

Then you receive the data payload in onMessageReceive() as you certainly do already and you generate your notification from onMessageReceive() as you may do already but in case and just for a very simple test:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getData());

    sendNotification("FCM message received");

}

private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_ic_notification)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, notificationBuilder.build());
}

I would be very interested to know if a notification is created when you send the message while the application is in background.
ic_stat_ic_notification (drawable hdpi)

ic_stat_ic_notification is attached.

Is it possible to use GCM receiver and FirebaseMessagingService's onMessageReceived(RemoteMessage remoteMessage){..} both at the same time.

It appears to me that when I send notification from Firbase console and app is in background... in my code both GCM receiver and FCM notification is showed.

first, is the notification showing icon app, sound and other same as property that you set in onMessageReceived() ?
second , how if the app was killed ? the notification still show "normally" ?

@abdymalikmulky yes... When App is in background firebase shows default notification as per documentaion.

In my code I have kept both GCM receiver and FirebaseMessagingService. My problem is when I send message from firebase console it invokes GCM receiver as well as Firebase notification.

thank you @KishorAndroid , i will try it

@abdymalikmulky I have same issue ...When you can solved then please Tell Us!!

and How to set BigPictureStyle() in FCM notification when app is in background or Destroyed!!

Why is this issue closed? Since the main issue was about "Custom Notifications when app is in background or killed" and not solved yet? Does this mean we should not wait for a fix to this? I was really hoping Firebase team to be working on this.

@yayaa I think you need to read all the thread first. It's definitely not a bug and everything is working as planned

I know it is as planned, but i thought at least this would be considered as feature demand. Most of the applications icon's somehow has a background, and when firebase applies white tint on it to display as notification icon, it is mostly white squared empty icon or some non-sense icon there. At least, customisation on icon - color and so on. I see on notification message documentation there are some fields like that and i thought maybe it's already done and i missed that, but when i try to send that from console as additional params in advance section, i saw no changes. That's why i actually said no improvements on this topic. @Svoka but thanks anyway.

@yayaa oh, I think I get it now. In my case I don't need console at all, because we have server with this logic. So we send data-only messages. (Console still can't do this, I guess)
By the way, you can provide icon from console:
it's R.drawable.#_ICON_STRING#

I know with data messages you can do anything. But we talked about having notification messages sent from console would also be customizable. And then i saw that issue was closed... :(

@yayaa I guess we need to create separate issue for that :)
In context of possibility to show icon this issue is closed.

Create new issue https://github.com/firebase/quickstart-android/issues/139

@Svoka Can you confrm that you build your application with Android Studio 2 to receive data only messages to background application?

@yayaa I don't think if I undertsand you well but if your are talking about icon appearing on status bar when you receive a notification, they are mandatory white on transparent background since Lollipop.
This icon is set like that:

Notification.Builder..setSmallIcon(android.R.drawable.my little_icon)

Yes, i am aware of that @2ndGAB . But the problem here is when you have an icon with some graph on a solid background, and when firebase automatically creates your notification icon by tinting your application icon as white, it ends up like @abdymalikmulky screenshot.

Anyway since this issue is closed, i will just stop watching until i need to use Firebase again, and just hope them to fix it by then.

@yayaa That's very strange, here is how I create my notification from a data only message, received in onMessageReceived()

        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.launcher_icon);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_logo_notif)
                .setLargeIcon(bm)
                .setContentTitle(title)
                .setSound(ringURI)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg).setSummaryText(this.getString(R.string.label_service)))
                .setContentText(msg)
                .setContentIntent(contentIntent)
                .addAction(R.drawable.ic_action_place, null, geoPendingIntent)
                .addAction(R.drawable.ic_action_web_site, null, webPendingIntent)
                ;

And here is the result: first the litle monochrome icon white on transparent background
And here is when you open the notification center

You can see that if you provide a valid little icon with setSmallIcon(), you won't have a white square in the status bar, same if you provide a valid large icon with setLargeIcon().

I usually build my icons with Android Asset Studio

I want to send a image in push message using firebase consol how can i send image in push message any solution.and also i want to custom look of notification..?

I want to send a image in push message using firebase consol how can i send image in push message any solution.and also i want to custom look of notification..?

I send User segment push notification but All user don't get push notification Why all did not get? From console.firebase.google.com I found monthly active user 4100 but when i send notification It shows 2100 send. and every time i got notification in 7 to 10 phones out of 12 different phones. That mean 50% user found notification. then what would be be others.

A notification is sent but does not reach all devices. 70% - 80%.

$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
    'registration_ids' => $registatoin_ids,
    'priority' => 'high',
    'data' => array("notification" => true),
);

@jaydip5500 data message payload is 4 KB only. Difficult to send an image.
Maybe you could send an URL used by your application to get the image from your server.

@tariqul000 @yerca Do you respect the limit of 1000 notifiactions sent at a time, then the exponential delay between 2 successive requests?

@2ndGAB Yes I do. I send 500 notifications every 1 minute, to not load my server.

an example of response.

{"multicast_id":xxxxxxxxxxxxxxxx,"success":500,"failure":0,"....

Ok good, no more idea.... sorry

@yerca Have you linked FCM with the Play Store console? You can check the FCM Statistics to see if there were errors sending to devices. Maybe the messages were queued/stored?

@2ndGAB @efung Thanks. I've looked. Many messages are in state accepted but not confirmed.

I have solved this problem.
In some devices, when the app is in background or killed,it really has this problem,but some devices not,maybe it has some relation with the android version or google play services version.
If you use the GCM api to send the notification ,the ic_launcher icon can be showed well.
If you use the Firebase Console to send the notification, your ic_launcher need to make some modification, the background must be transparent, just like the picture below.
Firebase will give a better solution and coming up very soon.
25

@abdymalikmulky modify your ic_launcher just like what I do

sorry... but imho, modify icon/logo design just for bug in library is a unacceptable workaround...
I could tolerate an alternative default file name instead ic_launcher

Update the version to the least ,current is 9.8.0, than follow the solution below,
https://firebase.google.com/docs/cloud-messaging/android/receive

finally ! thanks @chenyucheng97

@JulienDev @chenyucheng97 please tell the version you used for resolving this issue.

hi,i have the same problem. When app is killed,my app can not receive notification?i want to know why and how to solve that?

Hi!

I'm having the same issue... However, Is it possible to show the notification when the App is launched?

Thanks in advance

@PaoloApplingua yes its possible, you can try create and call notification manager notify same as you call notification from FCM

Couldn't agree more. One year passed and it's still not possible to control background notification and/or send data messages via the console unfortunately.

Meanwhile, people seem to get around the issue with hacky workarounds overwriting undocumented functions in FirebaseMessagingService like so:

https://stackoverflow.com/questions/37325051/notification-icon-with-the-new-firebase-cloud-messaging-system

Only thing that seems to work so far, but I'd rather refrain from that. Otherwise, why wouldn't it be mentioned in the docs.

shinayser commented on Jul 14, 2016
Just want to leave my feedback about the notification framework:We as developers should have full control of the notifications. I never wanted FCM to auto-notify my system bar for me and i should ALWAYS receive the "onMessageReceived" callback, doesn't matter in foreground or background.
Pehaps we could have a checkbox on the Firebase Notification console indicating "Auto-notify". If unchecked, we get the "onMessageReceived" callback. Otherwise, it notifies the system bar.

I have the same problem.

Application mode background or killed at that time FCM not call "onMessageReceived".

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    // Called when message is received.
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
           Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }
  }

I have really weird and frustrated problem, and I have no idea why it is happening. I have application signed and published as closed beta release on Google Play store. I have installed it on my phone and sending push message with data payload from my Digital Ocean droplet, works on my Huawei P9 Lite Android 7 even when application is killed, onMessageRecieved is always activated, but on the other phone Huawei P8 Lite, no notification is received, only when application is in foreground and in background (not killed)

So I have created this application to try and figure out what is happening: https://github.com/clzola/firebase-test (you will find php directory in which you can find scripts I use to send messages)

So here are the steps:

  1. Run application
  2. Copy token
  3. Kill application
  4. $ php notification.php "token"

on my phone, notification is shown in tray (Huawei P9 Lite, Android OS 7)

On the other phone (Huawei P8 Lite, Android OS 6), same steps reproduced, no notification in tray

I have tried to send only data payload, same scenario on p9 lite works, on p8 lite does not work, also tried with sending both payloads, notification and data payload, same thing, on p9 lite works on p8 lite does not.

When application is running on p8 lite (app is in foreground) sending messages with notification payload only, data payload only and both payloads works, also if I click back button and application goes to background also works all three type of messages. Now I swipe off application (killing it), none of the above messages are received on p8 lite. I have also tried to sign apk, send it to my email, detach phone from lap top (Android Studio), restart phone, and then installed signed apk, opened application, read the token, kill application and send notification payload only message and there is no notification in tray...

As I understand, Google Play Service should receive this notification message payload and show it in tray when application is not running ....

I noticed this message in logcat, it is printed out each time I send message to my phone when application is not running:

08-18 19:17:41.602 4565-4565/? W/GCM-DMM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=clzola.com.firebasetest (has extras) }

Also sending from Firebase Console I get same results

EDIT: I have figured out what was the problem, Huawei's EMUI has this Protected Apps system, and there I found both of my applications and switch that was off, I put switched on and both applications works on P8. Next question is why on my Huawei P9 Lite phone, they were switched on automatically with my interaction ... however I have found two Xiaomi phones that have same scenario but cannot find option similar to Protected Apps...

I couldn't believe that this was not possible. It is not clear from the docs that you can only modify the notification when the app is in foreground and it also is not logical. I understand that there is a possibility to let Firebase handle this, but you should be able to override this. The "data message" is not a good solution because iOS will not show the notification anymore.

I like the way I can handle the notification when the app is in the foreground, so if that would also be possible in the background, that would be great and also way more logical.

In the meantime is there anything I can do to make this work on iOS and Android? On Android I want to show my own custom notification (which can open in different activities, have a different priority, different styles and different notification tags). This custom notification currently only works in the foreground. Also I want iOS to stay the same (show the notification when push message is received and when opened same custom tasks like on Android). Currently the only possible solution I see is to send a "data message" to all Android users on a specific topic and the "notification message" to all iOS users on a specific topic.

Please tell me there is another way to do this. Because this is just horrible...

It's been trending topics about Firebase Cloud Messaging that Data Payload message is not fired onMessageReceived() method for some lower end device. And it's true. Here is the result.

App is killed scenario

**Devices got payload:: 1. Nexus 5s : OS 7.1

Device not get payload:: 1. Xiomi MI 4c: OS 5.1 2. Huawei LUA -U22 :OS 5.1**

Ensure that i'm not sending notification key from server / postman.

I am looking for the solution, i got data payload from firebase including all types of devices and Android OS & obviously From API level 15. My postman details are as follows.

 {
    "registration_ids": ["fC5uxGSRCsg:APA91bHh9fMXQ41LpX6tjjSsBKGrKTWYpzKimLDzvBGSHDPo2pq87JHqogUp2kqrmJi06siG_p6DfgRCim23iFzlBQAIrgtMDqRW4s39zUqv9CzyPqzxVl5PtnHPRDs4OagTuTePNyDI"],
    "data": {
        "title" : "my_custom_value",
        "message" : "tekksdasdasdsa",
         "isBackground" : "",
          "payload" : {


          },
           "timestamp" : "",
            "imageUrl" : "",
     }

}

the only way to resolve this issue is to use the handleIntent method. This function will always get called. or we can go back to GCM

    @Override
    public void handleIntent(Intent intent) {
//        super.handleIntent(intent);
        Logger.d(intent);
        Logger.d(intent.getExtras().getString("key"));
        Logger.d(intent.getExtras().getString("gcm.notification.body"));
        Logger.d(intent.getExtras().getString("stuff"));
       if(intent.getExtras()!= null){
            notification_msg = intent.getExtras().getString("gcm.notification.body");
            notification(notification_msg);
        }


}

In FCM, you can no more send silent/Custom push notification to the apps running in Background by using console. You have to use POST request to send them.

The details can be found out here https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol

PS: Make sure for sending custom push notification, you are having just 2 keys in body - data and to

What about showing image from url ? I want to add imageUrl when sending notification from Firebase Functions. Something like:

const payload = {
                                notification: {
                                    title: `xx`,
                                    body: 'xx,
                                    icon: 'imageURL',
                                },
                            };
return admin.messaging().sendToDevice(tokens, payload);

Notification is received when app is in background.

Agree with @jemshit. It was really convenient to specify a link for icon in notification push. Are there any plans to add this?

Thank you.

@pavelshackih @jemshit thanks for that feedback, the team is looking into this type of feature.

I'm still having issues with firebase push notification.
It only customizes my push notification when the app is in the foreground.

Hi!
I need to somehow remove extras from an intent that was delivered by FCM.
1) App is closed
2) I send push notification from the fcm
3) When a user clicks on notification tray icon app starts and retrieves data from intent's extra
4) Then I want to clear these extras to prevent unexpected behavior in the future (I use intent.removeExtras())
5) After that, I click the back button (an app is closed), then through task manager I choose my app
6) An app is started and intent still has extras from fcm in it.

Question: how I can completely remove given extras?

@BulatMukhutdinov pressing the back button does not close the app. Your activity might be resumed with the same intent as the previous one. Maybe if you swipe your app away from the recents screen then you would have your app launch with an intent with empty extras. I would suggest having some type of check to see if the extras have already been handled so you can ignore them if so.

@kroikie yes, an app doesn't close, but the activity is recreated. Although I remove extras, the recreated activity still receives these extras. Is it intended behavior? How can I completely remove extras?
Sure, I can store somewhere if I have already handled extras but it seems to me as a workaround

@BulatMukhutdinov I was able to reproduce this. I believe the recents menu reuses the intent last used by the activity. As you have seen, I don't think removing the extras from the intent in the activity has an effect on the intent used to recreate the activity from recents menu.

Maybe in a future release we could add controls that will allow the developer to define how the launched activity is handled by the recents menu but for now you will have to handle those intent extras yourself.

Why does not SDK call onMessageReceived in background? I can not find a reasonable reason.

Two years passed and we still dont have solution for this ?

My app built using ionic 3, and it can receive the notification message just fine through FCM when the app is closed/killed,

But it can't show the data message received. Mean i can't customise the notification style. I can't show the picture, can't show the button, and can't give user custom action.

Currently, user need to tap the notification in the tray, which will open the app, then only the second notification, containing the data message, appear.

Is there really no way to directly push the notification with data messages when the app is killed ?

Why this issue is closed?!

BTW, _about the first post_, the user @CarmelRaj07 reacted with

thumbs down emoji
laugh emoji
hooray emoji
confused emoji
rocket emoji
eyes emoji

And I can tell [s]he reacted with thumbs up and heart too. what a mess!!

[S]He did it again with all available emojis for thedumbtechguy's comment too.

i has know how to handle this issue.

Mehdi Dehghani notifications@github.com 于2019εΉ΄6月12ζ—₯周三 δΈ‹εˆ2:24ε†™ι“οΌš

Why this issue is closed?!

β€”
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/firebase/quickstart-android/issues/4?email_source=notifications&email_token=ABMS2DPHR7OWLM63HJ5A5DLP2CJCTA5CNFSM4CEJOTS2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODXPMBVI#issuecomment-501137621,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABMS2DOCUA2KGYXUYGOOSCDP2CJCTANCNFSM4CEJOTSQ
.

@flyme2012 thank you, actually I found the solution. of course after posting my prev comment.

I'm not sure if anyone has mentioned it, but of course it's possible to have custom notification! The only thing is that you should do it yourself! From the server, you only send the message payload (data message) in your push notification. Then in your phone side, like Android, you create the notification manually by using the information you receive in the push notification message payload. For example, this is a snippet that can work on your server, in Python:

from pyfcm import FCMNotification

api_key = "YOUR SERVER KEY"
registration_id = "Your user FCM registration token"
data_message = {
    "title": "ntf title",
    "body": "ntf body",
    "style": "a string that represent what you want, you will use it on the phone side."
}
push_service = FCMNotification(api_key=api_key)

result = push_service.notify_single_device(registration_id=registration_id, data_message=data_message)

print (result)

Then on Android side, you need to write your code for handling push notification. Basically what you can do is creating a notification, with title and body. Then for the style of the notification, you will decide according to style that you receive from FCM. It's completely up to you what to do, how to create the notification and its style.

Android example by Firebase, open the link to see the whole section.

Getting message Payload example

https://github.com/firebase/quickstart-android/blob/375c1ae5ec9000ee71b93cee409086e27d774bdb/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/kotlin/MyFirebaseMessagingService.kt#L43

Creating notification function (open the link to see sendNotification function)
https://github.com/firebase/quickstart-android/blob/375c1ae5ec9000ee71b93cee409086e27d774bdb/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/kotlin/MyFirebaseMessagingService.kt#L114

hey @ckarthikv
actually i am facing a issue in IOS when the app is in background.

608 Can you please have look into it,.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

llooz picture llooz  Β·  5Comments

DenLangeKilde picture DenLangeKilde  Β·  5Comments

tekinarslan picture tekinarslan  Β·  5Comments

shivamsriva31093 picture shivamsriva31093  Β·  3Comments

the-dagger picture the-dagger  Β·  4Comments