Home > other >  How can I handle a notification from Firebase when it arrives and I have the app open?
How can I handle a notification from Firebase when it arrives and I have the app open?

Time:09-28

I want to update activities when a notification arrives but I can't get the current Activity where the user is. I'm working with FirebaseMessagingService.

Code

CodePudding user response:

You have to consider that when receiving the notification the application may be in the foreground or background and that depending on it the handling is different.

You cannot get the activity from that service, instead, you have to tell it which activity appears in the foreground when the notification is clicked and get the "extras" data.

For example using a configuration like this in the notification server (nodejs):

var message = {
        notification: {
            title: title,
            body: text
        },
        data: {
            title: title,
            body: text,
            latitude: latitude,
            longitude: longitude,
            name: name
        },
        android: {
            priority: 'high',
            notification: {
                sound: 'default',
                clickAction: '.PetNotificationActivity'
            },
        },
        apns: {
            payload: {
                aps: {
                    sound: 'default'
                },
            },
        },
        tokens: registrationTokens
    };

In that example, PetNotificationActivity is the activity that I want to bring to the foreground when opening the notification.

And, In the PetNotificationActivity something like this:

public class PetNotificationActivity extends AppCompatActivity {

    ....

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pet_notification);
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            String latitudeValue = bundle.getString("latitude");
            String longitudeValue = bundle.getString("longitude");
            String nameValue = bundle.getString("name");
            ...
        }
    }

FCM documentation at Handling messages

CodePudding user response:

A better approach would be for your interested activities to register a broadcast receiver and for your service to send a broadcast when a message arrives.

  • Related