WorkManager的基本用法
添加依赖:
def work_version = "2.5.0"
implementation "androidx.work:work-runtime:$work_version"
定义一个后台任务:
package com.example.workmanagerdemo
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
class SimpleWorker(context: Context,params:WorkerParameters) : Worker(context,params) {
override fun doWork(): Result {
//在这里编写后台任务的具体逻辑
println("SimpleWorker后台任务")
//返回执行结果
// Result.success() 成功
// Result.failure() 失败
// Result.retry() 失败重试
return Result.success()
}
}
运行后台任务:
package com.example.workmanagerdemo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkInfo
import androidx.work.WorkManager
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
//只执行一次
val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
.setInitialDelay(5,TimeUnit.SECONDS) //延迟5秒执行
.addTag("simple") //添加标签
.build()
//重复执行,间隔不能短于15分钟
//val request = PeriodicWorkRequest.Builder(SimpleWorker::class.java, 15,TimeUnit.MINUTES).build()
//开始执行
WorkManager.getInstance(this).enqueue(request)
//监听后台任务运行结果
WorkManager.getInstance(this)
.getWorkInfoByIdLiveData(request.id)
.observe(this){
if (it.state == WorkInfo.State.SUCCEEDED) {
//执行成功
println("运行成功")
}else if(it.state == WorkInfo.State.FAILED){
//执行失败
println("运行失败")
}
}
}
//取消后台任务请求
cancelButton.setOnClickListener {
//取消该标签下的所有后台任务请求,也可以通过id取消单个任务请求
WorkManager.getInstance(this).cancelAllWorkByTag("simple")
}
}
}