Android 新架构组件 -- WorkManager
Android WorkManager
compile "android.arch.work:work-runtime:1.0.0-alpha02"
继承Worker
类并实现doWork()
方法
public class MineWorker extends Worker {
@NonNull
@Override
public WorkerResult doWork() {
LogUtils.i("MineWorker--doWork");
return WorkerResult.SUCCESS;
}
}
想要该Worker
执行,需要调用WorkManager
将该Worker
添加到队列中
WorkManager workManager = WorkManager.getInstance();
OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(MineWorker.class).build();
workManager.enqueue(oneTimeWorkRequest);
结果输出:
MineWorker--doWork
在手机充电时,并且有网的情况下执行某个任务:
// 在手机充电时,并且有网的情况下执行某个任务
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(true)
.build();
OneTimeWorkRequest constraintsOneTimeWorkRequest1 = new OneTimeWorkRequest.Builder(MineWorker.class).setConstraints(constraints).build();
workManager.enqueue(constraintsOneTimeWorkRequest1);
顺序的去执行不同的OneTimeWorker
:
// OneTimeWorker顺序执行
OneTimeWorkRequest workA = new OneTimeWorkRequest.Builder(MineWorker.class).build();
OneTimeWorkRequest workB = new OneTimeWorkRequest.Builder(MineWorker.class).build();
OneTimeWorkRequest workC = new OneTimeWorkRequest.Builder(MineWorker.class).build();
OneTimeWorkRequest workD = new OneTimeWorkRequest.Builder(MineWorker.class).build();
OneTimeWorkRequest workE = new OneTimeWorkRequest.Builder(MineWorker.class).build();
WorkContinuation chain1 = WorkManager.getInstance()
.beginWith(workA)
.then(workB);
WorkContinuation chain2 = WorkManager.getInstance()
.beginWith(workC)
.then(workD);
WorkContinuation chain3 = WorkContinuation
.combine(chain1, chain2)
.then(workE);
chain3.enqueue();
定期的去执行某一个worker
:
// 定期执行
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(true)
.build();
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest
.Builder(MineWorker.class, 3, TimeUnit.SECONDS)
.setConstraints(constraints)
.build();
workManager.enqueue(periodicWorkRequest);