https://developer.android.google.cn/topic/libraries/architecture/workmanager
https://developer.android.google.cn/topic/libraries/architecture/workmanager/basics
示例:https://github.com/android/architecture-components-samples/tree/main/WorkManagerSample
1. Application 需要
implements Configuration.Provider
重写
@NonNull
@Override
public Configuration getWorkManagerConfiguration() {
return new Configuration.Builder().setMinimumLoggingLevel(Log.VERBOSE).build();
}
2.创建WorkRequest
// val uploadWorkRequest = OneTimeWorkRequest.from(UploadWorker::class.java);//两种方法都可以
val uploadWorkRequest: WorkRequest = OneTimeWorkRequestBuilder<UploadWorker>() .build()
// Submit the WorkRequest to the system
WorkManager .getInstance(applicationContext) .enqueue(uploadWorkRequest)
3.创建 UploadWorker
import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
class UploadWorker(appContext: Context, workerParams: WorkerParameters) :
Worker(appContext, workerParams) {
override fun doWork(): Result {
// Do the work here--in this case, upload the images.
// uploadImages()
println("UploadWorker doWork" + Thread.currentThread().name)
// Indicate whether the work finished successfully with the Result
return Result.success()
}
}
控制台输出
2021-02-23 13:39:01.327 14973-15082/ I/System.out: UploadWorker doWorkpool-1-thread-1