1、导入包:
implementation "androidx.work:work-runtime:2.7.1"
2、定义Worker:
class LogWork(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
override fun doWork(): Result {
//任务的具体行为
Log.i("caowj", "Work doWork...${TimeUtils.getNowString()}")
return Result.success();
}
}
3、执行Worker:
fun startLogWork(compatActivity: AppCompatActivity) {
Log.d("caowj","startLogWork...")
//定义触发条件
val constraints: Constraints = Constraints.Builder() //NetworkType.NOT REQUIRED: 对网络没有要求
//NetworkType.CONNECTED: 网络连接的时候执行
//NetworkType.UNMETERED:环计费的网络比如WIFI下执行
//NetworkType.NOT ROAMING:非漫游网络状态执行
//NetworkType.METERED: 计费网络比如3G,4G下执行
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
.build()
// // 单次任务
// val logRequest = OneTimeWorkRequest.Builder(LogWork::class.java)
// .setConstraints(constraints) //设置触发条件
// .setInitialDelay(5, TimeUnit.SECONDS) //设置延迟执行
// .addTag("logRequest") //设置tag标签
.setBackoffCriteria(BackoffPolicy.LINEAR, java.time.Duration.ofSeconds(12)) //设置退避策略
// .build()
// 周期性任务(注意:可以定义的间隔时间最短不得少于15分钟。)
val logRequest = PeriodicWorkRequest.Builder(LogWork::class.java, 15, TimeUnit.MINUTES)
.setConstraints(constraints) //设置触发条件
.setInitialDelay(5, TimeUnit.SECONDS) //设置延迟执行
.addTag("logRequest") //设置tag标签
// .setBackoffCriteria(BackoffPolicy.LINEAR, java.time.Duration.ofSeconds(12)) //设置退避策略
.build()
//将任务请求加入队列
val workManager = WorkManager.getInstance(compatActivity)
workManager.enqueue(logRequest)
workManager.getWorkInfoByIdLiveData(logRequest.id).observe(compatActivity, Observer {
Log.d("caowj", "work监听:$it")
})
}
注意:周期性任务(PeriodicWorkRequest)可以定义的间隔时间最短不得少于15分钟。
4、参考:
https://blog.csdn.net/fjnu_se/article/details/128179736