1.在module.json5中
"requestPermissions": [
{"name": "ohos.permission.INTERNET"},
{"name": "ohos.permission.GET_BUNDLE_INFO"},
{"name": "ohos.permission.KEEP_BACKGROUND_RUNNING"}
],
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"backgroundModes": [
"dataTransfer" // 对应 BackgroundMode.DATA_TRANSFER
],
2.在EntryAblility中
async onForeground(): Promise<void> {
// Ability has brought to foreground
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
try {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [{ bundleName: 'com.xxx.xxx', abilityName: 'EntryAbility' }],
actionType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
const wantAgentObj = await wantAgent.getWantAgent(wantAgentInfo);
const taskTypes = ['dataTransfer']; // 或 ['audioPlayback'], ['audioRecording'] 等
const res = await backgroundTaskManager.startBackgroundRunning(this.context, backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj);
// console.info('后台长时任务已申请, notificationId:', res.notificationId);
} catch (e) {
console.error('申请后台长时任务失败:', JSON.stringify(e));
}
}
鸿蒙启动后台服务运行
安卓理事人2026-01-17 14:21
相关推荐
程序员黑豆2 小时前
鸿蒙应用开发教程:以红绿灯切换为例,掌握条件渲染的核心用法Catrice03 小时前
HarmonyOS ArkTS 实战:实现一个校园证件照拍摄与预约应用qizayaoshuap3 小时前
# [特殊字符] 手电筒 — 鸿蒙ArkTS设备功能调用与UI交互设计JaneConan3 小时前
鸿蒙报错速查:arkts-no-any any 类型禁用,用了就炸,根因 + 真解法listening7774 小时前
HarmonyOS 6.1 UX动效实战:从“生硬”到“灵动”的物理动画引擎2301_768103495 小时前
HarmonyOS趣味相机实战第29篇:AudioRenderer合成快门声、并发门闩与资源释放listening7776 小时前
HarmonyOS 6.1 混沌工程实战:从“故障免疫”到“韧性架构”特立独行的猫a6 小时前
Python三方库鸿蒙PC移植指南PPT程序员黑豆6 小时前
鸿蒙应用开发:ForEach 循环渲染用法详解国服第二切图仔6 小时前
01-three-layer-architecture