Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FCM when app in background #20

Closed
hablema opened this issue May 25, 2016 · 51 comments
Closed

FCM when app in background #20

hablema opened this issue May 25, 2016 · 51 comments

Comments

@hablema
Copy link

hablema commented May 25, 2016

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.

@kroikie
Copy link
Contributor

kroikie commented May 25, 2016

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.

@wassupnari
Copy link

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.

@avirepo
Copy link

avirepo commented Jun 13, 2016

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.

@samtstern
Copy link
Contributor

@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.

@hablema
Copy link
Author

hablema commented Jun 13, 2016

@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.

@rimzici
Copy link

rimzici commented Jul 13, 2016

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

@kroikie
Copy link
Contributor

kroikie commented Jul 13, 2016

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.

@rimzici
Copy link

rimzici commented Jul 15, 2016

@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.

@2ndGAB
Copy link

2ndGAB commented Jul 15, 2016

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?

@pratikbutani
Copy link

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

@2ndGAB
Copy link

2ndGAB commented Jul 25, 2016

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

#89

@anujjpandey
Copy link

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.

@2ndGAB
Copy link

2ndGAB commented Aug 3, 2016

@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.

@anujjpandey
Copy link

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

Note: I'm sending message from firebase console.

@2ndGAB
Copy link

2ndGAB commented Aug 3, 2016

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.

@anujjpandey
Copy link

Thanks @2ndGAB

@rimzici
Copy link

rimzici commented Aug 8, 2016

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

@rimzici
Copy link

rimzici commented Aug 9, 2016

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.

@kroikie
Copy link
Contributor

kroikie commented Aug 10, 2016

@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.

@rimzici
Copy link

rimzici commented Aug 16, 2016

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.

@tariqul000
Copy link

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.

@paisrikanth
Copy link

paisrikanth commented Nov 4, 2016

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" />

@paisrikanth
Copy link

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?

@EstebanMV96
Copy link

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

@aaalive
Copy link

aaalive commented Dec 13, 2016

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
}
}

@2ndGAB
Copy link

2ndGAB commented Dec 13, 2016

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!!!

@aaalive
Copy link

aaalive commented Dec 13, 2016

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

@aaalive
Copy link

aaalive commented Dec 19, 2016

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

@WebMobi59
Copy link

WebMobi59 commented Dec 26, 2016

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.

@2ndGAB
Copy link

2ndGAB commented Dec 26, 2016

@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.

@WebMobi59
Copy link

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.

@Siddharth-Dev
Copy link

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.

@WebMobi59
Copy link

Thanks, @Siddharth-Dev
Got it

@samkerm
Copy link

samkerm commented Jan 26, 2017

Hey guys,

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

@kroikie
Copy link
Contributor

kroikie commented Jan 29, 2017

@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.

@christianraj
Copy link

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

@jogilsang
Copy link

jogilsang commented Feb 23, 2017 via email

@achavhan
Copy link

achavhan commented Mar 9, 2017

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?

@2ndGAB
Copy link

2ndGAB commented Mar 9, 2017

@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.

@achavhan
Copy link

@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.

@christianraj
Copy link

christianraj commented Mar 13, 2017 via email

@tushar2812
Copy link

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.

@christianraj
Copy link

christianraj commented Mar 22, 2017 via email

@akshayejh
Copy link

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

@kkyyppp
Copy link

kkyyppp commented Feb 21, 2018

how about my solution
https://stackoverflow.com/questions/48897883

@himalayaahuja
Copy link

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.?

@gauravdhim1990
Copy link

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

@KORuL
Copy link

KORuL commented Mar 2, 2019

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

@baderkhane
Copy link

    // 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);
        }
    }

@babinchicken
Copy link

babinchicken commented Dec 15, 2019

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 .

@sameer8171
Copy link

I'm get message in both param data and notification , When my app in background onMessageReceived not triggered
so how to resolve this issue ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests