Workmanager是jetpack系列及其重要的一部分,他可以让用户设定定时任务,并设定一些条件,条件符合并到达时间后会自动执行,他的兼容性极高,在API23以上,它采用JobScheduler,以下采用AlarmManage和广播接受者。Workmanager他不是神,他也有延迟,他是系统提供出来的,很多app都能共享,所以同一时间的任务多,那么就会造成排队等候,就有了延迟。所以Workmanager适用于不急着使用的后台定时任务,如果像要下载文件等及时更新的,那么就还是service适合。
使用
设置Worker:
public class MyWork extends Worker {
public MyWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
SystemClock.sleep(2000);
Log.d("yanjin","doWork了!!!!");
return Result.success();
}
}
然后开始调用
WorkManager workManager = WorkManager.getInstance(WorkerManagerActivity.this);
workManager.enqueue(workRequest);
那么就需要一个workRequest,这里我们设置一个一次性任务
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWork.class)
.setConstraints(constraints)
.build();
至此我们可以调用了,但是如果我们要加限制,那么就要额外添加如下代码:
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)//设置网络情况
.setRequiresBatteryNotLow(true)//设置在电量不足的情况下不执行
.setRequiresCharging(true)//在充电时执行
.setRequiresStorageNotLow(true)//设置在容量不足的情况下不执行
// .setRequiresDeviceIdle(true)//在待机情况下执行,需要判断api大于23
.build();
全部代码如下:
public class WorkerManagerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_worker_manager);
findViewById(R.id.tv_one_time).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
oneTime();
}
});
}
/**
* 一次性任务
*/
private void oneTime() {
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)//设置网络情况
.setRequiresBatteryNotLow(true)//设置在电量不足的情况下不执行
.setRequiresCharging(true)//在充电时执行
.setRequiresStorageNotLow(true)//设置在容量不足的情况下不执行
// .setRequiresDeviceIdle(true)//在待机情况下执行,需要判断api大于23
.build();
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWork.class)
.setConstraints(constraints)
.setInitialDelay(1000, TimeUnit.MILLISECONDS)//延时一秒
.build();
WorkManager workManager = WorkManager.getInstance(WorkerManagerActivity.this);
workManager.enqueue(workRequest);
}
}
退避策略
如果我们doWork里面返回的是Result.retry();那么我们很可能需要重试,比如我们上一次的任务因为没有网络导致没有执行,那么我们就要重试,并且我们还需要设置重试的时间间隔怎么办?那么就用到这个退避策略了。如下:
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWork.class)
.setConstraints(constraints)
.setInitialDelay(1000, TimeUnit.MILLISECONDS)//延时一秒
.setBackoffCriteria(BackoffPolicy.LINEAR, Duration.ofSeconds(2))//线性增长,如果失败首先隔两秒再次请求,如果再次失败就是4秒
.build();
BackoffPolicy还有EXPONENTIAL,指数型增长,可以自由试试。
获取任务状态以及取消任务
workManager.getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer() {
@Override
public void onChanged(WorkInfo workInfo) {
Log.d("yanjin","workInfo state = "+workInfo.getState());
}
});
通过监听id就能获取到任务的状态,并且也可以取消任务。
workManager.cancelWorkById(workInfo.getId());
数据的传递
workRequest中可以添加data数据源
Data data = new Data.Builder()
.putString(KEY,"input")
.build();
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWork.class)
.setConstraints(constraints)
.setInitialDelay(1000, TimeUnit.MILLISECONDS)//延时一秒
.setBackoffCriteria(BackoffPolicy.LINEAR, Duration.ofSeconds(2))//线性增长,如果失败首先隔两秒再次请求,如果再次失败就是4秒
.addTag(TAG)
.setInputData(data)
.build();
在doWork中获取
@NonNull
@Override
public Result doWork() {
Data inputData = getInputData();
String name = inputData.getString(WorkerManagerActivity.KEY);
Log.d("yanjin","输出的数据 = "+name);
SystemClock.sleep(2000);
Data data = new Data.Builder()
.putString(WorkerManagerActivity.KEY,"input")
.build();
return Result.success(data);
}
当然我们看到Result.success(data),同样我们也可以把处理的结果返回。在监听任务状态中获取
workManager.getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer() {
@Override
public void onChanged(WorkInfo workInfo) {
if(workInfo != null && workInfo.getState() == WorkInfo.State.SUCCEEDED){
Data data = workInfo.getOutputData();
String name = data.getString(KEY);
Log.d("yanjin","传出的数据 = "+name);
}
}
});
这样,一个轮回就完成了。
周期性任务
PeriodicWorkRequest是设置周期性执行任务的对象,大部分设置和OneTimeWorkRequest一样但是注意,他的最小周期是15分钟!!!
任务链以及任务组合
OneTimeWorkRequest workRequest1 = new OneTimeWorkRequest.Builder(MyWork.class)
.build();
OneTimeWorkRequest workRequest2 = new OneTimeWorkRequest.Builder(MyWork.class)
.build();
final WorkManager workManager = WorkManager.getInstance(WorkerManager2Activity.this);
workManager.beginWith(workRequest1).then(workRequest2).enqueue();
这是简单的任务链,先执行1再执行2。那么如果我们想要如下需求呢?
OneTimeWorkRequest workRequestA = new OneTimeWorkRequest.Builder(MyWork.class)
.build();
OneTimeWorkRequest workRequestB = new OneTimeWorkRequest.Builder(MyWork.class)
.build();
OneTimeWorkRequest workRequestC = new OneTimeWorkRequest.Builder(MyWork.class)
.build();
OneTimeWorkRequest workRequestD = new OneTimeWorkRequest.Builder(MyWork.class)
.build();
OneTimeWorkRequest workRequestE = new OneTimeWorkRequest.Builder(MyWork.class)
.build();
WorkContinuation ABContinuation = WorkManager.getInstance(WorkerManager2Activity.this).beginWith(workRequestA).then(workRequestB);
WorkContinuation CDContinuation = WorkManager.getInstance(WorkerManager2Activity.this).beginWith(workRequestC).then(workRequestD);
//这里需要变成集合
List continuations = new ArrayList<>();
continuations.add(ABContinuation);
continuations.add(CDContinuation);
WorkContinuation.combine(continuations).then(workRequestE).enqueue();