即时配送场景中,骑手上线后需要在后台同时维持"持续定位"与"来单语音播报"两类受管控行为:单一长时任务只能携带一种后台模式,无法同时承载定位与音频播报;系统或用户还可能随时取消某个长时任务,应用必须能按任务粒度精确启停,并及时感知取消事件自动收尾。
本示例以骑手接单应用为载体,基于backgroundTaskManager创建多个相互独立的长时任务,配合geoLocationManager实现后台持续定位、textToSpeech实现后台来单播报,提供以下场景:
骑手上线时,分别申请location和audioPlayback两种类型的长时任务,各自携带不同的requestCode生成独立的WantAgent,系统会创建两个相互独立的长时任务,通知栏分别显示两条通知。此功能依赖API Version 21+,startBackgroundRunning返回ContinuousTaskNotification对象,其中continuousTaskId用于标识任务,后续可按该ID精确停止:
startLocationTask(): void {
const context = this.getUIContext().getHostContext();
if (context === undefined) {
return;
}
// A distinct requestCode makes the system create an independent continuous task
const locationWantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: 'com.demo.backgroundtask',
abilityName: 'EntryAbility'
}
],
actionType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
wantAgent.getWantAgent(locationWantAgentInfo).then((locationWantAgentObj: WantAgent) => {
backgroundTaskManager.startBackgroundRunning(context, ['location'], locationWantAgentObj)
.then((notification: backgroundTaskManager.ContinuousTaskNotification) => {
// continuousTaskId identifies the task and is used to stop it later
this.locationTaskId = notification.continuousTaskId !== undefined ? notification.continuousTaskId : -1;
this.registerTaskCancelListener();
this.startLocationUpdate();
})
// ...
});
} 播报长时任务通过不同的requestCode创建,与定位任务相互独立:
startBroadcast(): void {
const context = this.getUIContext().getHostContext();
if (context === undefined) {
return;
}
// A different requestCode generates a second independent continuous task
const audioWantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: 'com.demo.backgroundtask',
abilityName: 'EntryAbility'
}
],
actionType: wantAgent.OperationType.START_ABILITY,
requestCode: 1,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
wantAgent.getWantAgent(audioWantAgentInfo).then((audioWantAgentObj: WantAgent) => {
backgroundTaskManager.startBackgroundRunning(context, ['audioPlayback'], audioWantAgentObj)
.then((notification: backgroundTaskManager.ContinuousTaskNotification) => {
this.audioTaskId = notification.continuousTaskId !== undefined ? notification.continuousTaskId : -1;
// ...
})
// ...
});
this.initTtsEngine();
this.startBroadcastTimer();
} API Version 21+ 新增stopBackgroundRunning(context, continuousTaskId)重载,支持按任务ID精确停止指定长时任务,两个任务互不影响。停止定位任务时同时注销定位监听与任务取消监听:
stopLocationTask(): void {
const context = this.getUIContext().getHostContext();
if (context === undefined) {
return;
}
this.stopLocationUpdate();
this.unregisterTaskCancelListener();
if (this.locationTaskId !== -1) {
// Stop only the task with the given id, leaving other tasks running
backgroundTaskManager.stopBackgroundRunning(context, this.locationTaskId)
.then(() => {
// ...
this.locationTaskId = -1;
})
// ...
}
} 停止播报任务时同时清理播报定时器并释放TTS引擎:
stopBroadcast(): void {
const context = this.getUIContext().getHostContext();
if (context !== undefined && this.audioTaskId !== -1) {
backgroundTaskManager.stopBackgroundRunning(context, this.audioTaskId)
.then(() => {
// ...
this.audioTaskId = -1;
})
// ...
}
if (this.broadcastTimerId !== -1) {
clearInterval(this.broadcastTimerId);
this.broadcastTimerId = -1;
}
if (this.ttsEngine !== null) {
// ...
this.ttsEngine.stop();
this.ttsEngine.shutdown();
// ...
this.ttsEngine = null;
}
} 注册continuousTaskCancel监听,当系统或用户取消长时任务时,通过AppStorage通知UI层:
registerTaskCancelListener(): void {
if (this.taskCancelCallback !== null) {
return;
}
// Report the cancel event through AppStorage so the UI layer can react
this.taskCancelCallback = () => {
AppStorage.setOrCreate('bgTaskCancelled', true);
};
backgroundTaskManager.on('continuousTaskCancel', this.taskCancelCallback);
} UI层通过@StorageLink + @Watch感知取消事件:
@StorageLink('bgTaskCancelled') @Watch('onBgTaskCancelled') bgTaskCancelled: boolean = false; 回调中自动下线、停止定位与播报,并弹窗提示:
onBgTaskCancelled(): void {
if (!this.bgTaskCancelled) {
return;
}
this.bgTaskCancelled = false;
if (!this.isOnline) {
return;
}
this.isOnline = false;
this.stopLocationUpdate();
this.stopBroadcast();
this.unregisterTaskCancelListener();
// ...
this.getUIContext().getPromptAction().showDialog({
title: $r('app.string.dialog_title_notice'),
message: $r('app.string.dialog_auto_offline_message'),
buttons: [{ text: $r('app.string.dialog_button_got_it'), color: 'rgba(10, 89, 247, 1)' }]
});
} 启用geoLocationManager.on('locationChange')以5秒间隔持续获取位置,配合location类型长时任务保证后台运行:
startLocationUpdate(): void {
// Keep receiving locations every 5 seconds while the app stays in the background
const request: geoLocationManager.ContinuousLocationRequest = {
interval: 5,
locationScenario: geoLocationManager.UserActivityScenario.NAVIGATION
};
// ...
geoLocationManager.on('locationChange', request, (location: geoLocationManager.Location) => {
this.currentLatitude = location.latitude;
this.currentLongitude = location.longitude;
// ...
});
// ...
} 创建TTS引擎时通过extraParams设置isBackStage: true启用后台播报能力,配合audioPlayback长时任务保证后台播报不被中断:
initTtsEngine(): void {
// isBackStage enables speaking while the app is in the background
const extraParam: Record<string, Object> = {
'style': 'interaction-broadcast',
'locate': 'CN',
'name': 'DeliveryTts',
'isBackStage': true
};
const initParams: textToSpeech.CreateEngineParams = {
language: 'zh-CN',
person: 0,
online: 1,
extraParams: extraParam
};
textToSpeech.createEngine(initParams).then((engine: textToSpeech.TextToSpeechEngine) => {
this.ttsEngine = engine;
engine.setListener(this.buildSpeakListener());
})
// ...
} 通过setInterval每10秒播报一次来单提醒:
startBroadcastTimer(): void {
// Broadcast a new-order reminder every 10 seconds
this.broadcastTimerId = setInterval(() => {
this.broadcastNewOrder();
}, BROADCAST_INTERVAL);
}
broadcastNewOrder(): void {
if (this.ttsEngine === null) {
return;
}
const context = this.getUIContext().getHostContext();
if (context === undefined) {
return;
}
this.ttsRequestId++;
const speakExtraParam: Record<string, Object> = {
'speed': 1,
'volume': 2,
'pitch': 1,
'languageContext': 'zh-CN',
'audioType': 'pcm',
'playType': 1,
'queueMode': 1
};
const speakParams: textToSpeech.SpeakParams = {
requestId: `tts_${this.ttsRequestId}`,
extraParams: speakExtraParam
};
this.ttsEngine.speak(context.resourceManager.getStringSync($r('app.string.tts_new_order').id), speakParams);
}
获取网络权限:ohos.permission.INTERNET。
获取粗略位置权限:ohos.permission.APPROXIMATELY_LOCATION。
获取精确定位权限:ohos.permission.LOCATION。
获取后台位置权限:ohos.permission.LOCATION_IN_BACKGROUND。
申请长时任务权限:ohos.permission.KEEP_BACKGROUND_RUNNING。
├──entry/src/main/ets // 代码区 │ ├──entryability │ │ └──EntryAbility.ets // UIAbility生命周期 │ ├──entrybackupability │ │ └──EntryBackupAbility.ets // 备份能力 │ ├──model │ │ └──OrderModel.ets // 数据模型与Mock数据 │ └──pages │ ├──Index.ets // 订单列表主页(长时任务管理+定位+播报) │ └──MapPage.ets // 地图详情页 └──entry/src/main/resources // 应用资源目录