HarmonyOS 鸿蒙Next音乐类应用如何实现同时后台播放和下载?

发布于 1周前 作者 nodeper 来自 鸿蒙OS

HarmonyOS 鸿蒙Next音乐类应用如何实现同时后台播放和下载?

长时任务好像同时只能申请一个,这样播放和下载会冲突。希望能给出完整的代码样例。

2 回复

在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")
    }
    ;
  }
}

HarmonyOS 鸿蒙Next音乐类应用实现同时后台播放和下载,需要开发者遵循以下步骤:

后台播放实现

  1. 创建AVPlayer实例对象用于音频播放,并加载音频资源。
  2. 创建AVSession并激活,确保音频能够通过播控中心进行控制。
  3. 申请ohos.permission.KEEP_BACKGROUND_RUNNING权限,并在module.json5中进行相应配置。
  4. 使用WantAgent模块申请长时任务,避免应用进入挂起状态。

后台下载实现

  1. 使用后台任务管理(BackgroundTasks Kit)能力,申请对应的长时任务。
  2. 在后台任务中处理下载逻辑,确保下载过程在应用切换到后台后仍能继续。

开发者需注意,同时后台播放和下载会占用系统资源,应合理优化代码和资源管理,避免影响用户体验和系统稳定性。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部