11

Does the FirebaseMessagingService run in the background similar to how an IntentService operates?

I see that FirebaseMessagingService extents Service which does not run in the background, but I'd like to be sure whether or not I should be doing any work inside the FirebaseMessagingService asynchronously or synchronously.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Sakiboy
  • 7,252
  • 7
  • 52
  • 69

2 Answers2

18

FirebaseMessagingService's method onMessageReceived(RemoteMessage message) is called "in the background" (not on the UI/Main thread). If you try do asynchronous work inside onMessageReceived(RemoteMessage message) you will receive an error saying:

Method execute must be called from the main thread, currently inferred thread is worker.

So all work that is done within onMessageReceived(RemoteMessage message) should be done synchronously because it's in its own background worker thread.

Sakiboy
  • 7,252
  • 7
  • 52
  • 69
  • 6
    There's a side note though: _For all messages where onMessageReceived is provided, your service should handle any message within 10 seconds of receipt. If your app needs more time to process a message, use the Firebase Job Dispatcher._ – Alécio Carvalho Jul 17 '18 at 09:13
  • @AlécioCarvalho - Definitely, especially with the background restrictions that are in place on the newer versions of Android. – Sakiboy Aug 22 '18 at 17:22
3

A Service does not "run in the background". A Service is just an instance of a class (ie: an object). The methods of a Service can run on either the main (UI) thread or on a background (worker) thread. It all depends on how they are called.

The lifecycle methods of the service onCreate(), onStartCommand(), onDestroy() are all called on the main (UI) thread. But in your Service you can start other threads and do other things on those threads.

Dharman
  • 30,962
  • 25
  • 85
  • 135
David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Yes that's very true about an android `Service`, but I don't think that's the case when it comes to a `FirebaseMessagingService`. See my answer for more details. – Sakiboy Dec 09 '16 at 20:03