HarmonyOS NEXT 长时任务的学习和总结

举报
水滴石轩 发表于 2025/03/09 16:46:04 2025/03/09
【摘要】 想要使用鸿蒙的长时任务需要配置权限:ohos.permission.KEEP_BACKGROUND_RUNNING并在module.json5中配置需要处理的长时任务类型,此处以定位为例: { ... "backgroundModes": [ // 长时任务类型的配置项 "location" ] ...

想要使用鸿蒙的长时任务需要配置权限:ohos.permission.KEEP_BACKGROUND_RUNNING
并在module.json5中配置需要处理的长时任务类型,此处以定位为例:

      {
        ...
        "backgroundModes": [
          // 长时任务类型的配置项
          "location"
        ]
      }
    ]

然后再合适的地方调用startBackgroundRunning方法开启长时任务,通过调用stopBackgroundRunning方法关闭长时任务
具体代码如下:

import { common, wantAgent, WantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { CSLogger } from './CSLogger';

const TAG: string = 'CSBackgroundTask';

export function startContinuousTask(context: common.UIAbilityContext) {
  let wantAgentInfo: wantAgent.WantAgentInfo = {
    // 点击通知后,将要执行的动作列表
    // 添加需要被拉起应用的bundleName和abilityName
    wants: [
      {
        bundleName: "com.example.csharmonyosdemo",
        abilityName: "EntryAbility"
      }
    ],
    // 指定点击通知栏消息后的动作是拉起ability
    actionType: wantAgent.OperationType.START_ABILITY,
    // 使用者自定义的一个私有值
    requestCode: 0,
    // 点击通知后,动作执行属性
    actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
  };

  try {
    // 通过wantAgent模块下getWantAgent方法获取WantAgent对象
    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
      try {
        let list: Array<string> = ["location"];
        backgroundTaskManager.startBackgroundRunning(context, list, wantAgentObj).then((res: backgroundTaskManager.ContinuousTaskNotification) => {
          CSLogger.info(TAG, "Operation startBackgroundRunning succeeded");
          // 此处执行具体的长时任务逻辑,如录音,录制等。

          setInterval(() => {
            CSLogger.info(TAG, "backgroundRunning task continue");
          }, 1000*60);
        }).catch((error: BusinessError) => {
          CSLogger.info(TAG, `Failed to Operation startBackgroundRunning. code is ${error.code} message is ${error.message}`);
        });
      } catch (error) {
        CSLogger.info(TAG, `Failed to Operation startBackgroundRunning. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
      }
    });
  } catch (error) {
    CSLogger.info(TAG, `Failed to Operation getWantAgent. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
  }
}

export function stopContinuousTask(context: common.UIAbilityContext) {
  backgroundTaskManager.stopBackgroundRunning(context).then(() => {
    CSLogger.info(TAG, `Succeeded in operationing stopBackgroundRunning.`);
  }).catch((err: BusinessError) => {
    CSLogger.info(TAG, `Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
  });
}`

此处CSLogger是自定义日志工具,详情可以查看我的其他文章

----------------- end ---------------

后面会继续补充不足之处。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。