Open app on firebase notification received (FCM)

stevyhacker picture stevyhacker · May 31, 2016 · Viewed 61.2k times · Source

I want to open application automatically when notification is received, is this possible with Firebase and new FCM notifications?

I know I can set click_action but that's only for customizing which activity will start on notification click, I need something that will start automatically when notification is received.

I tried the quick start messaging firebase sample and there is a onMessageReceived() method but it only works if the app is in foreground. Is there something that will execute while app is in background as well? GCM could do something like what I want here by directly starting activity intent from broadcast receiver which is called when notification is received.

Answer

Diego Giorgini picture Diego Giorgini · Jun 4, 2016

Quick answer:

To automatically open an application via FCM you need to use a data-message, which guarantees to always invoke the FirebaseMessagingService.onMessageReceived() method.

Then you can add your logic in the .onMessageReceived() method to start the preferred activity.

WARNING: launching a UI without any user interaction is a very very bad practice for most of the applications! Please read the MarkG answer here: How to start an Activity from a Service?

[...] Interrupting what the user is currently doing is considered bad design form, especially from something that is supposed to be operating in the background.
Therefore, you should consider using a Notification [...] to launch the desired Activity when the user decides it is time to investigate. [...]

Full explaination:

FCM works similarly to GCM and can receive two types of messages:

  1. display-messages:
    payload {"notification" : { "body" : "hello world"}}
    These messages are automatically displayed when the app is in background and they call FirebaseMessagingService.onMessageReceived() if the app is already in foreground.

  2. data-messages:
    payload {"data" : { "key1" : "value1"}}
    These messages always invoke FirebaseMessagingService.onMessageReceived(),
    even if the app is closed or in background.

click_action is a parameter of the notification payload, thus it applies to the display-messages.

Indicates the action associated with a user click on the notification.
If this is set an activity with a matching intent filter is launched when user clicks the notification.

https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support