How to create firebase background service in Android?

后端 未结 1 1210
清酒与你
清酒与你 2021-01-28 02:06

I\'m newbie to Android. I\'d like to create background service in android that listen for new Document created in Firestore. I\'ve all code ready but stuck with service starting

相关标签:
1条回答
  • 2021-01-28 03:04

    I'd like to create background service in android that listen for new Document created in Firestore.

    It's true that you can do that in an Android Service but please rememeber that a service represents only a way in which you can tell the OS that you have some background work that has to be done and that doesn't really requiere an attached view (activity).

    According to the official documentatation regarding Android services, if you want to benefit from a running service as much as possible:

    A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.

    So with other words, you'll need to provide an icon for the notification, so the user is informed that the app is consuming resources.

    According to your comment:

    Nope I want to listen for new documents created in Firestore.

    Yes, you can have a listener attached to some document in your database or even to a query, and it will update as the results change. But remeber that you will have to pay a read operation for each of the updates that you get, basically meaning that the user will also have the cost for the bandwidth, and the cost of their battery drain. So I always recommend remove the listeners according to the life-cycler of the activity.

    That's a way in which you you deal with Firestore when you want to listen to some documents in a background but please also consider using Cloud Functions for Firebase:

    Cloud Functions for Firebase let you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. There's no need to manage and scale your own servers.

    Edit:

    How do Cloud Functions actually work?

    As in the case of the client, Cloud Functions also allows you to attach a listener to a single document or even to a query. So a Cloud Function can be triggered when something special in your database happens, for instance when some documents gets written into a Firestore collection. Once the function is triggered, you can take some action. As Frank van Puffelen mentioned in his comment, you can send a notification for example. For Android, please see below a straightforward example:

    • Push notifications on content change

    Maybe this is not what you want, to send a notification but it's a simple example and I think you'll be able to get the idea.

    0 讨论(0)
提交回复
热议问题