Direct answer
Cancellation is a request to stop future work and cooperate with cleanup; it is not proof that every native operation stopped instantly. For WorkManager, Android documents cancellation by ID, unique name, or tag and notes that a running Worker receives a stop callback. A worker should check its stopped state, abort long loops, close files and database handles, and avoid publishing a partial model artifact as complete. An in-process coroutine has a different lifetime: it stops with the process and should cooperate with structured cancellation. The UI should distinguish cancelling, cancelled, completed, and failed. Local AI tasks often combine stages: queue request, load model, read a file, preprocess media, infer, validate, persist result, and update UI. Cancellation policy should specify which stages may finish and which must stop. If model loading cannot be interrupted, the app may wait for it to finish and then close the runtime before reporting cancellation. If a file transfer is cancelled, keep partial bytes only when the resumable-download contract says they can be validated later. A downstream worker should not continue just because an upstream task emitted a partial output. Give every task a stable ID and one owner. A cancel button should reach the actual Worker, coroutine job, or runtime cancellation API; hiding a progress indicator or removing a collector does not necessarily stop computation. Ensure that cancellation also prevents stale output from being saved after the user has moved to another task. Use unique work names or an explicit deduplication key to avoid duplicate workers. When replacing a WorkRequest, understand whether the chosen policy cancels the old task and whether downstream dependencies also cancel. Cancellation must preserve user data intentionally. A user may want to keep a captured image or prompt even if inference is cancelled, while a temporary download or decoded buffer can be deleted after safe cleanup. Make retention decisions by data type. For shared files, do not delete a final artifact that another task or app currently uses. Record task stage and outcome without logging private source content. Test cancellation before a task starts, during model initialization, during preprocessing, during inference, between inference and persistence, and while a retry is queued. Verify callbacks, job state, resource close count, no late writes, and whether a new request can start. Repeat after process recreation for persistent WorkManager tasks; in-process coroutines should be treated as gone after process death rather than recoverable. A useful implementation contract includes a cancellation token or job, stable request identity, idempotent state transitions, and a final cleanup block. Define whether cancellation is best-effort, which operations may still complete, and how the UI reports that. Never claim a hard stop if the runtime or API offers only cooperative cancellation. Verification sequence: 1. Identify the execution owner and API: WorkManager request, coroutine Job, service, or native runtime call. Route the user’s cancel action to that owner. 2. Check cancellation at safe boundaries and in long loops; override stop callbacks where required to release held resources. 3. Prevent downstream persistence and callbacks from committing results after cancellation or a newer request. 4. Preserve user inputs according to the declared policy, clean temporary artifacts only when safe, and record a privacy-safe outcome. 5. Start a new task and prove the old task cannot deliver stale state or keep native resources open. The goal is responsive cancellation with known semantics, not an empty spinner.
The user cancels a background model task and immediately retries
A user queued an on-device summarization task and taps Cancel after waiting. They immediately start a different document. The old Worker may still be finalizing a file or returning an inference stream.
Decision
Cancel through the actual execution owner, isolate both request identities, close resources cooperatively, and reject late results from the old task.
Expected outcome
Only the new task can update the current screen, while the old task reports a safe cancelled or stopping state.
Evidence to collect
The claim becomes reviewable only when the following evidence is attached to the same artifact and test run:
- Cancellation propagation trace
- Resource cleanup
- Resume or restart behavior
A runtime comparison is publishable only when artifact identity, build configuration, selected backend, task fixture, and failures are recorded.
Implementation workflow
- Route cancel to the execution owner. Determine whether the task is WorkManager work, an in-process coroutine, a foreground service, or native inference. A hidden UI or disposed collector is not enough; invoke the owner’s documented cancellation API.
- Stop cooperatively and release resources. Check cancellation between stages and inside long loops. Close file, database, recorder, and runtime handles in a finally or worker-stop path; avoid deleting a final artifact that other work currently uses.
- Guard state and downstream effects. Associate results with request identity and refuse writes from a cancelled or stale job. Review unique-work replacement policies and dependency chains so follow-on tasks do not continue unexpectedly.
- Test timing windows and retry. Cancel before start, during load, preprocessing, inference, before save, and while retry is queued. Confirm one close path, no late write, privacy-safe logs, and a successful new request after cleanup.
Keep each transition observable. A failure should identify the stage, artifact, runtime, and recovery action without logging private user content.
Acceptance criteria
- The user action reaches the actual worker, job, service, or runtime owner.
- Cancellation prevents stale output persistence and releases resources according to the API contract.
- A new task can start without an old callback overwriting its state or using its input.
Decision table
| Dimension | Choice or evidence | How to interpret it |
|---|---|---|
| Hide the progress indicator | UI-only cancellation | The worker or native inference may continue and still write a result. |
| Cancel WorkManager or coroutine job | Owner-directed cancellation | Stops or requests stop according to the API, with cleanup callbacks to implement. |
| Force process termination | Abrupt stop | May lose recoverable state and does not replace a correct cleanup contract. |
Failure patterns to prevent
- Cancelling notification only
- Saving partial output as complete
Also prevent silent fallback, unpinned artifacts, missing cancellation, and conclusions that combine unlike configurations. Store unsuccessful runs alongside successful ones.
Minimum reproducibility record
| Layer | Record |
|---|---|
| Device | Manufacturer, model, chipset, RAM class, operating-system build |
| Software | Application version and git commit |
| Model | Family, variant, revision, format, file length, hash, quantization |
| Runtime | Name, revision, requested backend, observed backend evidence |
| Workload | Fixture revision, input hash, prompt hash, output policy |
| Outcome | Completed, failed, cancelled, fallback, and privacy-safe diagnostics |
Release checklist
- ☐ The primary query is answered without an unsupported number.
- ☐ Every artifact and runtime is pinned.
- ☐ The representative task and failure policy are explicit.
- ☐ Lifecycle, cancellation, cleanup, and fallback are tested.
- ☐ User-content and network boundaries are documented.
- ☐ Result wording applies only to the recorded configuration.
- ☐ The page links to raw method or evidence when results are added.
Sources and related evidence
- Android persistent background work
- Android Developers — manage and cancel WorkManager work
- Android Developers — persistent background work
- Kotlin Coroutines — cancellation and timeouts
Chinese deployment and troubleshooting content is organized in the .奇连 AI 端侧专题.
Frequently asked questions
Does cancelling WorkManager stop a running Worker immediately?
Cancellation changes work state and signals a running worker to stop; the worker must cooperate and release resources. Do not assume every native call is interrupted at the exact moment the user taps.
Is hiding a loading screen enough to cancel inference?
No. Removing a UI collector or navigating away does not necessarily stop the execution owner. Route cancellation to the Worker, coroutine, service, or runtime operation.
Should cancellation delete a partially downloaded model?
Only when the download policy says those bytes are unsafe or unusable. Preserve resumable partial data after validating its identity; never remove a final artifact another task is using.