Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Heads Up notification in android using Firebase Cloud Messaging(Notification) while the app is not in foreground?

I have an app that should show headsup notification while the app is in both foreground and background(not in history).

In foreground case , i acheived this by the folowing method.

PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
    builder.setFullScreenIntent(pendingIntent,true);

But in background, it always showing in the notification area.Can anybody tell how to acheive this in background(not in history)

i tried the below parameters for notification but not working.

{ 
    "to" : "_Token_", 
    "priority":"high",
    "data":
    {
        "title": "Test",
        "text": "Fcm"
    },
    "notification":
    {
        "title": "Test",
        "text": "Fcm"
    }
}
like image 232
SachinS Avatar asked Mar 03 '17 13:03

SachinS


People also ask

How do I handle the Firebase notification when an app is in foreground?

Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded apps to receive notification messages or data messages, you'll need to write code to handle the onMessageReceived callback.

How does Firebase push notification work internally?

The FCM backend receives the message request, generates a message ID and other metadata, and sends it to the platform specific transport layer. When the device is online, the message is sent via the platform-specific transport layer to the device. On the device, the client app receives the message or notification.


2 Answers

You should completely delete notification part from your Json and just use data ! That's the trick. I mean this:

{ 
"to" : "_Token_", 
"priority":"high",
"data":
{
    "title": "Test",
    "text": "Fcm"
}
}

When you have notification tag in your Json, sometimes the library decide to handle the notifications itself. so when your app is in foreground it wont call your on message receiver and it show the notification itself.

Just remove the notification and always use data tag.

It works both when your app is in foreground/background or killed and stopped

like image 66
Omid Heshmatinia Avatar answered Sep 18 '22 16:09

Omid Heshmatinia


Firebase allows notification customization when data messages are used. Data messages invokes onMessageReceived() method even when the app in backgroud so you create your custom notification.

You can take reference of this link to know more about data notifications Firebase notifications

like image 29
Neha Avatar answered Sep 19 '22 16:09

Neha