Implementing Media Session (Provider) with HarmonyOS

Overview

This sample demonstrates the media session provider functionality using the @ohos.multimedia.avsession API. It enables custom data exchange between a media provider and a media controller.

Note: This sample only shows the provider side. For the complete custom interaction feature, use both the provider and controller samples together.

Preview

Media provider UI preview

Usage

Basic Operations

  1. Open the media provider sample app.
  2. Tap the Play button. The playback status changes and lyrics start updating.
  3. Tap the Pause button. Playback stops and lyrics freeze.
  4. Tap the Previous button to switch to the previous song in the playlist.
  5. Tap the Next button to switch to the next song.

Advanced Operations (with Media Controller)

  1. When you tap Play, Pause, Previous, or Next in this app, the corresponding sesssion state in the media controller updates accordingly.
  2. When you control playback from the media controller, this app reflects the change.
  3. The media controller can access this app's playlist, custom data packets, and lyrics.

Project Structure

entry/src/main/ets/
|---common
|---|---Log.ets                     // Logging utility
|---|---MediaData.ets               // Song metadata
|---|---Utils.ets                   // General utilities
|---feature
|---|---ProviderFeature.ets        // Business logic
|---pages
|---|---Index.ets                  // UI implementation

Implementation Details

  • UI layer is entirely in pages/Index.ets.
  • Variables shared with logic code are linked via @StorageLink. When the logic updates a linked variable, the UI refreshes automatically.
  • Logic classes are instantiated and used in onClick handlers:
import { MediaProvider } from '../feature/MediaProvider';

private mediaProvider: MediaProvider = new MediaProvider();

Button() {
  // Button label
}
.onClick(async () => {
  this.mediaProvider.startPlayback();
})

  • Business logic is encapsulated in feature/ProviderFeature.ets.

App Initialisation

  • Link variables
    Use AppStorage.SetAndLink() to connect logic variables with @StorageLink in the UI. Update or read values via set() and get():
private playbackState: SubscribedAbstractProperty<boolean> = null;

this.playbackState = AppStorage.SetAndLink('IsPlaying', false);
this.playbackState.set(false);

const isPlaying: boolean = this.playbackState.get();

  • Create and activate the media session
    Use createAVSession() to create the session, then activate() to activate it.
    Set the playlist via setAVQueueItems(), the playlist title via setAVQueueTitle(), and the current media metadata via setAVMetadata().
    Listen for controller commands using on() and handle them according.

Runtime Operations

  • Switching songs
    When changing tracks, update the provider’s own state and also call setAVPlaybackState() and setAVMetadata() to synchronise with the media controller.
  • Sending custom data packets
    Use dispatchSessionEvent() and setExtras() to send custom data packets to the controller.

Required Permissions

  1. Long-running task permission ohos.permission.KEEP_BACKGROUND_RUNNING
    To allow the provider to run in the background and respond to commands, declare this permission in the module.json5 of the Ability that needs background execution:
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
      }
    ]
  }
}

After declaring the permission, request a continuous task in the logic code:

async startContinuousTask() {
  let wantAgentInfo = {
    wants: [{
      bundleName: "com.samples.mediaprovider",
      abilityName: "com.samples.mediaprovider.EntryAbility"
    }],
    operationType: WantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
  };
  let want = await WantAgent.getWantAgent(wantAgentInfo);
  await backgroundTaskManager.startBackgroundRunning(
    globalThis.context,
    backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK,
    want
  );
}

Dependencies

This sample only showcases the provider side. For the complete custom interaction, combine it with the media controller sample.

Constraints and Limitations

  1. This sample runs only on standard systems (supported device: RK3568).
  2. It uses the Stage model and requires API version 10 Release (SDK version: API Version 10 Release, image version: 4.0 Release).
  3. Compile and run with DevEco Studio version 4.0 Release or higher.

Download

To download this project separately, execute:

git init
git config core.sparsecheckout true
echo code/BasicFeature/Media/AVSession/MediaProvider > .git/info/sparse-checkout
git remote add origin https://gitee.com/openharmony/applications_app_samples.git
git pull origin master

Tags: HarmonyOS AVSession MediaProvider ArkTS StageModel

Posted on Tue, 19 May 2026 01:48:08 +0000 by ManicMax