android - 我需要做什么才能在 Kotlin 中完成“在下月初触发一次工作/警报以调用 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(持续时间,时间单位)
推荐阅读
- python - Tweepy 转推机器人不断循环
- java - 如何解决会话超时问题?
- php - 如何使用同一服务器访问不同codeigniter项目中的同一会话?
- r - 在带有 purrr 的大型列表列表中对不同位置和不同名称的列进行子集
- django - Django 外键 query_set 通过 Views.py 更新
- jquery - 第二个 DropdownList 将不会被填充
- php - 如何将 href 带入变量并将其提供给 href="$vrable so"
- python - 是否有一种既定的方法可以将用图形/会话编写的 Tensorflow 网络架构转换为 Keras API 以供 TPU 使用?
- python - 带有图例标签的单行上的 matplotlib 图例标题
- ios - 向下滚动并从 UITableViewController 返回时,导航栏标题变小