鸿蒙启动后台服务运行

复制代码
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));
    }
  }
相关推荐
jiejiejiejie_10 小时前
Flutter for OpenHarmony 心情日记功能实战指南
flutter·华为
Math_teacher_fan11 小时前
Flutter 跨平台开发实战:鸿蒙与音乐律动艺术(六)、Lissajous 利萨茹曲线:频率耦合的轨迹艺术
flutter·ui·数学建模·华为·harmonyos·鸿蒙系统
xmdy586613 小时前
Flutter+开源鸿蒙实战|智安盾电商溯源平台Day3 溯源查询逻辑+鸿蒙网络请求适配
flutter·开源·harmonyos
maaath13 小时前
【maaath】Flutter 跨平台日历日程应用开发实战
flutter·华为·harmonyos
LeesonWong14 小时前
架构困境与四层结构化设计
harmonyos
梦想不只是梦与想15 小时前
鸿蒙 应用市场更新功能:版本检测与更新提醒
harmonyos·鸿蒙·版本更新
xmdy586615 小时前
Flutter+开源鸿蒙实战|智安盾电商溯源平台Day2 首页+核心入口UI开发(鸿蒙多端适配)
flutter·开源·harmonyos
jiejiejiejie_16 小时前
Flutter for OpenHarmony 萌系 UI 实战合集:骨架屏 + 引导页一站式指南
flutter·ui·华为
nashane19 小时前
HarmonyOS 6学习:HAR包与HSP包的选择与优化指南
学习·华为·harmonyos·harmonyos 5
全栈若城19 小时前
自定义 TabBar 实战:浮动标签栏与舵式标签栏
harmonyos·harmonyos6·三方库开发