gpt4 book ai didi

android - Android WorkManager 何时停止 Worker?

转载 作者:行者123 更新时间:2023-12-04 11:15:21 25 4
gpt4 key购买 nike

我们有一个使用 WorkManager 处理后台同步工作的 Android 应用程序。我们的同步 worker 是这样的:

public class SyncWorker extends Worker {

[...]

@NonNull
@Override
public Result doWork() {

if (canNotRetry(getRunAttemptCount())) {
// This could seem unreachable, consider removing... or not... because if stopped by the
// system, the work might be retried by design
CBlogger.INSTANCE.log([...]);
return Result.success();
}

boolean syncOk = false;

//Sync
try (Realm realm = Realm.getDefaultInstance()) {

// Doing sync related ops & network calls
// checking this.isStopped() between operations to quit
// sync activity when worker has to be stopped

syncOk = true;
} catch (Throwable throwable) {
CBlogger.INSTANCE.log([...]);
}

// On error, continue with following code to avoid any logic in catch
// This method must NOT throw any unhandled exception to avoid unique work to be marked as failed
try {

if (syncOk) {
return Result.success();
}

if (canNotRetry(getRunAttemptCount() + 1)) {
CBlogger.INSTANCE.log([...]);
return Result.success();
} else {
CBlogger.INSTANCE.log([...]);
return Result.retry();
}
} catch (Throwable e) {
CBlogger.INSTANCE.log([...]);
return Result.success();
}
}

private boolean canNotRetry(int tryNumber) {
// Check if the work has been retry too many times
if (tryNumber > MAX_SYNC_RETRY_COUNT) {
CBlogger.INSTANCE.log([...]);
return true;
} else {
return false;
}
}

@Override
public void onStopped() {
CBlogger.INSTANCE.log([...]);
}
}

这项工作是由帮助类的专用方法安排的:

    public static void scheduleWorker(Context context, String syncPolicy, ExistingWorkPolicy existingWorkingPolicy){

Constraints constraints = new Constraints.Builder()
.setRequiresCharging(false)
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();

Data.Builder data = new Data.Builder();
data.putString(context.getResources().getString(R.string.sync_worker_policy), syncPolicy);

Log.d(TAG, "Scheduling one-time sync request");
logger.info("Scheduling one-time sync request");
OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder
(SyncWorker.class)
.setInputData(data.build())
.setConstraints(constraints)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
OneTimeWorkRequest.MIN_BACKOFF_MILLIS,
TimeUnit.MILLISECONDS)
.build();

WorkManager.getInstance(context).enqueueUniqueWork("OneTimeSyncWorker", existingWorkingPolicy, oneTimeWorkRequest);
}

当用户单击“同步”按钮或由另一个计划每 20' 运行一次的工作人员调用并以这种方式调用帮助程序的函数时调用它:

SyncWorkerManager.scheduleWorker(context, context.getResources().getString(R.string.sync_worker_policy_full), ExistingWorkPolicy.KEEP);

以便新的同步仅在尚未等待或运行时才排队。请注意,同步工作策略强制要求连接网络。

这种策略总体来说效果很好,但有时我们会在日志中发现 Worker 的 onStopped()在 SyncWorker 启动后几秒钟(大约 10 英寸)调用该方法。

已知我们从不以编程方式停止外部的特定 Worker,我们只调用 WorkManager.getInstance(context).cancelAllWork();在注销过程中或新登录之前(也安排 del 定期 Worker),系统何时可以决定停止 Worker 并调用其 onStopped()方法?

我知道它可能发生在以下情况:
  • 不再满足约束(网络连接断开)
  • Worker 运行超过 JobScheduler 实现施加的 10' 限制(我们的场景在 Android 9 设备上测试)
  • 具有相同名称和 REPLACE 策略的新独特工作(我们从未在我们的应用程序中将此策略用于 SyncWorker,仅用于 PeriodicSyncWorker)
  • 由于 this bug 引起的虚假调用(我们使用“androidx.work:work-runtime:2.2.0”)

  • 是否有任何其他情况可以导致 worker 停止?就像是:
  • 打盹模式
  • 应用备用桶
  • 应用后台限制(设置 --> 应用 --> 我的应用 --> 电池 --> 允许后台)
  • 应用电池优化(设置--> 应用--> 我的应用--> 电池--> 电池优化)

  • 谢谢

    最佳答案

    Worker 有多种原因可以停止。您可以明确要求取消它,否则 WorkManager 可能会出于各种原因停止它,这些原因是 documented here .

    关于android - Android WorkManager 何时停止 Worker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175506/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com