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.
Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded apps to receive notification messages or data messages, you'll need to write code to handle the onMessageReceived callback.
if you are sending it from your firebase console it sends a notification message so those you will not get if your app is closed, you need to send messages that have the data payload which the console does not do.
FCM does not guarantee the order of delivery. Some typical use cases of non-collapsible messages are chat messages or critical messages.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With