#鸿蒙通关秘籍#HarmonyOS NEXT后台长时任务如何申请与管理?

HarmonyOS
2024-11-29 15:02:32
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
SSD白云孤飞

在HarmonyOS NEXT中,应用在后台执行长时间任务需要申请长时任务,以避免被系统挂起的情况。该操作需要如下步骤:

  1. 必须申请ohos.permission.KEEP_BACKGROUND_RUNNING权限。可以在module.json5config.json文件中声明所需的权限。
  2. module.json5中,为需要使用长时任务的UIAbility上声明相应的长时任务类型,示例如下:
    "module": {
        "abilities": [
            {
                "backgroundModes": [
                "audioRecording"
                ], 
            }
        ],
        ...
    }
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
  3. 通过Promise接口startBackgroundRunningstopBackgroundRunning来申请和取消长时任务。以下是调用示例:
    startContinuousTask() {
      let wantAgentInfo = {
        wants: [
          {
            bundleName: "com.example.myapplication",
            abilityName: "com.example.myapplication.MainAbility"
          }
        ],
        actionType: wantAgent.OperationType.START_ABILITY,
        requestCode: 0,
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
      };
    
      wantAgent.getWantAgent(wantAgentInfo).then(wantAgentObj => {
         backgroundTaskManager.startBackgroundRunning(this.context,
           backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
           console.info(`Succeeded in startBackgroundRunning.`);
         }).catch(err => {
           console.error(`Failed to startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
         });
      });
    }
    
    stopContinuousTask() {
       backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
         console.info(`Succeeded in stopBackgroundRunning.`);
       }).catch(err => {
         console.error(`Failed to stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
       });
    }
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.
    • 20.
    • 21.
    • 22.
    • 23.
    • 24.
    • 25.
    • 26.
    • 27.
    • 28.
    • 29.
    • 30.

通过这些步骤,确保在应用的后台任务中使用符合条件的长时任务类型,实现应用的长时间稳定运行。

分享
微博
QQ
微信
回复
2024-11-29 17:13:51


相关问题
后台长时任务启动失败
2616浏览 • 1回复 待解决
后台长时任务启动失败报错码201
2940浏览 • 1回复 待解决
如何申请多个长时任务
2447浏览 • 1回复 待解决
HarmonyOS 申请时任务报错9800006 -
337浏览 • 1回复 待解决