鸿蒙操作系统使用 Background Tasks Kit 实现后台长时任务实战(本文已在AtomGit仓库开源)
一、背景说明
音乐播放、文件下载、运动导航这类应用的业务必须"退到后台还能继续跑",否则应用一进后台就被系统挂起。26.0.1 Beta1 为 Background Tasks Kit 新增了数据传输类型长时任务的进度模板通知与 updateDataTransferProgress() 接口,后台下载的进度展示能力进一步补齐。本文基于 @ohos.resourceschedule.backgroundTaskManager,完整实现"申请权限与通知授权 → 申请长时任务 → 模拟后台下载并更新进度 → 任务完成取消任务"的全流程,代码基于 API 21 及以上(含 26.0.x),可直接运行。
二、技术原理
长时任务(Continuous Task)是应用退后台后仍能持续运行的资格凭证,核心机制有三条:
- 类型声明与一致性校验:申请时必须声明任务类型(
BackgroundTaskMode,如 MODE_AUDIO_PLAYBACK、MODE_DATA_TRANSFER),系统会做一致性校验——申请了数据传输却没实际传数据、或申请播放却在录音,都会被管控(挂起甚至终止); - 通知绑定:长时任务申请成功后,通知栏会出现关联消息;用户删除该通知,系统自动停止任务。所以申请前要先调
notificationManager.requestEnableNotification()拿到通知授权; - 多任务与 ID 管理:API 21 起一个 UIAbility 可同时申请最多 10 个长时任务,每个任务有独立 ID;取消指定任务用
stopBackgroundRunning(context, taskId)。
26.0.1 的增量:startContinuousTask() 支持数据传输类型直接发送进度模板通知(progressInfo 可选进度环与完成响铃),也可用 updateDataTransferProgress() 持续更新;当存在进度类型实况窗且条件满足时,仅保留实况窗通知,避免重复打扰。
三、实现步骤
1. 权限与通知授权。module.json5 声明权限:
{
"module": {
"requestPermissions": [
{ "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" },
{ "name": "ohos.permission.INTERNET" }
]
}
}
2. 长时任务封装 entry/src/main/ets/task/ContinuousTaskHelper.ets(完整代码):
import { backgroundTaskManager } from '@kit.BackgroundTaskKit';
import { common } from '@kit.AbilityKit';
import { wantAgent, WantAgent } from '@kit.AbilityKit';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
const TAG: string = 'ContinuousTaskHelper';
export class ContinuousTaskHelper {
private taskId: number = -1;
// 通知授权是长时任务通知展示的前提
async enableNotification(): Promise<boolean> {
try {
await notificationManager.requestEnableNotification();
return true;
} catch (err) {
const e: BusinessError = err as BusinessError;
hilog.error(TAG, 'notification denied: %{public}d', e.code);
return false;
}
}
// 申请数据传输类型的长时任务
async startTask(context: common.UIAbilityContext): Promise<void> {
// wantAgent:点击通知跳回应用
const wantAgentObj: WantAgent =
await wantAgent.getWantAgent({ wants: [['ability.wantAction.home']] });
const request = new backgroundTaskManager.ContinuousTaskRequest();
request.backgroundTaskModes = [
backgroundTaskManager.BackgroundTaskMode.MODE_DATA_TRANSFER
];
request.wantAgent = wantAgentObj;
request.combinedTaskNotification = false;
// 26.0.1:数据传输类型可直接携带进度模板
request.progressInfo = {
progressValue: 0,
progressMax: 100,
isProgressRing: true,
isBell: false
};
try {
const taskId = await backgroundTaskManager.startContinuousTask(
context, request);
this.taskId = taskId as number;
hilog.info(TAG, 'task started, id=%{public}d', this.taskId);
} catch (err) {
const e: BusinessError = err as BusinessError;
hilog.error(TAG, 'start failed: %{public}d %{public}s', e.code, e.message);
throw e;
}
}
// 更新数据传输进度(仅 startContinuousTask 申请的任务支持)
async updateProgress(progressValue: number): Promise<void> {
try {
await backgroundTaskManager.updateDataTransferProgress(
this.taskId, progressValue, 100);
} catch (err) {
const e: BusinessError = err as BusinessError;
hilog.error(TAG, 'update progress failed: %{public}d', e.code);
}
}
// 任务结束:取消长时任务,避免退后台被系统挂起
async stopTask(): Promise<void> {
if (this.taskId < 0) { return; }
try {
await backgroundTaskManager.stopBackgroundRunning(this.taskId);
this.taskId = -1;
hilog.info(TAG, 'task stopped');
} catch (err) {
const e: BusinessError = err as BusinessError;
hilog.error(TAG, 'stop failed: %{public}d', e.code);
}
}
}
3. 页面调用 entry/src/main/ets/pages/Index.ets(完整代码):
import { ContinuousTaskHelper } from '../task/ContinuousTaskHelper';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Index {
private helper: ContinuousTaskHelper = new ContinuousTaskHelper();
@State log: string = '就绪';
build() {
Column({ space: 12 }) {
Text(this.log).fontSize(14)
Button('开始后台下载').onClick(async () => {
if (!await this.helper.enableNotification()) {
this.log = '未获通知授权'; return;
}
const ctx = this.getUIContext().getHostContext() as common.UIAbilityContext;
await this.helper.startTask(ctx);
// 模拟下载:进度走到 100 后取消任务
for (let p = 10; p <= 100; p += 10) {
await this.helper.updateProgress(p);
this.log = `下载进度 ${p}%`;
}
await this.helper.stopTask();
this.log = '下载完成,任务已取消';
})
}
.width('100%').height('100%').justifyContent(FlexAlign.Center)
}
}
四、应用场景示例
真实下载场景中,进度更新应放在下载回调里而不是定时循环:每收到一段数据调一次 updateProgress,下载全部完成后调 stopTask()。若应用在下载中途切到后台,长时任务保证进程不被挂起,下载持续进行,用户可在通知栏进度模板上直接看到百分比变化。
五、技术要点
- 通知授权前置:长时任务通知依附于通知授权,
requestEnableNotification()被拒绝后任务仍可申请,但通知缺失且用户无感知,建议把授权结果作为是否继续的分支条件; - 类型与实际业务必须一致:系统会做一致性校验,申请 MODE_DATA_TRANSFER 却无传输行为、或行为与申请类型不符,应用退后台会被挂起或终止;
- 两代接口的区别:
startBackgroundRunning()(API 21+)是通用接口,progressInfo 属性不生效;进度模板要用startContinuousTask()(26.0.1+),旧设备需做版本分支(可先用 startBackgroundRunning + updateBackgroundRunning 兜底); - 进度更新的调用约束:progressInfo 只在 startContinuousTask 申请且类型包含 MODE_DATA_TRANSFER 时生效;在 updateBackgroundRunning 中使用会报 9800006;数据传输类型不参与通知合并;
- 及时取消:任务结束立即 stop,带着已完结的长时任务退后台会被系统挂起;取消指定任务用
stopBackgroundRunning(context, taskId)(多任务场景); - 错误码:201 权限失败、9800005 校验失败、9800007 存储失败、9800008 设备类型不支持(26.0.1 新增),申请前可用 try/catch 区分处理。
六、扩展建议
26.0.1 起数据传输型长时任务与进度类型实况窗有联动规则:应用已挂进度实况窗、任务含 MODE_DATA_TRANSFER 且携带 progressInfo、类型不含录音/定位/VOIP 时,系统只保留实况窗通知。需要更丰富的进度样式可配合 Live View Kit;纯音频类后台播放则申请 MODE_AUDIO_PLAYBACK 并与 AVPlayer 的播放状态联动(暂停时及时取消,恢复时重新申请)。
结语
本文用约 130 行 ArkTS 完成了数据传输型长时任务从申请、进度更新到取消的完整闭环,核心是 ContinuousTaskRequest 的类型声明、通知授权前置与 26.0.1 的进度模板能力。按"申请—执行—取消"的节奏管理任务生命周期,应用即可在退后台后合规地持续工作。
代码仓库
本文完整示例工程已在 AtomGit 开源,为标准鸿蒙 Stage 工程(AppScope 应用配置、entry 模块、长时任务封装与页面、hvigor 构建脚本齐全),DevEco Studio 可直接打开编译运行:https://atomgit.com/NJPJI_Yang/hm-article-2026-11-24-continuous-task-background-tasks-kit
更多推荐




所有评论(0)