为了账号安全,请及时绑定邮箱和手机立即绑定

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

想要使用鸿蒙的长时任务需要配置权限: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 ---------------

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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消