【JetPack】WorkManager笔记
WorkManager简介:
WorkManager 是 Android Jetpack 库中的一个重要组件。它用于处理那些需要在后台可靠执行的任务,这些任务可以是一次性的,也可以是周期性的,甚至是需要满足特定条件才执行的任务。例如,它可以用于在后台上传文件、下载更新、清理缓存等操作。
与传统的后台处理方式相比,WorkManager 具有很多优势。它可以根据设备的状态(如网络可用性、电量等)智能地调度任务,确保任务能够在合适的时机执行。即使应用程序进程被杀死,它依然能够保证任务的执行,这对于一些重要的后台任务来说是非常关键的。
// 创建Data
Data data = new Data.Builder()
.putString("inputData", "Jay")
.build();
// 创建触发条件 (触发条件满足,不会立刻执行)
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
.build();
// 创建一次性执行的任务
OneTimeWorkRequest workRequest1 = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
workRequest1 = new OneTimeWorkRequest.Builder(MyWork.class)
// 设置触发条件
.setConstraints(constraints)
// 设置延迟执行
.setInitialDelay(5, TimeUnit.SECONDS)
// 指数退避策略,如果返回结果是retry,那么按线性2s,重复执行,大概就是2,4,8
.setBackoffCriteria(BackoffPolicy.LINEAR, Duration.ofSeconds(2))
// 设置标签
.addTag("workRequest1")
// 参数传递
.setInputData(data)
.build();
}
// 任务提交给系统
WorkManager workManager = WorkManager.getInstance(this);
// 将任务加入workManager队列
workManager.enqueue(workRequest1);
// 观察任务状态
workManager.getWorkInfoByIdLiveData(workRequest1.getId()).observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(WorkInfo workInfo) {
Log.d("test", workInfo.toString());
if (workInfo != null) {
String outString = workInfo.getOutputData().getString("key");
Log.d("test", "outString = " + outString);
}
}
});
// 取消任务
OneTimeWorkRequest finalWorkRequest = workRequest1;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
workManager.cancelWorkById(finalWorkRequest.getId());
}
}, 2000);
// 创建周期性任务 (周期不可少于15min)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(MyWork.class, Duration.ofMinutes(15))
.build();
workManager.enqueue(periodicWorkRequest);
}
MyWork继承Worker类,在满足条件时执行Work
public class MyWork extends Worker {
public MyWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
// SystemClock.sleep(2000);
String inputData = getInputData().getString("inputData");
Log.d("test","MyWork doWork " + inputData);
// 将参数传递回去
Data data = new Data.Builder()
.putString("key", "执行成功")
.build();
return Result.success(data);
}
}
任务组合
public void addWork(View view) {
OneTimeWorkRequest workRequest1 = new OneTimeWorkRequest.Builder(AWorker.class)
.build();
OneTimeWorkRequest workRequest2 = new OneTimeWorkRequest.Builder(BWorker.class)
.build();
OneTimeWorkRequest workRequest3 = new OneTimeWorkRequest.Builder(CWorker.class)
.build();
OneTimeWorkRequest workRequest4 = new OneTimeWorkRequest.Builder(DWorker.class)
.build();
OneTimeWorkRequest workRequest5 = new OneTimeWorkRequest.Builder(EWorker.class)
.build();
// 任务组合
WorkContinuation workContinuation1 = WorkManager.getInstance(this)
.beginWith(workRequest3)
.then(workRequest4);
WorkContinuation workContinuation2 = WorkManager.getInstance(this)
.beginWith(workRequest1)
.then(workRequest2);
List<WorkContinuation> list = new ArrayList<>();
list.add(workContinuation1);
list.add(workContinuation2);
WorkContinuation.combine(list)
.then(workRequest5)
.enqueue();
}