我需要做什么才能在 Kotlin 中完成"fire a job/alarm once at the beginning of next month to call an API"?



我是 Kotlin 和 Android 的新手,当我尝试研究 Kotlin/Android 中的作业调度程序时,我对很多方法感到不知所措,但似乎都以自己的方式复杂。

我正在开发一个简单的应用程序,记录客户的反馈,主要是离线的。但它有一个在线功能,那就是在每个月初通过API的帮助向某些电子邮件地址发送报告。

我需要最简单的方法来实现这一点,它:

  • 无论应用程序处于活动状态还是已销毁,都可以执行 - 因此作为服务?
  • 不必精确(不准确的时间是可以的)。
  • 我只需要触发一次,因为当用户与应用程序交互时,应用程序将设置为下一次触发。 不需要重复。
  • 下月初开火。
  • 如果上一个作业尚未触发,但用户已经与应用进行了另一次交互,我可以将现有作业替换为新作业,因为报告汇总了整个月的活动。我读到具有"相同意图"的警报/作业可以相互替换,尽管我不确定在实施中实际是什么样子的。
  • 因为数据在数据库中,而且我认为当应用程序处于非活动状态时我可能无法访问数据库,所以我想我可以在每次设置作业/警报时将要发送的数据放在用户共享首选项中。我在后台服务可以从共享首选项中读取的某处读到。
  • 需要做网络调用。

因此,例如,如果要发送的所需数据已经在共享首选项中,那么实现此目的的最简单/最基本的方法是什么?

fun userDoInteractionWithApp (data: Data) {
this.process (data)
val report = this.generateThisMonthReport()
this.scheduleNextReport(report, Date())
}
fun scheduleNextReport(report: String, curDate: Date) {
this.saveToSharedPreferences ("report", report)
val c = Calendar.getInstance()
c.time = curDate
c.add(Calendar.MONTH, 1)
c.set(Calendar.DAY_OF_MONTH, 1)
c.set(Calendar.HOUR_OF_DAY, 10)
val targetDate = c.time
// and then?
}
fun sendReport() { // I want to fire this function, for example
val report = this.loadFromSharedPreferences ("report") as String
Network.sendReport(senderEmail, destinationEmail, "This is the report", report) // will run synchronously
}

如果您不必在确切的时间启动应用程序,最好的方法是使用

工作管理器

你称之为:

val uploadWorkRequest = OneTimeWorkRequestBuilder<YourWorker>()
.build()
WorkManager.getInstance().enqueue(uploadWorkRequest)

您可以设置延迟链接以下内容:

.setInitialDelay(duration, TimeUnit)

相关内容

最新更新