首页 > 解决方案 > 我需要做什么才能在 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
}

标签: androidkotlinschedulerjobsandroid-alarms

解决方案


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

工作经理

你称之为:

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

您可以设置延迟链接:

.setInitialDelay(持续时间,时间单位)


推荐阅读