鸿蒙启动后台服务运行

复制代码
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));
    }
  }
相关推荐
小雨下雨的雨2 小时前
鸿蒙PC应用:工程结构解析与配置文件详解
ui·华为·harmonyos·鸿蒙系统
世人万千丶3 小时前
鸿蒙跨端框架 Flutter 学习 Day 3:性能进阶——Iterable 延迟加载与计算流的智慧
学习·flutter·ui·华为·harmonyos·鸿蒙·鸿蒙系统
夜雨声烦丿3 小时前
Flutter 框架跨平台鸿蒙开发 - 打造全能健康指数计算器,BMI/体脂率/热量/饮水一站式管理
flutter·华为·harmonyos
夜雨声烦丿3 小时前
Flutter 框架跨平台鸿蒙开发 - 打造实时汇率换算器,支持20+货币与离线模式
flutter·华为·harmonyos
时光慢煮3 小时前
基于 Flutter × OpenHarmony 开发的去除空行 / 多余空格工具实战
flutter·华为·开源·openharmony
世人万千丶4 小时前
鸿蒙跨端框架 Flutter 学习 Day 3:综合实践——多维数据流与实时交互实验室
学习·flutter·华为·交互·harmonyos·鸿蒙
世人万千丶4 小时前
鸿蒙跨端框架 Flutter 学习 Day 3:工程实践——数据模型化:从黑盒 Map 走向强类型 Class
学习·flutter·ui·华为·harmonyos·鸿蒙·鸿蒙系统
IT陈图图4 小时前
基于 Flutter × OpenHarmony 的应用头部信息区域的实现与解析
flutter·华为·openharmony
大雷神5 小时前
Harmony App 开发中Flutter 与鸿蒙原生交互传参教程
flutter·交互·harmonyos