WorkManager是干啥的。
WorkManager is the recommended library for persistent work. Scheduled work is guaranteed to execute sometime after its [Constraints](https://developer.android.google.cn/reference/androidx/work/Constraints)
are met. WorkManager allows observation of work status and the ability to create complex chains of work.
从上面可以知道:workmanager是一个google 推荐的library 用来执行work的,他有一些特点
- persistent 稳定(开机之后 条件满足后自动执行)
- Constraints 有约束条件
- observation of work status 状态可以被监听
- create complex chains of work 可以合并链式的组合工作
WorkManager 的使用
使用从 添加依赖、任务创建和开启、组合任务、任务监听和任务取消介绍任务的使用。
- 添加依赖
app 的build.gradle 添加依赖
def work_version = "2.7.1"
// (Java only)
implementation "androidx.work:work-runtime:$work_version"
- 普通任务创建和 开启
1 创建任务 创建一个class CWorker 继承与Worker,任务都是在 doWork里面执行,return 可以是Result.success Result.failer,Result.retry.
public class CWork extends Worker {
public CWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Result.success();
}
}
2 开启任务
开启任务需要生成一个WorkRequest ,然后workmanager执行enqueue就开始执行了。
// 普通任务 开启
private void playCommon(){
// 1 生成 WorkRequest
OneTimeWorkRequest aWorkRequest = new OneTimeWorkRequest.Builder(AWork.class).build();
// 2 workManager enqueue
WorkManager.getInstance(this).enqueue(aWorkRequest);
}
- 延时任务
workrequest 添加initialDelay参数就会延时执行
private void playDelay(){
// 参数1 是时长 参数2 是单位
OneTimeWorkRequest aWorkRequest = new OneTimeWorkRequest.Builder(AWork.class)
.setInitialDelay(1000, TimeUnit.MILLISECONDS) // 延时时间执行
.build();
WorkManager.getInstance(this).enqueue(aWorkRequest);
}
- 条件任务
任务可以添加约束条件,例如网络约束(无网络,联网,wifi,计费流量等)、保持电量充足的时候执行、在充电的时候执行、storage不足的时候不执行、待机下执行等约束条件。
不满足条件的时候work 就会被block,满足条件就会执行。
private void playConstraints(){
@SuppressLint("IdleBatteryChargingConstraints") Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)//设置网络情况 例如 wifi 联网 计费流量等
.setRequiresBatteryNotLow(true)//设置在电量不足的情况下不执行
.setRequiresCharging(false)//在充电时执行
.setRequiresStorageNotLow(true)//设置在storage不足的情况下不执行
.setRequiresDeviceIdle(false)//在待机情况下执行 非待机下不执行
.build();
OneTimeWorkRequest aWorkRequest = new OneTimeWorkRequest.Builder(AWork.class)
.setConstraints(constraints) // 设置条件
.build();
WorkManager instance = WorkManager.getInstance(this);
instance.enqueue(aWorkRequest);
}
- retry 任务
retry 任务需要work 的dowork 方法返回值Result 的retry。才会再次执行,而且是当retry的时候执行了新的work,这个times 的值非static 的时候每次都是初始值。
public class RetryWork extends Worker {
private String TAG = "RetryWork";
public static int times = 0;
public RetryWork(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@SuppressLint("RestrictedApi")
@NonNull
@Override
public Result doWork() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (times >= 2) {
return Result.success();
}else {
times++;
Log.d(TAG,"times :"+times);
return Result.retry();
}
}
}
retry 的时候 setBackoffCriteria 可以设置retry 的时间和类型,
BackoffPolicy.LINEAR 是线性每次间隔时间一样,BackoffPolicy.EXPONENTIAL 每次间隔时间会递增。
@RequiresApi(api = Build.VERSION_CODES.O)
private void playRetry(){
// 1 work return Result.retry()
OneTimeWorkRequest aWorkRequest = new OneTimeWorkRequest.Builder(RetryWork.class)
.setBackoffCriteria(BackoffPolicy.LINEAR, Duration.ofSeconds(10)) // 重试设置10s后重试 线性间隔
// .setBackoffCriteria(BackoffPolicy.EXPONENTIAL,Duration.ofSeconds(10))// 重试设置10s后重试 线性间隔
.build();
WorkManager instance = WorkManager.getInstance(this);
instance.enqueue(aWorkRequest);
}
- 周期任务
PeriodicWorkRequest 和 OnetimeWorkRequest 类型相反,是周期性任务。
周期任务区分为 设置 flex 时间和 不设置flex 时间两种。
1 不设置flex时间 每次间隔这段时间执行一次
三参数 (AWork.class,30,TimeUnit.MINUTES)
参数1 work
参数2 时间间隔
参数3 时间单位
2 设置flex时间(AWork.class,30,TimeUnit.MINUTES,15,TimeUnit.MINUTES)
第四个参数和第五个参数设置flex时间
flex时间 需要少于 间隔时间。
[ before flex | flex ][ before flex | flex ]...
间隔时间被分为 before flex 和flex 时间段,任务的执行在flex时间段里面。
// 周期任务
private void playPeriod(){
//
// PeriodicWorkRequest aWorkRequest = new PeriodicWorkRequest.Builder(AWork.class,30,TimeUnit.MINUTES)
// .build();
// [ before flex | flex ][ before flex | flex ]...
// [ cannot run work | can run work ][ cannot run work | can run work ]...
PeriodicWorkRequest aWorkRequest = new PeriodicWorkRequest.Builder(AWork.class,30,TimeUnit.MINUTES,15,TimeUnit.MINUTES)
.build();
WorkManager instance = WorkManager.getInstance(this);
instance.enqueue(aWorkRequest);
}
- 任务添加标记
任务添加标记,此标记用来搜索标记取消等可以使用。
private void playTag(){
// 参数1 是时长 参数2 是单位
OneTimeWorkRequest aWorkRequest = new OneTimeWorkRequest.Builder(AWork.class)
.addTag("tag") // 标记 主要用来查询
.build();
WorkManager.getInstance(this).enqueue(aWorkRequest);
}
- 任务参数
1 给任务传参数
setInputData 给任务传参数
work 里面通过 getInputData 获取参数
2 从任务传出结果带参数
Result.success(data);或者 Result.failer(data) 可以设置结果。
@NonNull
@Override
public Result doWork() {
Data inputData = getInputData();
String param = inputData.getString("param1");
Log.d(TAG,"doWork start param:"+param);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Data.Builder builder = new Data.Builder();
@SuppressLint("RestrictedApi")
Data data = builder.put("key", "work A").build();
Log.d(TAG,"doWork end");
return Result.success(data);
}
// 传参
private void playParam(){
// 1 传入 work 2 work 传出结果
Data data = new Data.Builder()
.putString("param","input")
.build();
OneTimeWorkRequest aWorkRequest = new OneTimeWorkRequest.Builder(AWork.class)
.setInputData(data) // 传递的数据
.build();
WorkManager instance = WorkManager.getInstance(this);
instance.enqueue(aWorkRequest);
instance.getWorkInfoByIdLiveData(aWorkRequest.getId()).observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(WorkInfo workInfo) {
workInfo.getOutputData();
}
});
}
- 任务进度设置
work 里面设置进度 setProgressAsync 设置
@NonNull
@Override
public Result doWork() {
setProgressAsync(new Data.Builder().putInt(PROGRESS, 0).build());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setProgressAsync(new Data.Builder().putInt(PROGRESS, 100).build());
Log.d(TAG,"doWork end");
return Result.success();
}
LiveData 监听里面获取到进度
//set play progress
private void setPlayProgress(){
···
instance.getWorkInfoByIdLiveData(aWorkRequest.getId()).observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(WorkInfo workInfo) {
Data progress = workInfo.getProgress();// 进度
}
});
}
- unique 任务
特殊任务,同样的名字的特殊任务会有冲突,可以设置冲突的解决方式。
ExistingWorkPolicy (REPLACE,KEEP,APPEND,APPEND_OR_REPLACE)
private void playUnique(){
WorkManager instance = WorkManager.getInstance(this);
OneTimeWorkRequest aWorkRequest = new OneTimeWorkRequest.Builder(AWork.class)
.build();
// ExistingWorkPolicy
// •REPLACE: 用新工作替换现有工作。此选项将取消现有工作。
// •KEEP: 保留现有工作,并忽略新工作。
// •APPEND: 将新工作附加到现有工作的末尾。此选项会将新工作链接到现有工作,并在现有工作完成后运行。并且现有工作将成为新工作的先决条件。如果现有工作为CANCELLED或者FAILED状态,新工作也会变为CANCELLED或者FAILED状态。
// •APPEND_OR_REPLACE: 此选项类似于APPEND,不过它不依赖于现有工作的状态。即使现有工作为CANCELLED或者FAILED状态,新工作仍旧会运行。
WorkContinuation uniqye_a = instance.beginUniqueWork("uniqye_A", ExistingWorkPolicy.APPEND, aWorkRequest);
uniqye_a.enqueue();
}
组合任务
1 通过 workmanager 的方法 beginWith (works).then(works)进行,里面的works 可以是单参数和list。
/**
* 2 合并A和B 然后执行C
*/
private void multipleWork(){
OneTimeWorkRequest aWork = new OneTimeWorkRequest.Builder(AWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
OneTimeWorkRequest BWork = new OneTimeWorkRequest.Builder(BWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
OneTimeWorkRequest CWork = new OneTimeWorkRequest.Builder(CWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
WorkManager instance = WorkManager.getInstance(this);
instance.cancelAllWork();
instance.beginWith(Arrays.asList(aWork,BWork)).then(CWork).enqueue();
instance.getWorkInfosByTagLiveData("mul").observe(this, new Observer<List<WorkInfo>>() {
@Override
public void onChanged(List<WorkInfo> workInfos) {
for (WorkInfo workInfo : workInfos) {
Log.d(TAG,"onChanged workInfo:"+workInfo);
}
}
});
}
2 组合任务的组合
通过 WorkContinuation 复杂组合任务
/**
* 2 任务1 合并A和B 然后执行C
* 任务2 合并D和E 然后执行F
* 任务1 和2 同时
*/
@SuppressLint("EnqueueWork")
private void multipleWork2(){
OneTimeWorkRequest aWork = new OneTimeWorkRequest.Builder(AWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
OneTimeWorkRequest BWork = new OneTimeWorkRequest.Builder(BWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
OneTimeWorkRequest CWork = new OneTimeWorkRequest.Builder(CWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
OneTimeWorkRequest dWork = new OneTimeWorkRequest.Builder(AWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
OneTimeWorkRequest eWork = new OneTimeWorkRequest.Builder(BWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
OneTimeWorkRequest fWork = new OneTimeWorkRequest.Builder(CWork.class)
.addTag("mul") // 设置 TAG// .setExpedited()
.build();
WorkManager instance = WorkManager.getInstance(this);
instance.cancelAllWork();
WorkContinuation work1 = instance.beginWith(Arrays.asList(aWork, BWork)).then(CWork);
WorkContinuation work2 = instance.beginWith(Arrays.asList(eWork, dWork)).then(fWork);
WorkContinuation.combine(Arrays.asList(work1,work2)).enqueue();
}
搜索任务
通过 id,tag,uniquename,,searchRequest (组合搜索 id,tag,state,uniquename)
private void searchWork(){
// 1 id
WorkManager instance = WorkManager.getInstance(this);
ListenableFuture<WorkInfo> workInfoById = instance.getWorkInfoById();
WorkInfo workInfo= workInfoById.get();
// 2 通过tag
instance.getWorkInfosByTag("");
// 3 通过uniqueName
instance.getWorkInfosForUniqueWork("");
// 4 通过组合条件
WorkQuery.Builder query = WorkQuery.Builder.fromIds(Arrays.asList(UUID.fromString("ss")));
WorkQuery.Builder.fromTags(Arrays.asList("tag1","tag2","tag3"));
WorkQuery.Builder.fromStates(Arrays.asList(WorkInfo.State.BLOCKED,WorkInfo.State.FAILED));
WorkQuery.Builder.fromUniqueWorkNames(Arrays.asList("name1","name2"));
// 上面是 单独某一个类型去查询
// 下面是根据 && 类型去添加
// query.addIds();
// query.addTags();
// query.addStates();
// query.addUniqueWorkNames();
instance.getWorkInfos(query.build());
}
WorkQuery搜索是通过搜索数据库搜索的
query.addIds addTags addStates 等方法都是&& 条件搜索的。
public static SupportSQLiteQuery workQueryToRawQuery(@NonNull WorkQuery querySpec) {
List<Object> arguments = new ArrayList<>();
StringBuilder builder = new StringBuilder("SELECT * FROM workspec");
String conjunction = " WHERE";
List<WorkInfo.State> states = querySpec.getStates();
if (!states.isEmpty()) {
List<Integer> stateIds = new ArrayList<>(states.size());
for (WorkInfo.State state : states) {
stateIds.add(WorkTypeConverters.stateToInt(state));
}
builder.append(conjunction)
.append(" state IN (");
bindings(builder, stateIds.size());
builder.append(")");
arguments.addAll(stateIds);
conjunction = " AND";
}
List<UUID> ids = querySpec.getIds();
if (!ids.isEmpty()) {
List<String> workSpecIds = new ArrayList<>(ids.size());
for (UUID id : ids) {
workSpecIds.add(id.toString());
}
builder.append(conjunction)
.append(" id IN (");
bindings(builder, ids.size());
builder.append(")");
arguments.addAll(workSpecIds);
conjunction = " AND";
}
List<String> tags = querySpec.getTags();
if (!tags.isEmpty()) {
builder.append(conjunction)
.append(" id IN (SELECT work_spec_id FROM worktag WHERE tag IN (");
bindings(builder, tags.size());
builder.append("))");
arguments.addAll(tags);
conjunction = " AND";
}
List<String> uniqueWorkNames = querySpec.getUniqueWorkNames();
if (!uniqueWorkNames.isEmpty()) {
builder.append(conjunction)
.append(" id IN (SELECT work_spec_id FROM workname WHERE name IN (");
bindings(builder, uniqueWorkNames.size());
builder.append("))");
arguments.addAll(uniqueWorkNames);
conjunction = " AND";
}
builder.append(";");
return new SimpleSQLiteQuery(builder.toString(), arguments.toArray());
}
监听任务
添加搜索的任务
//
private void addListener(){
WorkManager instance = WorkManager.getInstance(this);
// 通过查询 liveData 然后 observer
instance.getWorkInfoByIdLiveData("").observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(WorkInfo workInfo) {
}
});
instance.getWorkInfosByTagLiveData("tag").observe(this, new Observer<List<WorkInfo>>() {
@Override
public void onChanged(List<WorkInfo> workInfos) {
}
});
}
取消任务
根据 id tag uniquename 等取消
// cancel
private void cancelWork(){
WorkManager instance = WorkManager.getInstance(this);
// 通过查询 liveData 然后 observer
instance.cancelAllWork();
instance.cancelAllWorkByTag();
instance.cancelWorkById();
instance.cancelUniqueWork();
}
工作原理
WorkManager 任务的稳定性和条件满足的 原理两方面去分析
开机启动自启动任务
bootComplate 广播接收
<receiver
android:name="androidx.work.impl.background.systemalarm.RescheduleReceiver"
···>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
</intent-filter>
</receiver>
public class RescheduleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= WorkManagerImpl.MIN_JOB_SCHEDULER_API_LEVEL) {
try {
WorkManagerImpl workManager = WorkManagerImpl.getInstance(context);
final PendingResult pendingResult = goAsync();
workManager.setReschedulePendingResult(pendingResult);
} catch (IllegalStateException e) {
}
} else {
Intent reschedule = CommandHandler.createRescheduleIntent(context);
context.startService(reschedule);
}
}
}
WorkManagerImpl 里面 初始化
public static @NonNull WorkManagerImpl getInstance(@NonNull Context context) {
synchronized (sLock) {
WorkManagerImpl instance = getInstance();
if (instance == null) {
Context appContext = context.getApplicationContext();
if (appContext instanceof Configuration.Provider) {
initialize(
appContext,
((Configuration.Provider) appContext).getWorkManagerConfiguration());
instance = getInstance(appContext);
} else {
}
}
return instance;
}
}
public static void initialize(@NonNull Context context, @NonNull Configuration configuration) {
···
if (sDelegatedInstance == null) {
context = context.getApplicationContext();
if (sDefaultInstance == null) { // 初始化
sDefaultInstance = new WorkManagerImpl(
context,
configuration,
new WorkManagerTaskExecutor(configuration.getTaskExecutor()));
}
sDelegatedInstance = sDefaultInstance;
}
}
}
public WorkManagerImpl(
@NonNull Context context,
@NonNull Configuration configuration,
@NonNull TaskExecutor workTaskExecutor,
@NonNull WorkDatabase database) {
···
List<Scheduler> schedulers =
createSchedulers(applicationContext, configuration, workTaskExecutor);
Processor processor = new Processor(
context,
configuration,
workTaskExecutor,
database,
schedulers);
internalInit(context, configuration, workTaskExecutor, database, schedulers, processor); // 初始化
}
private void internalInit(···) {
···
// Checks for app force stops.
mWorkTaskExecutor.executeOnBackgroundThread(new ForceStopRunnable(context, this));
}
调用到 ForceStopRunnable run
@Override
public void run() {
try {
if (!multiProcessChecks()) {
return;
}
while (true) {
···
try {
forceStopRunnable();
break;
} catch (Exception exception) {
mRetryCount++;
···
}
} finally {
mWorkManager.onForceStopRunnableCompleted();
}
}
@VisibleForTesting
public void forceStopRunnable() {
boolean needsScheduling = cleanUp();
if (shouldRescheduleWorkers()) {
Logger.get().debug(TAG, "Rescheduling Workers.");
mWorkManager.rescheduleEligibleWork();
// Mark the jobs as migrated.
mWorkManager.getPreferenceUtils().setNeedsReschedule(false);
} else if (isForceStopped()) {
Logger.get().debug(TAG, "Application was force-stopped, rescheduling.");
mWorkManager.rescheduleEligibleWork();
} else if (needsScheduling) {
Logger.get().debug(TAG, "Found unfinished work, scheduling it."); // 调用到这里
Schedulers.schedule(
mWorkManager.getConfiguration(),
mWorkManager.getWorkDatabase(),
mWorkManager.getSchedulers());
}
}
Schedulers 的schedule 这里
public static void schedule(
@NonNull Configuration configuration,
@NonNull WorkDatabase workDatabase,
List<Scheduler> schedulers) {
···
WorkSpecDao workSpecDao = workDatabase.workSpecDao();
List<WorkSpec> eligibleWorkSpecsForLimitedSlots;
List<WorkSpec> allEligibleWorkSpecs;
workDatabase.beginTransaction();
try {
// Enqueued workSpecs when scheduling limits are applicable.
eligibleWorkSpecsForLimitedSlots = workSpecDao.getEligibleWorkForScheduling(
configuration.getMaxSchedulerLimit());
// Enqueued workSpecs when scheduling limits are NOT applicable.
allEligibleWorkSpecs = workSpecDao.getAllEligibleWorkSpecsForScheduling(
MAX_GREEDY_SCHEDULER_LIMIT);
if (eligibleWorkSpecsForLimitedSlots != null
&& eligibleWorkSpecsForLimitedSlots.size() > 0) {
long now = System.currentTimeMillis();
for (WorkSpec workSpec : eligibleWorkSpecsForLimitedSlots) {
workSpecDao.markWorkSpecScheduled(workSpec.id, now);
}
}
workDatabase.setTransactionSuccessful();
} finally {
workDatabase.endTransaction();
}
if (eligibleWorkSpecsForLimitedSlots != null
&& eligibleWorkSpecsForLimitedSlots.size() > 0) {
WorkSpec[] eligibleWorkSpecsArray =
new WorkSpec[eligibleWorkSpecsForLimitedSlots.size()];
eligibleWorkSpecsArray =
eligibleWorkSpecsForLimitedSlots.toArray(eligibleWorkSpecsArray);
// Delegate to the underlying schedulers.
for (Scheduler scheduler : schedulers) {
if (scheduler.hasLimitedSchedulingSlots()) { // SystemJobScheduler
scheduler.schedule(eligibleWorkSpecsArray);
}
}
}
if (allEligibleWorkSpecs != null && allEligibleWorkSpecs.size() > 0) {
WorkSpec[] enqueuedWorkSpecsArray = new WorkSpec[allEligibleWorkSpecs.size()];
enqueuedWorkSpecsArray = allEligibleWorkSpecs.toArray(enqueuedWorkSpecsArray);
// Delegate to the underlying schedulers.
for (Scheduler scheduler : schedulers) {
if (!scheduler.hasLimitedSchedulingSlots()) { // 这里调用的时GreedyScheduler 的schedule 方法 GreedyScheduler 是在 WoekManager 的createSchedulers 添加的
scheduler.schedule(enqueuedWorkSpecsArray);
}
}
}
}
eligibleWorkSpecsForLimitedSlots 列表是有限制的 或者周期性的worklist没执行的list。
他会进入到 SystemJobScheduler 里面去执行 。
schedule{
scheduleInternal(workSpec, jobId);
}
//mJobScheduler (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE),
scheduleInternal{
int result = mJobScheduler.schedule(jobInfo);
}
到条件后会调用到 SystemJobService 的 onStartJob
@Override
public boolean onStartJob(@NonNull JobParameters params) {
···
// We don't need to worry about the case where JobParams#isOverrideDeadlineExpired()
// returns true. This is because JobScheduler ensures that for PeriodicWork, constraints
// are actually met irrespective.
Logger.get().debug(TAG, String.format("onStartJob for %s", workSpecId));
mJobParameters.put(workSpecId, params);
}
WorkerParameters.RuntimeExtras runtimeExtras = null;
if (Build.VERSION.SDK_INT >= 24) {
runtimeExtras = new WorkerParameters.RuntimeExtras();
if (params.getTriggeredContentUris() != null) {
runtimeExtras.triggeredContentUris =
Arrays.asList(params.getTriggeredContentUris());
}
if (params.getTriggeredContentAuthorities() != null) {
runtimeExtras.triggeredContentAuthorities =
Arrays.asList(params.getTriggeredContentAuthorities());
}
if (Build.VERSION.SDK_INT >= 28) {
runtimeExtras.network = params.getNetwork();
}
}
// It is important that we return true, and hang on this onStartJob() request.
// The call to startWork() may no-op because the WorkRequest could have been picked up
// by the GreedyScheduler, and was already being executed. GreedyScheduler does not
// handle retries, and the Processor notifies all Schedulers about an intent to reschedule.
// In such cases, we rely on SystemJobService to ask for a reschedule by calling
// jobFinished(params, true) in onExecuted(...);
// For more information look at b/123211993
mWorkManagerImpl.startWork(workSpecId, runtimeExtras);
return true;
}
GreedyScheduler schedule 方法 没有延时 没有限制条件的直接 startwork 。 带延时直接延时处理。有限制条件的放到 限制条件的列表里面,后面条件任务里面会说明。
@Override
public void schedule(@NonNull WorkSpec... workSpecs) {
if (mInDefaultProcess == null) {
checkDefaultProcess();
}
if (!mInDefaultProcess) {
Logger.get().info(TAG, "Ignoring schedule request in a secondary process");
return;
}
registerExecutionListenerIfNeeded();
// Keep track of the list of new WorkSpecs whose constraints need to be tracked.
// Add them to the known list of constrained WorkSpecs and call replace() on
// WorkConstraintsTracker. That way we only need to synchronize on the part where we
// are updating mConstrainedWorkSpecs.
Set<WorkSpec> constrainedWorkSpecs = new HashSet<>();
Set<String> constrainedWorkSpecIds = new HashSet<>();
for (WorkSpec workSpec : workSpecs) {
long nextRunTime = workSpec.calculateNextRunTime();
long now = System.currentTimeMillis();
if (workSpec.state == WorkInfo.State.ENQUEUED) {
if (now < nextRunTime) {
// Future work
if (mDelayedWorkTracker != null) {
mDelayedWorkTracker.schedule(workSpec);
}
} else if (workSpec.hasConstraints()) {
if (SDK_INT >= 23 && workSpec.constraints.requiresDeviceIdle()) {
// Ignore requests that have an idle mode constraint.
Logger.get().debug(TAG,
String.format("Ignoring WorkSpec %s, Requires device idle.",
workSpec));
} else if (SDK_INT >= 24 && workSpec.constraints.hasContentUriTriggers()) {
// Ignore requests that have content uri triggers.
Logger.get().debug(TAG,
String.format("Ignoring WorkSpec %s, Requires ContentUri triggers.",
workSpec));
} else {
constrainedWorkSpecs.add(workSpec);
constrainedWorkSpecIds.add(workSpec.id);
}
} else {
mWorkManagerImpl.startWork(workSpec.id);
}
}
}
synchronized (mLock) {
if (!constrainedWorkSpecs.isEmpty()) {
mConstrainedWorkSpecs.addAll(constrainedWorkSpecs);
mWorkConstraintsTracker.replace(mConstrainedWorkSpecs);
}
}
}
条件任务例如网络低电量等条件任务
workmanager 的依赖里面 manifest 里面添加的有各种条件的广播接收receiver。
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxy$BatteryChargingProxy"
···>
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxy$BatteryNotLowProxy"
··· >
<intent-filter>
<action android:name="android.intent.action.BATTERY_OKAY" />
<action android:name="android.intent.action.BATTERY_LOW" />
</intent-filter>
</receiver>
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxy$StorageNotLowProxy"
··· >
<intent-filter>
<action android:name="android.intent.action.DEVICE_STORAGE_LOW" />
<action android:name="android.intent.action.DEVICE_STORAGE_OK" />
</intent-filter>
</receiver>
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxy$NetworkStateProxy"
··· >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
ConstraintProxy 接收
@Override
public void onReceive(Context context, Intent intent) {
Logger.get().debug(TAG, String.format("onReceive : %s", intent));
Intent constraintChangedIntent = CommandHandler.createConstraintsChangedIntent(context);
context.startService(constraintChangedIntent);
}
···
static Intent createConstraintsChangedIntent(@NonNull Context context) {
Intent intent = new Intent(context, SystemAlarmService.class);
intent.setAction(ACTION_CONSTRAINTS_CHANGED);
return intent;
}
SystemAlarmService 里面
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (mIsShutdown) {
Logger.get().info(TAG,
"Re-initializing SystemAlarmDispatcher after a request to shut-down.");
// Destroy the old dispatcher to complete it's lifecycle.
mDispatcher.onDestroy();
// Create a new dispatcher to setup a new lifecycle.
initializeDispatcher(); // 初始化 dispatcher
// Set mIsShutdown to false, to correctly accept new commands.
mIsShutdown = false;
}
if (intent != null) {
mDispatcher.add(intent, startId); / / 检测
}
// If the service were to crash, we want all unacknowledged Intents to get redelivered.
return Service.START_REDELIVER_INTENT;
}
SystemAlarmDispatcher 里面
public boolean add(@NonNull final Intent intent, final int startId) {
···
(CommandHandler.ACTION_CONSTRAINTS_CHANGED.equals(action)
&& hasIntentWithAction(CommandHandler.ACTION_CONSTRAINTS_CHANGED)) {
return false;
}
intent.putExtra(KEY_START_ID, startId);
synchronized (mIntents) {
boolean hasCommands = !mIntents.isEmpty();
mIntents.add(intent);
if (!hasCommands) {
// Only call processCommand if this is the first command.
// The call to dequeueAndCheckForCompletion will process the remaining commands
// in the order that they were added.
processCommand(); // 检测
}
}
return true;
}
@MainThread
@SuppressWarnings("FutureReturnValueIgnored")
private void processCommand() {
assertMainThread();
PowerManager.WakeLock processCommandLock =
WakeLocks.newWakeLock(mContext, PROCESS_COMMAND_TAG);
try {
processCommandLock.acquire();
// Process commands on the background thread.
mWorkManager.getWorkTaskExecutor().executeOnBackgroundThread(new Runnable() {
@Override
public void run() {
synchronized (mIntents) {
mCurrentIntent = mIntents.get(0);
}
if (mCurrentIntent != null) {
final String action = mCurrentIntent.getAction();
final int startId = mCurrentIntent.getIntExtra(KEY_START_ID,
DEFAULT_START_ID);
···
final PowerManager.WakeLock wakeLock = WakeLocks.newWakeLock(
mContext,
String.format("%s (%s)", action, startId));
try {
···
wakeLock.acquire();
mCommandHandler.onHandleIntent(mCurrentIntent, startId,
SystemAlarmDispatcher.this); // handler 处理message
} catch (Throwable throwable) {
···
} finally {
···
wakeLock.release();
···
postOnMainThread(
new DequeueAndCheckForCompletion(SystemAlarmDispatcher.this));
}
}
}
});
} finally {
processCommandLock.release();
}
}
CommonHandler onHandleIntent 再调用到 ConstraintsCommandHandler 的 onHandleIntent
@WorkerThread
void onHandleIntent(
@NonNull Intent intent,
int startId,
@NonNull SystemAlarmDispatcher dispatcher) {
String action = intent.getAction();
if (ACTION_CONSTRAINTS_CHANGED.equals(action)) { //条件变化 走到这里
handleConstraintsChanged(intent, startId, dispatcher);
} else if (ACTION_RESCHEDULE.equals(action)) {
handleReschedule(intent, startId, dispatcher);
} else {
Bundle extras = intent.getExtras();
if (!hasKeys(extras, KEY_WORKSPEC_ID)) {
Logger.get().error(TAG,
String.format("Invalid request for %s, requires %s.",
action,
KEY_WORKSPEC_ID));
} else {
if (ACTION_SCHEDULE_WORK.equals(action)) {
handleScheduleWorkIntent(intent, startId, dispatcher);
} else if (ACTION_DELAY_MET.equals(action)) {
handleDelayMet(intent, startId, dispatcher);
} else if (ACTION_STOP_WORK.equals(action)) {
handleStopWork(intent, dispatcher);
} else if (ACTION_EXECUTION_COMPLETED.equals(action)) {
handleExecutionCompleted(intent, startId);
} else {
Logger.get().warning(TAG, String.format("Ignoring intent %s", intent));
}
}
}
}
ConstraintsCommandHandler 里面
@WorkerThread
void handleConstraintsChanged() {
List<WorkSpec> candidates = mDispatcher.getWorkManager().getWorkDatabase()
.workSpecDao()
.getScheduledWork();
···
ConstraintProxy.updateAll(mContext, candidates);
// This needs to be done to populate matching WorkSpec ids in every constraint controller.
mWorkConstraintsTracker.replace(candidates);
List<WorkSpec> eligibleWorkSpecs = new ArrayList<>(candidates.size());
// Filter candidates should have already been scheduled.
long now = System.currentTimeMillis();
for (WorkSpec workSpec : candidates) {
String workSpecId = workSpec.id;
long triggerAt = workSpec.calculateNextRunTime();
if (now >= triggerAt && (!workSpec.hasConstraints()
|| mWorkConstraintsTracker.areAllConstraintsMet(workSpecId))) {
eligibleWorkSpecs.add(workSpec);
}
}
for (WorkSpec workSpec : eligibleWorkSpecs) {
String workSpecId = workSpec.id;
Intent intent = CommandHandler.createDelayMetIntent(mContext, workSpecId); // ACTION_DELAY_MET
Logger.get().debug(TAG, String.format(
"Creating a delay_met command for workSpec with id (%s)", workSpecId));
mDispatcher.postOnMainThread(
new SystemAlarmDispatcher.AddRunnable(mDispatcher, intent, mStartId)); // 里面 mDispatcher 。add
}
mWorkConstraintsTracker.reset();
}
}
//SystemAlarmDispatcher 里面
AddRunnable(@NonNull SystemAlarmDispatcher dispatcher,
@NonNull Intent intent,
int startId) {
mDispatcher = dispatcher;
mIntent = intent;
mStartId = startId;
}
@Override
public void run() {
mDispatcher.add(mIntent, mStartId);
}
又回到 dispacher 里面了 mDispatcher.add(mIntent, mStartId);
然后又到 commonHandler 里面的 handleConstraintsChanged
handleDelayMet(intent, startId, dispatcher);
}
之后DelayMetCommonHandler 里面处理
@WorkerThread
void handleProcessWork() {
mWakeLock = WakeLocks.newWakeLock(
mContext,
String.format("%s (%s)", mWorkSpecId, mStartId));
Logger.get().debug(TAG,
String.format("Acquiring wakelock %s for WorkSpec %s", mWakeLock, mWorkSpecId));
mWakeLock.acquire();
WorkSpec workSpec = mDispatcher.getWorkManager()
.getWorkDatabase()
.workSpecDao()
.getWorkSpec(mWorkSpecId);
// This should typically never happen. Cancelling work should remove alarms, but if an
// alarm has already fired, then fire a stop work request to remove the pending delay met
// command handler.
if (workSpec == null) {
stopWork();
return;
}
// Keep track of whether the WorkSpec had constraints. This is useful for updating the
// state of constraint proxies when onExecuted().
mHasConstraints = workSpec.hasConstraints();
if (!mHasConstraints) {
onAllConstraintsMet(Collections.singletonList(mWorkSpecId)); // 没有限制 直接就work
} else {
// Allow tracker to report constraint changes
mWorkConstraintsTracker.replace(Collections.singletonList(workSpec)); // 判断限制
}
}
WorkConstraintsTracker replace 方法
public void replace(@NonNull Iterable<WorkSpec> workSpecs) {
synchronized (mLock) {
for (ConstraintController<?> controller : mConstraintControllers) {
controller.setCallback(null);
}
for (ConstraintController<?> controller : mConstraintControllers) {
controller.replace(workSpecs);
}
for (ConstraintController<?> controller : mConstraintControllers) {
controller.setCallback(this);
}
}
}
ConstaintController
public void setCallback(@Nullable OnConstraintUpdatedCallback callback) {
if (mCallback != callback) {
mCallback = callback;
updateCallback(mCallback, mCurrentValue);
}
}
private void updateCallback(
@Nullable OnConstraintUpdatedCallback callback,
@Nullable T currentValue) {
// We pass copies of references (callback, currentValue) to updateCallback because public
// APIs on ConstraintController may be called from any thread, and onConstraintChanged() is
// called from the main thread.
if (mMatchingWorkSpecIds.isEmpty() || callback == null) {
return;
}
if (currentValue == null || isConstrained(currentValue)) {
callback.onConstraintNotMet(mMatchingWorkSpecIds); // 符合条件 callback 回去
} else {
callback.onConstraintMet(mMatchingWorkSpecIds);
}
}
满足条件后 会掉到 WorkConstraintsTracker 里面 遍历获取条件满足的 work之后 然后在回调到 DelayMetCommonHandler 里面的 onAllConstraintsMet 里面
// WorkConstraintsTracker
@Override
public void onConstraintMet(@NonNull List<String> workSpecIds) {
synchronized (mLock) {
List<String> unconstrainedWorkSpecIds = new ArrayList<>();
for (String workSpecId : workSpecIds) { // 遍历寻找所有的满足条件的work
if (areAllConstraintsMet(workSpecId)) {
Logger.get().debug(TAG, String.format("Constraints met for %s", workSpecId));
unconstrainedWorkSpecIds.add(workSpecId);
}
}
if (mCallback != null) {
mCallback.onAllConstraintsMet(unconstrainedWorkSpecIds); // 鬼掉到commonHandler 里面
}
}
}
// DelayMetCommonHandler 里面开启工作
@Override
public void onAllConstraintsMet(@NonNull List<String> workSpecIds) {
// WorkConstraintsTracker will call onAllConstraintsMet with list of workSpecs whose
// constraints are met. Ensure the workSpecId we are interested is part of the list
// before we call Processor#startWork().
if (!workSpecIds.contains(mWorkSpecId)) {
return;
}
synchronized (mLock) {
if (mCurrentState == STATE_INITIAL) {
mCurrentState = STATE_START_REQUESTED;
Logger.get().debug(TAG, String.format("onAllConstraintsMet for %s", mWorkSpecId));
// Constraints met, schedule execution
// Not using WorkManagerImpl#startWork() here because we need to know if the
// processor actually enqueued the work here.
boolean isEnqueued = mDispatcher.getProcessor().startWork(mWorkSpecId);
if (isEnqueued) {
// setup timers to enforce quotas on workers that have
// been enqueued
mDispatcher.getWorkTimer()
.startTimer(mWorkSpecId, WORK_PROCESSING_TIME_IN_MS, this);
} else {
// if we did not actually enqueue the work, it was enqueued before
// cleanUp and pretend this never happened.
cleanUp();
}
} else {
Logger.get().debug(TAG, String.format("Already started work for %s", mWorkSpecId));
}
}
}