2

I am writing Kotlin Android App with Firebase Realtime Database, and I want to update GPS data in specific period(10sec), not in real time. I tried both Timer() and Handler(), but the update time was not accurate, sometimes less than 10sec.

I read this but it doesn't help.

val myTimer = Timer()
        val task = object : TimerTask() {
            override fun run() {
                val database = FirebaseDatabase.getInstance()
                val gps = GPS(latFirebase, longFirebase)
                val mAuth = FirebaseAuth.getInstance()
                val currentUser = mAuth!!.currentUser
                val userID = currentUser!!.uid
                val ref = database.getReference("gps_data/$userID")
                ref.setValue(gps)
            }
        }
        myTimer.schedule(task, 100, 10000)
KENdi
  • 7,576
  • 2
  • 16
  • 31
kenchan13
  • 121
  • 1
  • 5

1 Answers1

2

Unfortunately, there is no auto-increment-every-ten-seconds operation built into the Firebase realtime database. If you need that functionality, you will have to either do that from the client-side apps, using a Handler like this:

val handler = Handler()
val timer = Timer()
val doAsynchronousTask = object : TimerTask() {
    override fun run() {
        handler.post {
            try {
                //Your function call
            } catch (e: Exception) {
                // TODO Auto-generated catch block
            }
        }
    }
}
timer.schedule(doAsynchronousTask, 0, 10000)

Or do it from a server-side environment such as Cloud Functions. Since Cloud Functions only run in response to triggers and don't have a built-in trigger for time yet, you can use a service like cron-job.org to emulate that. For that, please see Frank van Puffelen's answer from this post.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • yes, I do but it doesn't work and it keeps update in not stable time. I don't consider to use firebase cloud functions as the data structure has been constructed. my plan is to do it on client-side. – kenchan13 Oct 16 '18 at 11:56
  • there is one problem which related to GPS. When I test the GPS indoor, realtime database updates frequently. do you think it is related to Android GPS library? thanks – kenchan13 Oct 16 '18 at 13:04
  • In this case, just use it client side. And yes, it might be related. Do you think that my answer helped you? – Alex Mamo Oct 17 '18 at 03:15
  • Thanks a lot. I used Handler() and input a bigger delay constant(100,000). Although not stable(it update the GPS data to firebase between interval 30 seconds to 90 seconds), better than the previous version(update almost every second). – kenchan13 Oct 23 '18 at 16:50