HarmonyOS 一个应用同申请多个长时任务,创建多个UIAbility的demo

如果一个应用同时需要申请多个长时任务,需要创建多个UIAbility有没有相关demo

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/continuous-task-V5

HarmonyOS
2025-01-09 17:08:00
497浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
superinsect

在main里面new一个ability,在新的ability里面 windowStage.loadContent(‘pages/Index’, (err) => {}跳转至新的长时任务页面。

在module里面多个ability都要配置

"backgroundModes": [
"location",
"audioPlayback"
],
"abilities": [
{
  "name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"backgroundModes": [
  "location",
  "audioPlayback"
  ],
  "skills": [
  {
    "entities": [
    "entity.system.home"
    ],
    "actions": [
    "action.system.home"
    ]
  }
  ]
},
{
  "name": "EntryAbility1",
"srcEntry": "./ets/entryability1/EntryAbility1.ets",
"description": "$string:EntryAbility1_desc",
"icon": "$media:layered_image",
"label": "$string:EntryAbility1_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"backgroundModes": [
  "location",
  "audioPlayback"
  ]
}
],
  • 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.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.

在新开的ability的Index里面正常配置长时任务即可,例如

//Index.ets
import geoLocationManager from '@ohos.geoLocationManager';
import { PermissionUtils } from './PermissionUtils';
import common from '@ohos.app.ability.common';
import { BackgroundUtil } from './BackgroundUtil';
import hilog from '@ohos.hilog';
import { Want } from '@kit.AbilityKit';

const TAG: string = 'testTag'
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State count: number = 0;
  @State handlePopup: boolean = false
  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;

  aboutToAppear() {
    PermissionUtils.requestPermissionsFromUser(["ohos.permission.APPROXIMATELY_LOCATION", 'ohos.permission.LOCATION'], getContext(this) as common.UIAbilityContext);
    setInterval(() => {
      this.count++;
    }, 1000);
    PermissionUtils.requestPermissionsFromUser(["ohos.permission.APPROXIMATELY_LOCATION", 'ohos.permission.LOCATION'], getContext(this) as common.UIAbilityContext);

  }

  build() {
    Row() {
      Column() {
        Text(this.count.toString())
          .fontSize(50)
          .fontWeight(FontWeight.Bold);

        Button('ablity')
          .onClick(() => {
            // 跳转到文档列表的 UIAbility
            let want: Want = {
              deviceId: '',
              bundleName: 'com.example.continuoustask',
              moduleName: 'entry',
              abilityName: 'EntryAbility1'
            }
            // 跳转
            this.context.startAbility(want)
          })
        Button("开启长时任务").onClick(() => {
          console.log("123456")
          let requestInfo: geoLocationManager.LocationRequest = {
            'priority': geoLocationManager.LocationRequestPriority.ACCURACY,
            'timeInterval': 0,
            'distanceInterval': 0,
            'maxAccuracy': 0
          };
          let locationChange = (location: geoLocationManager.Location): void => {
            console.log('locationChanger: data: ' + JSON.stringify(location));
          };
          geoLocationManager.on('locationChange', requestInfo, locationChange);
          BackgroundUtil.startContinuousTask(this.context);
          this.handlePopup = true;
        }).bindPopup(this.handlePopup, {
          message: '开启长时任务成功',
        }).margin({
          bottom: '5%'
        })
          .align(Alignment.Center)

        Button("关闭长时任务").onClick(() => {
          BackgroundUtil.stopContinuousTask(this.context);
        })
          .bindPopup(!this.handlePopup, {
            message: '关闭长时状态',
          }).margin({
          /* bottom: '1%'*/
        }).backgroundColor(Color.Red)
          .width('50%')
      } .alignItems(HorizontalAlign.Center)
      .justifyContent(FlexAlign.SpaceAround)
      .size({width: "100%", height: 120})
    }
  }
}


//BackgroundUtil.ets

import common from '@ohos.app.ability.common';
import wantAgent from '@ohos.app.ability.wantAgent';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import hilog from '@ohos.hilog';
import { BusinessError } from '@ohos.base';

const TAG = 'testTag';

export class BackgroundUtil {
  /**
   * Start background task.
   *
   * @param context
   */
  public static startContinuousTask(context: common.UIAbilityContext): void {
    hilog.info(0x00000, TAG, '启动长时任务');
    let wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          bundleName: context.abilityInfo.bundleName,
          abilityName: context.abilityInfo.name
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
    };

    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
      try {
        backgroundTaskManager.startBackgroundRunning(context, backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj)
          .then(() => {
            hilog.info(0x0000, TAG, 'startBackgroundRunning succeeded');
          })
          .catch((err: BusinessError) => {
            hilog.error(0x0000, TAG, `startBackgroundRunning failed Cause: ${JSON.stringify(err)}`);
          });
      } catch (error) {
        hilog.error(0x0000, TAG, `stopBackgroundRunning failed. error: ${JSON.stringify(error)} `);
      }
    });
  }

  /**
   * Stop background task.
   *
   * @param context
   */
  public static stopContinuousTask(context: common.UIAbilityContext): void {
    hilog.info(0x00000, TAG, '停止长时任务');
    try {
      backgroundTaskManager.stopBackgroundRunning(context).then(() => {
        hilog.info(0x0000, TAG, 'stopBackgroundRunning succeeded');
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, TAG, `stopBackgroundRunning failed Cause: ${JSON.stringify(err)}`);
      })
    } catch (error) {
      hilog.error(0x0000, TAG, "stopBackgroundRunning")
    }
    ;
  }
}
  • 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.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
分享
微博
QQ
微信
回复
2025-01-09 20:17:44


相关问题
如何申请多个时任务
2613浏览 • 1回复 待解决
HarmonyOS 申请时任务报错9800006 -
518浏览 • 1回复 待解决
什么场景需要创建多个UIAbility
2457浏览 • 1回复 待解决
音视频播放是否需要创建时任务
2558浏览 • 1回复 待解决
多个UIAbility多个进程吗?
2926浏览 • 1回复 待解决
多个UIAbility多个进程吗
3095浏览 • 1回复 待解决
HarmonyOS 时任务启动失败9800005
690浏览 • 1回复 待解决
时任务后台运行,保证应用不被挂起
1665浏览 • 1回复 待解决
一个页面怎么实现多个AbilitySlice?
15081浏览 • 5回复 待解决