suspendfunupdatePhotoUploadWork(){// Get instance of WorkManager.valworkManager=WorkManager.getInstance(context)// Retrieve the work request ID. In this example, the work being updated is unique// work so we can retrieve the ID using the unique work name.valphotoUploadWorkInfoList=workManager.getWorkInfosForUniqueWork(PHOTO_UPLOAD_WORK_NAME).await()valexistingWorkRequestId=photoUploadWorkInfoList.firstOrNull()?.id?:return// Update the constraints of the WorkRequest to not require a charging device.valnewConstraints=Constraints.Builder()// Add other constraints as required here..setRequiresCharging(false).build()// Create new WorkRequest from existing Worker, new constraints, and the id of the old WorkRequest.valupdatedWorkRequest:WorkRequest=OneTimeWorkRequestBuilder<MyWorker>().setConstraints(newConstraints).setId(existingWorkRequestId).build()// Pass the new WorkRequest to updateWork().workManager.updateWork(updatedWorkRequest)}
getGeneration:对getGeneration()WorkInfo。返回的 Int 对应于
WorkRequest。
请注意,没有生成字段或属性,只有
WorkInfo.getGeneration() 方法结合使用。
曲目生成示例
以下是上述工作流的实现示例,
检索 WorkRequest 的世代。
// Get instance of WorkManager.valworkManager=WorkManager.getInstance(context)// Retrieve WorkInfo instance.valworkInfo=workManager.getWorkInfoById(oldWorkRequestId)// Call getGeneration to retrieve the generation.valgeneration=workInfo.getGeneration()
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# Update work that is already enqueued\n\nWorkManager allows you to update a [`WorkRequest`](/reference/androidx/work/WorkRequest) after you have already\nenenqueued it. This is often necessary in larger apps that frequently change\nconstraints or need to update their workers on the fly. As of WorkManager\nversion 2.8.0, the [`updateWork()`](/reference/androidx/work/WorkManager#updateWork(androidx.work.WorkRequest)) API is the means of doing this.\n\nThe `updateWork()` method allows you to change certain aspects of a\n`WorkRequest` on the fly, without having to go through the process of manually\ncanceling and enqueuing a new one. This greatly simplifies the development\nprocess.\n\nAvoid canceling work\n--------------------\n\nYou should generally avoid canceling an existing WorkRequest and enqueuing a new\none. Doing so can result in the app repeating certain tasks, and can require you\nto write a significant amount of additional code.\n\nConsider the following examples of where canceling a WorkRequest can cause\ndifficulties:\n\n- **Back-end request:** If you cancel a [`Worker`](/reference/androidx/work/Worker) while it is computing a payload to send to the server, the new `Worker` needs to start over and recompute the potentially expensive payload.\n- **Scheduling:** If you cancel a [`PeriodicWorkRequest`](/reference/androidx/work/PeriodicWorkRequest) and you would like the new `PeriodicWorkRequest` to execute on the same schedule, you need to calculate a time offset to ensure that the new execution time is aligned with the previous work request.\n\nThe `updateWork()` API allows you to update a work request's constraints and\nother parameters without the trouble of canceling and enqueuing a new request.\n\n### When to cancel work\n\nThere are cases where you should directly cancel a `WorkRequest` rather than\ncall `updateWork()`. This is what you should do when you wish to change the\nfundamental nature of the work that you have enqueued.\n| **Caution:** It is not possible to use `updateWork()` to change the type of `Worker` in a `WorkRequest`. For example, if you have enqueued a `OneTimeWorkRequest` and you would like for it to run periodically, you must cancel the request and schedule a new `PeriodicWorkRequest`.\n\n### When to update work\n\nImagine a photo app that does a daily backup of the user's photos. It has\nenqueued a `PeriodicWorkRequest` to do so. The `WorkRequest` has constraints\nthat require the device to be charging and connected to WiFi.\n\nHowever, the user only charges their device for 20 minutes a day using a fast\ncharger. In this case, the app may want to update the `WorkRequest` to relax the\ncharging constraint, so that it can still upload the photos even if the device\nisn't fully charged.\n\nIn this situation, you can use the `updateWork()` method to update the work\nrequest's constraints.\n\nHow to update work\n------------------\n\nThe `updateWork()` method provides a simple means of updating an existing\n`WorkRequest`, without having to cancel and enqueue a new one.\n\nTo use update enqueued work follow these steps:\n\n1. **Get the existing ID for enqueued work** : Get the ID of the WorkRequest you would like to update. You can retrieve this ID with any of the [`getWorkInfo`](/reference/androidx/work/WorkManager#getWorkInfosByTag(java.lang.String)) APIs, or by manually persisting the ID from the initial WorkRequest for later retrieval with the public property [`WorkRequest.id`](/reference/androidx/work/WorkRequest#id()), before enqueuing it.\n2. **Create new WorkRequest** : Create a new `WorkRequest` and use `WorkRequest.Builder.setID()` to set its ID to match that of the existing `WorkRequest`.\n3. **Set constraints** : Use `WorkRequest.Builder.setConstraints()` to pass the WorkManager new constraints.\n4. **Call updateWork** : Pass the new WorkRequest to `updateWork()`.\n\n### Update work example\n\nHere is an example code snippet in Kotlin that demonstrates how to use the\n`updateWork()` method to change the battery constraints of a `WorkRequest` used\nto upload photos: \n\n suspend fun updatePhotoUploadWork() {\n // Get instance of WorkManager.\n val workManager = WorkManager.getInstance(context)\n\n // Retrieve the work request ID. In this example, the work being updated is unique\n // work so we can retrieve the ID using the unique work name.\n val photoUploadWorkInfoList = workManager.getWorkInfosForUniqueWork(\n PHOTO_UPLOAD_WORK_NAME\n ).await()\n\n val existingWorkRequestId = photoUploadWorkInfoList.firstOrNull()?.id ?: return\n\n // Update the constraints of the WorkRequest to not require a charging device.\n val newConstraints = Constraints.Builder()\n // Add other constraints as required here.\n .setRequiresCharging(false)\n .build()\n\n // Create new WorkRequest from existing Worker, new constraints, and the id of the old WorkRequest.\n val updatedWorkRequest: WorkRequest =\n OneTimeWorkRequestBuilder\u003cMyWorker\u003e()\n .setConstraints(newConstraints)\n .setId(existingWorkRequestId)\n .build()\n\n // Pass the new WorkRequest to updateWork().\n workManager.updateWork(updatedWorkRequest)\n }\n\n### Handle the result\n\n`updateWork()` returns a `ListenableFuture\u003cUpdateResult\u003e`. The given\n`UpdateResult` can have one of the several values that outline whether or not\nWorkManager was able to apply your changes. It also indicates when it was able\nto apply the change.\n\nFor more information, see the [`updateWork()`](/reference/androidx/work/WorkManager.UpdateResult) [and](/reference/androidx/work/WorkManager.UpdateResult) [`UpdateResult`](/reference/androidx/work/WorkManager.UpdateResult)\n[reference](/reference/androidx/work/WorkManager.UpdateResult).\n\nTrack work with generations\n---------------------------\n\nEach time you update a `WorkRequest`, its *generation* increments by one. This\nlets you track exactly which `WorkRequest` is currently enqueued.\nGenerations provide you more control when observing, tracing, and testing work\nrequests.\n\nTo get the generation of a `WorkRequest`, follow these steps:\n\n1. **WorkInfo** : Call `WorkManager.getWorkInfoById()` to retrieve an instance of [`WorkInfo`](/reference/androidx/work/WorkInfo) corresponding to your `WorkRequest`.\n - You can call one of several methods that return a `WorkInfo`. For more information, see the [WorkManager reference](/reference/androidx/work/WorkManager#getWorkInfoById(java.util.UUID)).\n2. **getGeneration** : Call [`getGeneration()`](/reference/androidx/work/WorkInfo#getGeneration()) on the instance of `WorkInfo`. The `Int` returned corresponds to the generation of the `WorkRequest`.\n - Note that there isn't a generation field or property, only the `WorkInfo.getGeneration()` method.\n\n### Track generation example\n\nThe following is an example implementation of the workflow described above for\nretrieving the generation of a `WorkRequest`. \n\n // Get instance of WorkManager.\n val workManager = WorkManager.getInstance(context)\n\n // Retrieve WorkInfo instance.\n val workInfo = workManager.getWorkInfoById(oldWorkRequestId)\n\n // Call getGeneration to retrieve the generation.\n val generation = workInfo.getGeneration()\n\n| **Note:** The `UpdateResult` that `updateWork()` returns does not include the generation of the `WorkRequest`.\n\nPolicies for updating work\n--------------------------\n\nPreviously, the recommended solution to updating periodic work was to enqueue a\n`PeriodicWorkRequest` with the policy [`ExistingPeriodicWorkPolicy.REPLACE`](/reference/androidx/work/ExistingPeriodicWorkPolicy#REPLACE).\nIf there was a pending `PeriodicWorkRequest` with the same unique `id`, the new\nwork request would cancel and delete it. This policy is now *deprecated* in\nfavor of the workflow using the [`ExistingPeriodicWorkPolicy.UPDATE`](/reference/androidx/work/ExistingPeriodicWorkPolicy#UPDATE).\n\nFor example, when using [`enqueueUniquePeriodicWork`](/reference/androidx/work/WorkManager#enqueueUniquePeriodicWork(java.lang.String,androidx.work.ExistingPeriodicWorkPolicy,androidx.work.PeriodicWorkRequest)) with a\n`PeriodicWorkRequest`, you can initialize the new `PeriodicWorkRequest` with the\n`ExistingPeriodicWorkPolicy.UPDATE` policy. If there is a pending\n`PeriodicWorkRequest` with the same unique name, WorkManager updates it to the\nnew specification. Following this workflow, it is not necessary to use\n`updateWork()`.\n| **Note:** A similar update policy doesn't exist for `OneTimeWorkRequest`. This is because you can use the [`enqueueUniqueWork`](/reference/androidx/work/WorkManager#enqueueUniqueWork(java.lang.String,androidx.work.ExistingWorkPolicy,androidx.work.OneTimeWorkRequest)) method with the [`APPEND`](/reference/androidx/work/ExistingWorkPolicy#APPEND) or [`APPEND_OR_REPLACE`](/reference/androidx/work/ExistingWorkPolicy#APPEND_OR_REPLACE) policies. Doing so creates a chain of workers with the same name. As such, WorkManager can't effectively support an `UPDATE` policy for them, as it isn't possible to decide which workers in the chain it should update."]]