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

2025-03-05  本文已影响0人  水滴石轩

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

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

上一篇 下一篇

猜你喜欢

热点阅读