Search code examples
androidfirebasefirebase-realtime-databaseandroid-alarms

How do I reset Firebase Realtime Database values offline?


In my Firebase Realtime Database, I want to reset a specific value at 11:59 PM every day.

This is the code that I have in my MainActivity:

val dailyCal: Calendar = Calendar.getInstance()
dailyCal[Calendar.HOUR_OF_DAY] = 23
dailyCal[Calendar.MINUTE] = 59
dailyCal[Calendar.SECOND] = 59
dailyCal[Calendar.MILLISECOND] = 0
val dailyIntent: PendingIntent = PendingIntent.getBroadcast(
    this@MainActivity,
    0,
    Intent(this, DailyBroadcastReceiver::class.java),
    PendingIntent.FLAG_UPDATE_CURRENT
)
val dailyAm: AlarmManager = this.getSystemService(ALARM_SERVICE) as AlarmManager
dailyAm.setInexactRepeating(
    AlarmManager.RTC,
    dailyCal.timeInMillis,
    AlarmManager.INTERVAL_DAY,
    dailyIntent
)

This is what I have in my onReceive function in my DailyBroadcastReceiver to reset the value:

if (intent.action != Intent.ACTION_BOOT_COMPLETED) {
    val userInfo = database.getReference("users").child(auth.currentUser!!.uid).child("daily")
    userInfo.setValue(0)
}

So far this works if the user is on the app or if the user's phone is on and they are still connected to the internet despite not being on the app itself.

How do I make my app reset a specific value in my Firebase Realtime Database if the user isn't connected to the internet or even if their device is not turned on?


Solution

  • It's not possible to reliably use a user's mobile device to schedule work, for the reason you mentioned. In fact, the device could be off, or it could have no internet connection, or the user could even be using multiple device, each conflicting with each other for this nightly work.

    You should instead do the work on a backend you control. It's relatively easy to schedule and execute some code on a periodic basis using scheduled functions, so you should consider using that instead.

    See also: