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

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

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

HarmonyOS
2天前
浏览
收藏 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"
  ]
}
],

在新开的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")
    }
    ;
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
如何申请多个时任务
2132浏览 • 1回复 待解决
HarmonyOS 申请时任务报错9800006 -
40浏览 • 1回复 待解决
什么场景需要创建多个UIAbility
2022浏览 • 1回复 待解决
音视频播放是否需要创建时任务
2047浏览 • 1回复 待解决
多个UIAbility多个进程吗?
2289浏览 • 1回复 待解决
多个UIAbility多个进程吗
2497浏览 • 1回复 待解决
HarmonyOS 时任务启动失败9800005
38浏览 • 1回复 待解决
时任务后台运行,保证应用不被挂起
1190浏览 • 1回复 待解决