0

I am developing an app with a Firebase database. I need to listen new entry at anytime, even if app is closed. As soon as a new entry in the database is made a function is launch.

Here is my code :

var base = FirebaseDatabase.getInstance()
    var maBase = base.getReference("COMMANDE") 
    
fun ecouterCommande(context: Context) {
            // Read from the database
            maBase.addValueEventListener(object: ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot) {
                    var message = snapshot.value
                    if (message.toString() == "info"){
                        function1(context)
                    } else if (message.toString() == "contact")
                    {
                        function2(context)
                    } else if (message.toString() == "sms")
                    {
                        function3(context)
                    }
                }
    
                override fun onCancelled(error: DatabaseError) {
                    Toast.makeText(context, "ERREUR", Toast.LENGTH_SHORT).show()
                }
            })
        }

The code works, depending of the entry on my database (info, contact or sms) the corresponding function is launched.

But when that it still working even if the app is closed. Could you give me a bit of help please ? How can I do that ?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Nounet
  • 63
  • 1
  • 6

1 Answers1

1

You'll need to write a Firebase cloud function that listens to events in the db and triggers on a change at the specified path.

Cloud functions work independent of your app and fires on database events, regardless of whether your app is open or closed.

See Firebase docs here https://firebase.google.com/docs/functions/database-events

Mica Smith
  • 71
  • 1
  • 4