JetPack之WorkManager

依赖:

def work_version = "2.5.0"

// (Java only)
implementation "androidx.work:work-runtime:$work_version"

创建一个任务。需要继承Worker类:

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

    @NonNull
    @Override
    public Result doWork() {
        Log.i("shopkeeperTag", "doWork:");
        return Result.success();
    }
}

创建一个任务请求,任务请求有一次性的和多次的。以一次性为例,通过工厂方法,传入任务类:

        OneTimeWorkRequest request1=new OneTimeWorkRequest.Builder(MyWork.class)
                .build();

将任务请求交给WorkManager安排执行:

        WorkManager manager=WorkManager.getInstance(this);
        manager.enqueue(request1);

可以为一个任务请求设置限制、延时等其它选项:

        OneTimeWorkRequest request1=new OneTimeWorkRequest.Builder(MyWork.class)
//                设置触发条件
                .setConstraints(constraints)
//                设置延迟执行
                .setInitialDelay(5, TimeUnit.SECONDS)
//                退避策略,当worker返回retry时自动执行推迟策略
                .setBackoffCriteria(BackoffPolicy.LINEAR, Duration.ofSeconds(2))
//                设置Tag标签
                .addTag("workRequest1")
                .build();

触发条件:

//        设置触发条件
        Constraints constraints=new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
//                .setRequiresBatteryNotLow() //电量充足
//                .setRequiresCharging() //充电时
//                .setRequiresDeviceIdle() //设备空闲时
//                .setRequiresStorageNotLow() //内存充足
//  NOT_REQUIRED, A network is not required for this work.
//  CONNECTED, Any working network connection is required for this work.
//  UNMETERED, An unmetered network connection is required for this work.
//  NOT_ROAMING, A non-roaming network connection is required for this work.
                .build();

观察任务状态:

//        观察任务状态
        manager.getWorkInfoByIdLiveData(request1.getId()).observe(this, new Observer<WorkInfo>() {
            @Override
            public void onChanged(WorkInfo workInfo) {
                Log.i("shopkeeperTag", "WorkInfo onChanged: "+workInfo.getState());
            }
        });

取消任务:

//        取消任务
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                manager.cancelWorkById(request1.getId());
            }
        },2000);

传递参数:

向worker传递参数:

        Data inputData=new Data.Builder()
                .putString(inputDataTag,"sk")
                .build();


        OneTimeWorkRequest request1=new OneTimeWorkRequest.Builder(MyWork.class)
                .setInputData(inputData)
                .build();

worker中接收参数,并返回结果参数:

    public Result doWork() {
        String stringData=getInputData().getString(inputDataTag);
        Log.i("shopkeeperTag", "doWork: get input data: "+stringData);

        Data outputData=new Data.Builder()
                .putString(outputDataTag,"执行成功")
                .build();
        return Result.success(outputData);
    }

在监听任务状态时接收worker的结果参数:

manager.getWorkInfoByIdLiveData(request1.getId()).observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(WorkInfo workInfo) {
Log.i("shopkeeperTag", "WorkInfo onChanged: state = "+workInfo.getState()+", data = "+workInfo.getOutputData().getString(outputDataTag));
}
});

周期任务的创建:

//        周期任务
//        周期不能小于15分钟
        PeriodicWorkRequest request2=new PeriodicWorkRequest.Builder(MyWork.class,Duration.ofMinutes(15)).build();

任务链的简单使用:

public void addWork(View view){
OneTimeWorkRequest workA=new OneTimeWorkRequest
.Builder(AWorker.class)
.build();
OneTimeWorkRequest workB=new OneTimeWorkRequest
.Builder(BWorker.class)
.build();
WorkManager.getInstance(this)
.beginWith(workA)
.then(workB)
.enqueue();
}

任务组合:

public void addWork(View view){
OneTimeWorkRequest workA=new OneTimeWorkRequest
.Builder(AWorker.class)
.build();
OneTimeWorkRequest workB=new OneTimeWorkRequest
.Builder(BWorker.class)
.build();
OneTimeWorkRequest workC=new OneTimeWorkRequest
.Builder(CWorker.class)
.build();
OneTimeWorkRequest workD=new OneTimeWorkRequest
.Builder(DWorker.class)
.build();
OneTimeWorkRequest workE=new OneTimeWorkRequest
.Builder(EWorker.class)
.build();
WorkContinuation continuation1=WorkManager.getInstance(this)
.beginWith(workA)
.then(workB);
WorkContinuation continuation2=WorkManager.getInstance(this)
.beginWith(workC)
.then(workD);
List<WorkContinuation> taskList=new ArrayList<>();
taskList.add(continuation1);
taskList.add(continuation2);
WorkContinuation.combine(taskList)
.then(workE)
.enqueue();
}

发表评论