Quickstart-android: FCM when app in background

Created on 25 May 2016  ·  50Comments  ·  Source: firebase/quickstart-android

Hi,

The FCM works fine when the app is in foreground and a push comes, but when the app is in background and the system tray notification is clicked , it just opens up the app without passing any intent extras. I have added the click_action in Notification Payload from Advanced option of Firebase Console to open an activity but it dosen't work. I have also added the intent-filter ( handle backgound app section) as in documentation.

How can i open a specific activity using FCM service along with the data i pass when the app is in background or exit state.

Most helpful comment

Hi @kroikie

I have a follow up question.
According to this documentation, the notification will be delivered to the device's system tray when the app is in background which means onMessageReceived() won't get called, but I wonder if there's any way that I can customize the icon in the notification view. Currently, it shows default white icon.

All 50 comments

Hi hablema, thanks for giving FCM a try. You mentioned a couple of things:

  1. you are not receiving the data sent along with the notification message.
  2. and the click_action from the console does not result in the correct activity being launched.

So if I understand your issues, there are a couple of things to note:

  1. The data sent along with the notification message (which is the type of notification sent from the console) is accessed from the intent extras of the activity that is launched when the notification is tapped. Have you tried to get the data from the activity intent extra?
  2. You cannot currently set the click_action field from the console. The custom data in the console are only for data key value pairs, you cannot configure any of the notification message fields via the custom data fields.

Hi @kroikie

I have a follow up question.
According to this documentation, the notification will be delivered to the device's system tray when the app is in background which means onMessageReceived() won't get called, but I wonder if there's any way that I can customize the icon in the notification view. Currently, it shows default white icon.

Hi @kroikie

I am looking for the same solution as mentioned by @wassupnari. Can we achieve that or it is not possible with FCM. As using FCM on iOS we have background mode do Android also have same background mode using FCM or not.

@avirepo @wassupnari these customizations are possible through FCM but not yet through the console UI, you have to use the HTTP API.

You can see more discussion on #4, I am going to close this issue as we are tracking this feature request elsewhere. We know this is important to everyone so the team is working hard on it.

@kroikie : Thanks for info. I got it working as you have mentioned from the intent of the activity. The documentation should have been more clear in that aspect with a full sample manifest. Its good now, also i had a problem in which the FCM messages from console only started delivering after i tried from the HTTP API. Don't know why but after that its working directly from the console. Thanks again.

Hi Team,
Thanks for this module.

Works just fine except this issue. when the app is in background , and during cold launch from notification, the app is getting opened but how to access the notification data, and do some activities with that. Unlike the PushNotificationIOS's popInitialNotification, I dont think we have any function that will get the data. Can someone help me if you have made it work. @hablema
Thanks in advance

Hi @rimzici, on Android when your application is in the background and a notification message is sent the accompanying data payload (if included) is available via the launched intent resulting from the developer tapping on the notification. By default that would be your MainActivity, you can find an example of this in the messaging sample in this repo.

For more on handling data accompanying a notification message see the docs.

@kroikie ,
Thank You very much for your response. Actually it worked for me by using FCM.initialData, which provides data, both during cold launch and background running.
in the documentation its specified under "Behaviour when sending notification and data payload through GCM" , but since iam using FCM to send push, i must say both users can retrive data using that property.(this.initialData = FCM.initialData;)
Thankyou.

So does it mean that data-message only are not received anymore when the application is in background?? The doc is really fuzzy on it.

If yes, that's a very new behavior and it's what I'm facing in my application for few days because I built and published an application on 07/08/16 (FCM 9.2.0) which perfectly receives data-message sent by API while it's in background, on a Samsung GT-9295 5.0.1 and on a Nexus 7 6.0.1 and it's what I do for a long time in GCM then in FCM.

But starting from the working project built one week ago, I realize that now I rebuild it, the generated app is no more able to receive anything in background.

I tried to upgrade to FCM 9.2.1, same.

So there is something new in my environment, sdk, studio, java, I don't know, which causes this very important feature to not work anymore.

Why?

After a deep search, I have found what is going on: There are two types of messages in FCM:

  • display-messages: These messages only work when your app is in foreground
  • data-messages: Theses messages work even if your app is in background

Firebase team have not developed a UI to send data-messages to your devices.

To achieve this, you have to do a POST to the following URL:

https://fcm.googleapis.com/fcm/send

And the following headers:

  • Key: Content-Type, Value: application/json
  • Key: Authorization, Value: key=<your-server-key>

Body:

{
    "data": {
        "my_custom_key" : "my_custom_value",
        "other_key" : true
     },
    "registration_ids": ["your-device-token","your-device2-token","your-device3-token"]
}

To get your server key, you can find it in the firebase console: Your project -> settings -> Project settings -> Cloud messaging -> Server Key

Hope this helps!

Ref: How to handle notification when app in background in firebase

@pratikbutani That's sure, but according to lot of tests I did, applications built with Studio 2.1.2 can't work.

https://github.com/firebase/quickstart-android/issues/89

Anybody please let me know is it not possible to show custom notification instead of default when app is in background or is not running while using FCM.

@anujjpandey11 Yes it's possible by sending a data message which will be received by onMessageReceive().
Then based on the information sent, you can create your own notification using notification builder.

I already tried it but it is only work when app is in foreground.

Note: I'm sending message from firebase console.

AFAIK, firebase console is not able to send data only messages, unles it has been updated very recently.

To do that, I use Google Advanced REST Client

And configure it like here
Of course data are mine, replace everything in data by the infos you need.

Thanks @2ndGAB

Hi Team,
@kroikie : Well the issue still persits, I thought i had it solved but i was stupidly mistaken.
I looked into the links that you have suggested https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MainActivity.java#L37
, from there can you suggest me some way , how to pass the data from the MainApplication.java(MainActivity.java : RN < 29) to our react-native screens.(say like i need the data on one of my navigator screen).
Well after following some others issues and suggestion I tried like way too.
Initially, as suggested in react-native-fcm docs, in my backend i was sending data like this,
{
"to":"some_device_token",
"content_available": true,
"notification": {
"title": "hello",
"body": "yo",
"click_action": "OPEN_ACTIVITY_1"
},
"data": {
"extra":"juice"
}
}

and in my mainfest file, i have
<intent-filter> <action android:name="OPEN_ACTIVITY_1" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
so when app is fully closed and in background on clicking notification my app is lauched, but during background case no data in "FCM.initialData" or "FCM.on('notification', (notif) => { })" event.

with the same manifest I tried DATA ONLY push like

{
"to" : my_token,
"data": {
"id": 19,
"title": "Title test",
"msg": "Text of the test"
}
"content_available": true
}

that time notification not even received in the tray. gets data when app in open. So I assume without "notification" key device wont receive push in tray.

So after all I come to conclusion that only way is what you have said already to handle it somehow like

if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}

someone help me how to pass this data from MainApplication.java to our javascript file.
or is there any work around y using react-native-system-notifivation along with our fcm, as they gave done in GCM ????
Need Help
Thanks In Advance

Hi.
Do anyone have a working solution for this??
I tried by sending "DATA ONLY" message iam able to receive push message inside FCM.on('notification',()=> {
});
but not in notification tray, so I have created a custom notification using react-native-system-notification.
that has only made the situation worse. Iam not able to receive push notification at
"FCM. initialData" , where it used when app is not running. not only that , that module "react-native-system-notification" is not maintained well , it has alot issues.
So got to stick with "notification" message or hybrid message.
someone help how to receive notification data when app is in background.

@rimzici I don't think that, messages from the Firebase console (notification messages) are supported by React Native. I would suggest that you use data messages (sent from the REST API) and generate your own notifications.

Hi,
@kroikie , Well, may be i would have messed up with something, still a newbie.
Anyway finally It all came together.
after upgrading to
"react": "^15.2.1",
"react-native": "^0.31.0",
"react-native-fcm": "^1.0.16",

it all works perfectly.
thank you very much team.

If I send User segment push notification 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. That mean 50% user found. then what would be be others.

With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/white_status_icon" />

FCM background notifications works on all the android versions except Android 7.. When the app is in the background I get the notification and once I tap the notification I can open the activity and read the intents,
however on Android 7 when I receive the ratification in the background the tap fails to open the activity

is there something that I'm missing for Android 7?

Ya esta solucionado el poder darle manejo a los mensajes que llegan mientras la aplicación esta totalmente cerrada ?

Hi All

The issue still remains - if sent push with notification and data when app on bakground - notification arrives but no extras on launching activity. In all other scenarios when app killed /open data arrives to extras of activity/onMessageReceived.

Please help

Example of postman body:

{
"to": "my_token",
"notification": {
"title": "title_here",
"body": "message_here"
},
"data": {
data_key_here : data_value_here
}
}

I don't know about notification + data, I use data message only and I create the notification by myself in onMessageReceive. That now works from AS 2.2.2 and also 2.2.3.
I use Firebase 9.8.0. I didn't try with the new 10.0.1 yet.

EDIT
I recently discovered a maybe new issue; data messages are not received when you've installed a debug apk. arghhhhh!!!

Thank you notification/ data only also works. I need to take care of this exact scenario: notification with data & app on background

My issue was when activity arrive to onStart - he still have old intent. So I override onNewIntent func and set the new Intent to be the one of activity. In such case onStart it rceives Intent with data from push

Same problem on my side.
I got the push when app is in foreground or background. When I tap the push notification, I'd like to go to the specific activity.

Here is my code chip for that.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
//It is optional
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

    //Calling method to generate notification
    sendNotification(remoteMessage.getNotification().getBody());

}

private void sendNotification(String messageBody) {

    Intent intent = new Intent(this, ConnectCallActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(ConnectCallActivity.class);
    stackBuilder.addNextIntent(intent);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("EntryView")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

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

}

It works well when app is in foreground, but just open the app(Launcher activity) when app is in background.
Thanks for any advice.

@SelfnessAid in case you want to start the app by tapping the notification, this code is not concerned.
Your app will be started with an intent as parameter and that is the information you have to process.
But of course, you have to prepare your intent with the relevant informations.

Here is the code you need:

In your sendNotification(), add the parameters you need to your intent.

Intent intent = new Intent(this, ConnectCallActivity.class);
intent.putExtra("myInfo", "This is an example of information I need when the user tap the notification");

Then I'm not sure about your flag PendingIntent.FLAG_ONE_SHOT, personnaly, I use:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

After, you have to add code in your MainActivity().

Add somewhere in onCreate(), the following call:

    processExtrasData();

Then also add the following method. (@aaalive yes, that point is the key!):

protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);    //must store the new intent unless getIntent() will return the old one
    processExtrasData();
}

And so you processExtrasData() function:

private void processExtrasData() {

    Bundle extras = getIntent().getExtras();
    if (extras != null) {

        String myInfo= extras.getString("myInfo", "I didn't found any info"));

        Log.i("MyApp", myInfo);
     }
}

I hope it will help you.

Hi, @2ndGAB
Thanks for your help.
But I have one question about your answer.
Where should I define the onNewIntent(Intent intent) func ?
Sorry, I am new guy of Android app development.

Hi @SelfnessAid
The onNewIntent(Intent intent) func is a pre-defined method in activity which gets called when an exsisting activity is brought up front (by opening it using an intent). So in this onNewIntent(Intent intent) you get the new intent.
You can simply override it in the activity.

Thanks, @Siddharth-Dev
Got it

Hey guys,

Is FCM what i need to fetch data in background from FirebaseDataBase?
My current setup doesnt observeSingleEventOfType:withBlock

@samkerm yes you can use FCM to fetch data from the Firebase Realtime Database. Note that if you open a listener in the background and leave it open it may affect battery life.

I can receive notification even if app is killed but when app is killed i sent 3 message from server i could receive only one message(which sent lastly) when i tap the notification and move into app
Any help to get all message which i sent to be received when i get back to my app

Don't worry. i'm fine

나의 SOL에서 보냄




      1. 오후 2:08에 christianraj notifications@github.com님이 작성:I can receive notification even if app is killed but when app is killed i sent 3 message from server i could receive only one message(which sent lastly) when i tap the notification and move into app


        Any help to get all message which i sent to be received when i get back to my app



—You are receiving this because you are subscribed to this thread.Reply to this email directly, view it on GitHub, or mute the thread.

When app is in killed notification is not visible neither is data. it's been whole day I am trying to get a notification when app is killed. I have tried sending only notification and only data from Postman but nothing works when app is killed. FCM does not launch any notification. it only works when app is in background or foreground. Has anyone actually found a solution?

@achavhan Do you use a recent Android Studio version?
I personnaly use data message only but in that case you have to build the notification by yourself in onMessageReceive.
I suppose it's what you do.

@2ndGAB In my leeco 1s auto start was turned off by default. Giving permission of auto start solved the issue. Now I am looking for the reason why it didn't work in emulator.

my personal advise is use phonegap-push-plugin

---- On Thu, 09 Mar 2017 22:11:10 +0530 AMOL CHAVHAN <[email protected]> wrote ----

When app is in killed notification is not visible neither is data. it's been whole day I am trying to get a notification when app is killed. I have tried sending only notification and only data from Postman but nothing works when app is killed. FCM does not launch any notification. it only works when app is in background or foreground. Has anyone actually found a solution?


You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or mute the thread.

i got a solution for that.
just put below code in oncreate method of launcher activity.

if (bundle != null) {
        String value = bundle.getString("key");
        if (value != null) {

            startActivity(new Intent(MainActivity.this, secActivity.class));
        }
}

when app is in background or killed,FCM will not call onmessagerecieved method,but it will send data to system tray to display notification.so datapayload(sent from fcm console) will not be handled by onmessagerecieved method.when user click on notification,it will launch default activity of app and datapayload will be passed by intent .so making change in oncreate method of launcher activity(as above)we can get datapayload even when app is in background or killed.(ex key is sent by fcm console).when app is in foreground datapayload and will be handled by onmessagerecieved method of fcm service.

thank you

---- On Wed, 22 Mar 2017 10:38:51 +0530 tushar2812 <[email protected]> wrote ----

i got a solution for that.

just put below code in oncreate method of launcher activity.

if (bundle != null) { String value = bundle.getString("key"); if (value != null) { startActivity(new Intent(MainActivity.this, secActivity.class)); } }
when app is in background or killed,FCM will not call onmessagerecieved method,but it will send data to system tray to display notification.so datapayload(sent from fcm console) will not be handled by onmessagerecieved method.when user click on notification,it will launch default activity of app and datapayload will be passed by intent .so making change in oncreate method of launcher activity(as above)we can get datapayload even when app is in background or killed.(ex key is sent by fcm console).when app is in foreground datapayload and will be handled by onmessagerecieved method of fcm service.


You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or mute the thread.

If app is in Foreground you can receive the "Notification" as well as "Data" in "onMessageReceived"
and there you can create PendingIntent including the click action.

But if the app is running in background the "Notification" is delivered to SystemTray but the "Data" is delivered to "Intent Extra" if you deliver Notification and Data both at same time. So instead in you "onMessageRecieved" method, what you need to do is. In you Activity where you are redirecting users to when they click notification.

Just create :

String data_message = getIntent().getStringExtra("data-key");

Replace "data-key" with the key of data.

Say for example :

const payload = { notification: { title : "Notification Title", body: "Notification Message", icon: "default", click_action: "TARGETNOTIFICATION" }, data: { message : "Notification Message" } };

If you want detailed explaination, you can checkout :
https://www.youtube.com/playlist?list=PLGCjwl1RrtcRHjHyZAxm_Mq4qvtnundo0

Hi Guys , the only issue i am facing is with ionic 3 cordova fcm plugin , the push notification shows up silently in the systems tray whereas i want the the notification to pop out and display like chat notifications do on whats app or instagram.. what can be done about this.?

Is this possible to send a notification from FCM for background app.
I don't have my own server to store token key

In Meizu M1 Note data-only push comes if app is foreground/background? but if app is killed onMessageRecieved is not call.

    // Handle possible data accompanying notification message.
    // [START handle_data_extras]
    if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            Object value = getIntent().getExtras().get(key);
            Log.d(TAG, "Key: " + key + " Value: " + value);
        }
    }

everything is working fine ,
issue is i want to increase badge count as soon as notification is recieved which is possible in foreground ,
for Background i have used Notification tray so badge is increased only when i click notification when i clear noti and open it doesnt increase badge .

Was this page helpful?
0 / 5 - 0 ratings