鸿蒙启动后台服务运行

复制代码
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));
    }
  }
相关推荐
lqj_本人6 小时前
鸿蒙electron跨端框架PC今日打卡实战:频率、连续天数和今日进度怎么放进桌面工具
华为·harmonyos
GitCode官方11 小时前
直播预约|开源鸿蒙PC命令行工具迁移实战:从环境搭建到真机验证全流程拆解
人工智能·华为·开源·harmonyos·atomgit
lqj_本人11 小时前
鸿蒙electron跨端框架PC工志簿实战:项目、工时、阻塞和下一步都要有位置
数据库·华为·harmonyos
胡琦博客16 小时前
Tauri 如何跑到鸿蒙上?从 tauri-demo 看 OpenHarmony 适配链路
华为·harmonyos
nashane17 小时前
HarmonyOS 6学习:文件打开方式应用重复的根治方案与最佳实践
学习·华为·harmonyos
Swift社区17 小时前
AI + 鸿蒙 App:下一代应用架构
人工智能·架构·harmonyos
ZHW_AI课题组17 小时前
调用华为云API实现图像标签识别
图像处理·华为·华为云
枫叶丹417 小时前
【HarmonyOS 6.0】Enterprise Space Kit:空间管理服务深入解析
开发语言·华为·harmonyos