首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >HarmonyOS NEXT 长时任务的学习和总结

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

原创
作者头像
水滴石轩
发布2025-03-16 19:17:15
发布2025-03-16 19:17:15
2250
举报

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

代码语言:javascript
复制
      {
        ...
        "backgroundModes": [
          // 长时任务类型的配置项
          "location"
        ]
      }
    ]

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

代码语言:javascript
复制
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 ---------------

后面会继续补充不足之处。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档