3

I'm sending firebase-messages using the firebase-console. The messages shall contain additional data like shown below with the purpose to open a specific URL within a webview in my app:

enter image description here

I set up my manifest and firebase class to get the messages. Within my firebase class I try to get the data:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    if(remoteMessage.getData().containsKey("key1")) {
        intent.putExtra("destination", remoteMessage.getData().get("key1"));
    }
    PendingIntent pendingIntent = PendingIntent.getActivity
    (this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    String channelId = "default";
    NotificationCompat.Builder builder;
    if (remoteMessage.getNotification() != null ) {
        if (remoteMessage.getNotification().getTitle() != null) {
            builder = new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_stat_onesignal_default)
                    .setContentTitle(remoteMessage.getNotification().getTitle())
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent);
        } else {
            builder = new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_stat_onesignal_default)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent);
        }

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "default", NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
        }

        manager.notify(0, builder.build());
    }
}

Within my MainActivity class I try to get the data. When the app is in the foreground, the following works (no matter what activity is opened, it will jump to the MainActivity and execute the following):

@Override
protected void onNewIntent(Intent intent) {
    if (intent.getExtras() != null) {

        Bundle extras = intent.getExtras();

        if(extras.containsKey("destination")) {
            Log.e("FIREBASE_CONTAINS", (String) extras.get("destination"));
        }
    }
}

But the event wont trigger if the app started from the background. I tried to get the intent and check for the key within the onResume() event of the activity, but it does not work (Same in inCreate() and onStart()).

Can anybody help me?

------------EDIT-----------------

As described in one of the comments, the problem seems to be that Notification-Messages won't reach the onMessageReceived() event. Apparently the firebase console can't send data-notifications (which would reach the event) so I tried using POSTMAN. I've read that I have to leave the notification tag out of the message body and put all my information in the data section. But if I do so, the messages won't reach my app (they do, when I add the notification section again, but of course they are not reaching the onMessageReceived() event in that case).

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
tge
  • 69
  • 1
  • 10

4 Answers4

2

There are 3 types of push messages

  • notification
  • data
  • and both

A push messages is basically a json payload:

payload:{
    notificacion...
    data
}

Rules for each type of push messages are differente. In your case you are using the Firebase web console and adding custom data, which mean your payload will have notification and data.

For the combined type the behaviour in backgroun is to use a default notificacion (NotificationCompat, the visual kind) and open the default activity registered in the manifest. In the activity you can get the data.

Lets say your default activity is called MainActivity

public class MainActivity {

    onCreate...{
    //... usual stuff
    Intent fcmIntent = getIntent();
    if fcmIntent != null
    //check the extras and forward them to the next activity if needed
    }
}
cutiko
  • 9,887
  • 3
  • 45
  • 59
  • As I said within my question, I tried that. But it the intent does not carry the extras (I checked for the key the same way as I did in onNewIntend() ) – tge Jul 17 '19 at 13:55
1

There are two type of push message

(1)Notification Message (will receive when app is in foreground)

(2)Data Message (will receive when app is in background+foreground)

enter image description here

Reference : https://firebase.google.com/docs/cloud-messaging/android/receive

Hardik Bambhania
  • 1,732
  • 15
  • 25
  • According to this table, the data should be forwarded to the oNMessageRecieved function, even if the app is in the background, right? Or does it not effect the additional data from the firebase console? – tge Jul 17 '19 at 13:57
  • @tge : Yes, You are right. If you send data push then you will receive it in onMessageReceived() method as RemoteMessage obejct in foreground and background. – Hardik Bambhania Jul 17 '19 at 14:00
  • so why can't I access those data when I reopen the app? – tge Jul 17 '19 at 14:04
  • Notification message : { "message":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "notification":{ "title":"Portugal vs. Denmark", "body":"great match!" } } } Data message : { "message":{ "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "data":{ "Nick" : "Mario", "body" : "great match!", "Room" : "PortugalVSDenmark" } } } Reference : https://firebase.google.com/docs/cloud-messaging/concept-options – Hardik Bambhania Jul 17 '19 at 14:05
  • Firebase console not able to send data push, It always send notification push.To send data push, You need to use Postman (Rest API test tool)kind of tool. – Hardik Bambhania Jul 17 '19 at 14:07
  • But isn't that exactly what I do with if(remoteMessage.getData().containsKey("key1")) { intent.putExtra("destination", remoteMessage.getData().get("key1")); } ? – tge Jul 17 '19 at 14:10
  • Is your if condition is returning true ? – Hardik Bambhania Jul 17 '19 at 14:14
  • So the solution to my problem is using another way to send the messages? I will try this! – tge Jul 17 '19 at 14:14
  • @tge : Try to send push by other way using Rest API test tool. – Hardik Bambhania Jul 17 '19 at 14:16
  • Let me know if you fail. – Hardik Bambhania Jul 17 '19 at 14:42
  • I tried to use Postman but if I send messages including notification and data in their body it wont jump to onMessageReceived and if I only use data and drop the notification part the notification wont reach the app at all – tge Jul 21 '19 at 18:17
  • I guess to keep everything clear I assume your argumentation to be the solution to my problem. I'll open a different question, because it will be related on postman. – tge Jul 22 '19 at 10:02
  • @tge : As per above table if you send data and notification both in message body then onMessageReceived() will not call if your application is in background. – Hardik Bambhania Jul 22 '19 at 10:47
  • yes, the problem is solved. I need to cut out the notification part. It didn't work for me because I did only display the message if the notificationpart was not null. But I was able to test it and now it seems to work! So I will edit my code now. Thanks again for your help. – tge Jul 22 '19 at 10:54
0

You need to set click_action in firebase notification data set to be able to receive data from background and implement onMessageReceived to handle foreground data

See updated answer here: https://stackoverflow.com/a/73724040/7904082

Akinyemi Jamiu
  • 431
  • 3
  • 10
  • Adding click_action works to redirect to the activity, but it does not send data to the activity when app is in background. It does send data when the notification comes when the app is in foreground. – Robby Lebotha Feb 24 '23 at 06:14
  • 1
    @RobbyLebotha, you need to get your data in **onNewIntent** of the activity that has the intent filter for **click_action** as shown for background notification. And for foreground, you get your data in **onMessageReceived** of FirebaseMessagingService then show notification and set your data to the notification pending intent. – Akinyemi Jamiu Mar 01 '23 at 21:21
-1

I solved this buy handling the notification in handleIntent it fires when app is killed,in background and foreground. I completely ignore the onMessageReceived(@NonNull RemoteMessage message) method because it doesnt seem to work when app is in background.

@Override

    public void handleIntent(Intent intent) {
        Log.d( "FCM", "handleIntent \n"+intent.getStringExtra("data"));
        String messageTitle = intent.getStringExtra("title");
        String messageBody = intent.getStringExtra("body");
        //from here pass the values to a method to show your notification.
        
    }

In your activity you will then be able to retrieve any data from the intent.

To redirect to your desired activity, you must add click_action to your payload. Here is what my payload looks like:

"notification": {
  "body": "Your message is here",
  "title": "Hey Robby",
  "discount_code": "baba-blacksheep",
  "uid": "2",
  "click_action": "OPEN_ACTIVITY_FROM_NOTIFICATION"
}
Robby Lebotha
  • 1,211
  • 11
  • 9
  • This could only work [if you're using your own server to send the notification](https://stackoverflow.com/questions/37711082/how-to-handle-notification-when-app-in-background-in-firebase/73724040#73724040). OP asked for Firebase implementation, and this does not answer that question, plus you never explain that this will only work when you send it from your own server. – Jorn Rigter Mar 28 '23 at 15:32
  • handleIntent() will receive the notification whether app is in foreground or background or killed. Regardless if the message is coming from the firebase console or you own server. – Robby Lebotha Mar 29 '23 at 07:52
  • Untrue. I verified this with my own app, [Firebase says so themselves](https://firebase.google.com/docs/cloud-messaging/android/receive) and many people confirm this [in this thread](https://stackoverflow.com/questions/37711082/how-to-handle-notification-when-app-in-background-in-firebase) – Jorn Rigter Mar 29 '23 at 09:19