按照官方文档开启长时任务:
startContinuousTask() {
let wantAgentInfo: wantAgent.WantAgentInfo = {
// 点击通知后,将要执行的动作列表
// 添加需要被拉起应用的bundleName和abilityName
wants: [
{
bundleName: "com.xxxx.xxxx.news",
abilityName: "com.xxxx.xxxx.news.EntryAbility"
}
],
// 指定点击通知栏消息后的动作是拉起ability
actionType: wantAgent.OperationType.START_ABILITY,
// 使用者自定义的一个私有值
requestCode: 0,
// 点击通知后,动作执行属性
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// 通过wantAgent模块下getWantAgent方法获取WantAgent对象
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
backgroundTaskManager.startBackgroundRunning(getContext(),
backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
console.info(`Succeeded in operationing startBackgroundRunning.`);
}).catch((err: BusinessError) => {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
});
}
stopContinuousTask() {
backgroundTaskManager.stopBackgroundRunning(getContext()).then(() => {
console.info(`Succeeded in operationing stopBackgroundRunning.`);
}).catch((err: BusinessError) => {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
}
调用stopContinuousTask方法报错:
Failed to operation stopBackgroundRunning. Code is 9800005, message is BussinessError 9800005: Continuous Task verification failed. The application has not applied for a continuous task.
长时任务有约束和限制,其中运行限制里面,如果应用申请了长时任务,但是未真正执行申请类型的长时任务或申请类型的任务已结束,系统会对应用进行管控。
简单的说,申请完长时任务,系统会在5秒之内检测是都执行申请类型的长时任务,没有,就直接结束任务了,那再触发stopContinuousTask就会报这个错。
约束限制可参见指导:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides...约束与限制