Android

Android JetPack学习总结(十九)

WorkManager

使用WorkManager API 可以轻松地调度即使在应用退出或设备重启时仍应运行的可延迟异步任务

用统一的方法解决绝大部分后台问题

工作流程

image

添加依赖:

dependencies {
    def versions = "2.2.0"
    implementation "androidx.work:work-runtime:$versions"
}

创建一个继承Worker的worker类,补全方法并做一些简单的操作:

public class MyWork extends Worker {
public MyWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Result.success();
}
}

在activity中获取workManager的引用:

private WorkManager manager=WorkManager.getInstance(this);

创建工作请求,并放入请求队列中:

WorkRequest workRequest= OneTimeWorkRequest.from(MyWork.class);
manager.enqueue(workRequest);

可以设置工作条件,例如在有计费式网络下开启:

Constraints constraints=new Constraints.Builder()
.setRequiredNetworkType(NetworkType.METERED)
.build();
WorkRequest workRequest= new OneTimeWorkRequest
.Builder(MyWork.class)
.setConstraints(constraints)
.build();
manager.enqueue(workRequest);

不知道为什么,NetworkType设置为CONNECT不管用。

通过work请求传入数据

WorkRequest workRequest= new OneTimeWorkRequest
.Builder(MyWork.class)
.setConstraints(constraints)
.setInputData(new Data.Builder().putString(INPUT_DATA_KEY,WORK_A_NAME).build())
.build();

获取传入的数据

public Result doWork() {
    String name=getInputData().getString(INPUT_DATA_KEY);
}

返回输出数据

@NonNull
@Override
public Result doWork() {
    String name=getInputData().getString(INPUT_DATA_KEY);
    return Result.success(new Data.Builder().putString(OUTPUT_DATA_KEY,name+" output").build());
}

在activity中通过observer获取数据

manager.getWorkInfoByIdLiveData(workRequest.getId()).observe(MainActivity.this, new Observer<WorkInfo>() {
@Override
public void onChanged(WorkInfo workInfo) {
Log.i("hello","on create: "+workInfo.getState());
if (workInfo.getState()== WorkInfo.State.SUCCEEDED){
Log.i("hello","on create: "+workInfo.getOutputData().getString(OUTPUT_DATA_KEY));
}
}
});

串行执行任务,和animation一样的写法

OneTimeWorkRequest workRequestA = getWorkRequest(WORK_A_NAME);
OneTimeWorkRequest workRequestB = getWorkRequest(WORK_B_NAME);
manager.beginWith(workRequestA)
.then(workRequestB).enqueue();

发表评论