As part of my learning of Google's Firebase and Android (Kotlin), I have come up with a simple app idea that I wanted to pursue and actually publish on Google store.
The idea is that you create a group, join people, and send short pre-defined messages as push notifications to everyone in the group. Kind-of like a pager or chat app.
- Creating users and groups is done using Firebase Cloud Firestore --> that part works perfectly fine
- For the notification part, within the group, I insert a notification object under the Group collection and have a database listener on my app side that creates the notification, simple implemention like this:
val docRef = DatabaseController.db.collection(NaggerGlobalNotifications.TABLE_NAME)
docRef.addSnapshotListener { snapshot, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
for (dc in snapshot!!.documentChanges) {
when (dc.type) {
DocumentChange.Type.ADDED -> {
val newNotification = dc.document.toObject<MyNotification>()
NotificationsController.createNotification(
this,
newNotification.title,
newNotification.message
)
}
}
}
}
The "NotificationsController.createNotification" creates the notification using standard NotificationCompat.Builder which works perfectly fine.
Now comes the part with which I am struggling
My initial plan was to have a Service that has this listener running in the background. As soon as some notification is added to my Firebase Cloud Firestore node, the listener catches it and makes the notification on the group members' phones.
This works perfectly fine when the app is alive. When the app is killed, the notifications cease to work.
I tried a solution described here: https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android but I ended up here: Listen to firebase database changes when app is closed . In general, the proposed fix worked except...
It seems it is not possible to listen for Firebase database changes in the background
I could implement this is as a kind of a timer task, to call Firebase DB every 30 seconds or use the FCM messages instead of the database, but that begs the question:
- In case of timer call - if I would have a million users and every 30 seconds there would be a million calls to firebase for updates, would I have to be a millionaire to buy that kind of bandwidth with Google Firebase?
- In case of FCM - triggering FCM messages is possible only using Firebase console or with the need of a setting up a dedicated server (I think?) --> nice for big companies, but not for a single developer like me :(
In general, what I seek here is a bit of a guidance.
The app is kind of like a chat app with predefined short messages (like 100 characters max) and I guess I am trying to implement this with the least possible hardware expenses. Perhaps I'm being foolish here to believe this is possible without huge servers.
Thank you for any tips!
Keran