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.
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. [...]
FCM works similarly to GCM and can receive two types of messages:
{"notification" : { "body" : "hello world"}}
FirebaseMessagingService.onMessageReceived()
if the app is already in foreground.
{"data" : { "key1" : "value1"}}
FirebaseMessagingService.onMessageReceived()
,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