API Reference

更新时间:
复制 MD 格式

This topic describes the main AliPlayerKit APIs. It covers core APIs, the slot system, video sources, player interfaces, state storage, the event system, the logging system, preload interfaces, lifecycle policies, and the strategy system.

Note

AliPlayerKit provides complete code comments for all core APIs—including classes and methods. In IDEs such as Android Studio, you can view these comments using hover tips or Quick Documentation features to improve development efficiency. These comments also make the APIs more accessible to AI programming tools, helping them better understand API semantics.

Core APIs

AliPlayerKit (Global Interface)

The AliPlayerKit class provides global configuration and initialization. It is the only global entry point for the entire player framework.

Initialization methods

Method

Parameter

Return value

Description

init(Context)

context: application context

void

Initialize global settings. Call this method in Application.onCreate().

Status Query

Method

Parameter

Return value

Description

isInitialized()

-

boolean

Check whether initialization is complete.

getContext()

-

Context

Get the application context.

getPlayerKitVersion()

-

String

Get the Kit version number.

getSdkVersion()

-

String

Get the underlying SDK version number.

getDeviceId()

-

String

Get the device ID.

Configuration methods

Method

Parameter

Return value

Description

setDebugModeEnabled(boolean)

enable: Specifies whether the feature is enabled.

void

Enable or disable debug mode.

isDebugModeEnabled()

-

boolean

Check whether debug mode is enabled.

setLogPanelEnabled(boolean)

enable: set to true to enable

void

Show or hide the log panel.

isLogPanelEnabled()

-

boolean

Check whether the log panel is enabled.

setDisableScreenshot(boolean)

disable: Specifies whether the feature is disabled.

void

Enable or disable screenshots.

isDisableScreenshot()

-

boolean

Check whether screenshots are disabled.

setPlayerViewType(PlayerViewType)

viewType: view type

void

Set the player view type.

getPlayerViewType()

-

PlayerViewType

Get the current player view type.

Cache management

Method

Parameter

Return value

Description

clearCaches()

-

void

Clear player caches.

Global APIs

Method

Parameter

Return value

Description

getLogger()

-

IPlayerLogger

Get the global logger instance.

getPreloader()

-

IPlayerPreloader

Get the global preloader instance.

setLogger(IPlayerLogger)

logger: logger instance

void

Set a custom logger implementation.

setPreloader(IPlayerPreloader)

preloader: preloader instance

void

Set a custom preloader implementation.

AliPlayerView (View Component)

The AliPlayerView class is the core player view component. It handles UI rendering and slot management. As the View layer in the MVC architecture, it renders the player UI and manages UI components.

Controller binding

Method

Parameter

Return value

Description

attach(AliPlayerController, AliPlayerModel)

controller, model

void

Bind the controller and data using the default UI.

attach(AliPlayerController, AliPlayerModel, SlotRegistry)

controller, model, registry

void

Bind the controller and data using a custom UI.

detach()

-

void

Unbind and release resources.

Lifecycle

Method

Parameter

Return value

Description

bindLifecycle(LifecycleOwner)

lifecycleOwner

boolean

Bind the lifecycle.

Other methods

Method

Parameter

Return value

Description

onBackPressed()

-

boolean

Handle the back button press. Return true if handled.

getSlotManager()

-

ISlotManager

Get the slot manager.

AliPlayerController (Controller)

The AliPlayerController class controls playback logic and state management. As the Controller layer in the MVC architecture, it coordinates interactions between the View and Model layers.

Constructors

Method

Parameter

Description

AliPlayerController(Context)

context: application context

Create a controller using the default lifecycle policy.

AliPlayerController(Context, IPlayerLifecycleStrategy)

context, lifecycleStrategy

Create a controller using a custom lifecycle policy.

Configuration and initialization

Method

Parameter

Return value

Description

configure(AliPlayerModel)

model: playback data

void

Configure playback data.

getModel()

-

AliPlayerModel

Get the current playback data configuration.

getPlayer()

-

IMediaPlayer

Get the player instance.

destroy()

-

void

Destroy the player.

State management

Method

Parameter

Return value

Description

getStateStore()

-

IPlayerStateStore

Get the player state store.

getStrategyManager()

-

StrategyManager

Get the strategy manager.

View settings

Method

Parameter

Return value

Description

setDisplayView(AliDisplayView)

displayView

void

Set the display view.

setSurface(Surface)

surface

void

Set the Surface.

surfaceChanged()

-

void

Notify that the Surface has changed.

Lifecycle methods

Method

Parameter

Return value

Description

onResume()

-

void

Manually resume playback outside a LifecycleOwner context.

onPause()

-

void

Manually pause playback outside a LifecycleOwner context.

AliPlayerModel (Data Model)

The AliPlayerModel class encapsulates playback configuration data. As the Model layer in the MVC architecture, it holds all configuration data required by the player. Use the Builder pattern to create instances.

Builder methods

Method

Parameter

Description

videoSource(VideoSource)

video source object

Set the video source. Required.

sceneType(int)

scene type

Set the playback scene type.

coverUrl(String)

thumbnail URL

Set the thumbnail URL.

videoTitle(String)

video title

Set the video title.

autoPlay(boolean)

Autoplay

Set whether to enable autoplay.

traceId(String)

trace ID

Set the trace ID.

startTime(long)

start position

Set the start position in milliseconds.

isHardWareDecode(boolean)

Is hardware decoding enabled?

Set whether to enable hardware decoding.

allowedScreenSleep(boolean)

Is hibernation supported?

Set whether to allow screen sleep.

build()

-

Build an AliPlayerModel instance.

Property accessors

Method

Return value

Description

getVideoSource()

VideoSource

Get the video source object.

getSceneType()

int

Get the playback scene type.

getCoverUrl()

String

Get the thumbnail URL.

getVideoTitle()

String

Get the video title.

isAutoPlay()

boolean

Get whether autoplay is enabled.

getTraceId()

String

Get the trace ID.

getStartTime()

long

Get the start position.

isHardWareDecode()

boolean

Get whether hardware decoding is enabled.

isAllowedScreenSleep()

boolean

Get whether screen sleep is allowed.

Slot System

The slot system is AliPlayerKit’s UI extension mechanism. It lets you customize individual UI components of the player.

ISlotManager (Slot Management Interface)

The ISlotManager interface provides slot management capabilities. Retrieve it from AliPlayerView.getSlotManager().

  • Method

    Parameter

    Return value

    Description

    rebuildSlots()

    -

    void

    Rebuild all slots after modifying the SlotRegistry.

    getSlotView(SlotType)

    slotType: slot type

    View

    Get the slot view for the specified type.

    bindData(AliPlayerModel)

    model: playback data

    void

    Bind playback data to the slot system.

    unbindData()

    -

    void

    Unbind playback data.

    updateSceneType(int)

    sceneType: scene type

    void

    Update the scene type and rebuild slots.

SlotRegistry (Slot Registry)

The SlotRegistry class registers custom slots. Pass it into AliPlayerView.attach().

Registration methods

Method

Parameter

Description

register(SlotType, SlotBuilder)

type, builder

Register a slot builder.

register(SlotType, Class<? extends View>)

type, slotClass

Register a slot class. The class is created using reflection.

register(SlotType, int)

type, layoutId

Register a layout resource as a slot.

Management methods

Method

Return value

Description

unregister(SlotType)

SlotBuilder

Unregister a slot builder.

isRegistered(SlotType)

boolean

You can check if it is registered.

clear()

void

Clear all registrations.

size()

int

Get the number of registered slots.

ISlot (Slot Interface)

Custom slots must implement the ISlot interface to define their lifecycle.

Method

Description

onAttach(SlotHost)

Called when the slot is attached to its host.

onDetach()

Called when the slot is detached from its host.

onBindData(AliPlayerModel)

Called when playback data is bound.

onUnbindData()

Called when playback data is unbound.

Note

We recommend extending BaseSlot to implement custom slots. The framework automatically manages event subscription lifecycles.

SlotType (Slot Types)

Constant

Description

SlotType.PLAYER_SURFACE

Player surface view slot: the core view used to render video content.

SlotType.FULLSCREEN

Fullscreen management slot: manages fullscreen toggle logic.

SlotType.GESTURE_CONTROL

Gesture control slot: handles gesture controls such as tap, double-tap, long press, and drag.

SlotType.LANDSCAPE_HINT

Landscape viewing hint slot: prompts users to watch landscape videos in fullscreen.

SlotType.COVER

Cover image slot: displays the video cover image.

SlotType.CENTER_DISPLAY

Center display slot: displays status information in the center area, such as playback speed, brightness, and volume.

SlotType.PLAY_STATE

Playback state slot: displays playback state information such as error messages and loading indicators.

SlotType.LOG_PANEL

Log panel slot: displays player log information for debugging.

SlotType.TOP_BAR

Top control bar slot: displays the back button, title, and settings.

SlotType.BOTTOM_BAR

Bottom control bar slot: displays playback controls, the progress bar, and the fullscreen toggle.

SlotType.SETTING_MENU

Settings menu slot: displays the settings menu, including playback speed, definition, mirroring, and rotation options.

SceneType (Playback Scenes)

Constant

Value

Description

SceneType.VOD

0

Video-on-demand scene: standard video playback with full playback controls.

SceneType.LIVE

1

Live streaming scene: real-time stream playback without seeking or speed control.

SceneType.VIDEO_LIST

2

Video list scene: player used in a video list. Disables vertical gestures.

SceneType.RESTRICTED

3

Restricted playback scene: limits timeline operations. Used in education and training.

SceneType.MINIMAL

4

Minimal playback scene: shows only the playback view with no UI elements.

PlayerViewType (Player View Types)

Constant

Description

PlayerViewType.DISPLAY_VIEW

AliDisplayView (recommended): official display view component with better compatibility and performance.

PlayerViewType.SURFACE_VIEW

SurfaceView: uses a separate rendering thread but does not support animations.

PlayerViewType.TEXTURE_VIEW

TextureView: supports animations and transformations. Best for scenes requiring view animations.

Video Sources

VideoSourceFactory (Video Source Factory)

Method

Parameter

Return value

Description

VideoSourceFactory.createVidAuthSource(String, String)

vid, playAuth

VideoSource

Create a VidAuth video source (recommended).

VideoSourceFactory.createVidStsSource(String, String, String, String, String)

vid, accessKeyId, accessKeySecret, securityToken, region

VideoSource

Create a VidSts video source.

VideoSourceFactory.createUrlSource(String)

url: video URL

VideoSource

Create a URL video source.

Note

In production environments, use the VidAuth method. It offers higher security and integrates with Alibaba Cloud VOD services for enhanced playback capabilities. For more information, see Multiple video source support.

VideoSource (Video Source)

Method

Return value

Description

isValid()

boolean

Check whether the video source is valid.

getType()

int

Get the video source type.

getSourceId()

String

Get the video source ID.

Player Interfaces

IMediaPlayer (Media Player Interface)

The IMediaPlayer interface defines core player operations. Retrieve it from AliPlayerController.getPlayer().

Playback controls

Method

Parameter

Description

start()

-

Start playback.

pause()

-

Pause playback.

toggle()

-

Toggle between playing and pausing.

stop()

-

Stop playback.

replay()

-

Replay the video.

seekTo(long)

positionMs

Seek to the specified position in milliseconds.

release()

-

Release player resources.

Data sources

Method

Parameter

Description

setDataSource(AliPlayerModel)

model

Set the video data source.

View settings

Method

Parameter

Description

setDisplayView(AliDisplayView)

displayView

Set the display view.

setSurface(Surface)

surface

Set the rendering Surface.

surfaceChanged()

-

Notify that the Surface has changed.

Playback settings

Method

Parameter

Description

setSpeed(float)

speed

Set the playback speed (0.3 to 3.0).

setLoop(boolean)

loop

Enable or disable looping.

setMute(boolean)

mute

Mute.

setScaleType(int)

scaleType

Set the rendering fill mode.

setMirrorType(int)

mirrorType

Set the mirroring mode.

setRotation(int)

rotation

Set the rotation angle.

selectTrack(TrackQuality)

trackQuality

Select the video definition.

snapshot()

-

Capture a screenshot.

State queries

Method

Return value

Description

getPlayerId()

String

Get the unique player identifier.

getStateStore()

IPlayerStateStore

Get the state store interface.

ScaleType (Rendering Fill Modes)

Constant

Value

Description

ScaleType.FIT_XY

0

Stretch to fill the view.

ScaleType.FIT_CENTER

1

Fit while preserving aspect ratio (may show black bars).

ScaleType.CENTER_CROP

2

Crop to fill while preserving aspect ratio.

MirrorType (Mirroring Modes)

Constant

Value

Description

MirrorType.NONE

0

No mirroring.

MirrorType.HORIZONTAL

1

Horizontal mirroring.

MirrorType.VERTICAL

2

Vertical mirroring.

Rotation (Rotation Angles)

Constant

Value

Description

Rotation.DEGREE_0

0

0 degrees.

Rotation.DEGREE_90

90

90 degrees.

Rotation.DEGREE_180

180

180 degrees.

Rotation.DEGREE_270

270

270 degrees.

State Storage Interface

IPlayerStateStore (Player State Storage)

The IPlayerStateStore interface provides read-only access to player state. Retrieve it from AliPlayerController.getStateStore() or IMediaPlayer.getStateStore().

Playback state

Method

Return value

Description

getPlayState()

PlayerState

Get the current playback state.

getDuration()

long

Get the total video duration in milliseconds.

getCurrentPosition()

long

Get the current playback position in milliseconds.

getCurrentSpeed()

float

Get the current playback speed.

Video settings

Method

Return value

Description

getVideoSize()

VideoSize

Get the video size (may be null).

getCurrentRotation()

int

Get the current rotation angle.

getCurrentScaleType()

int

Get the current fill mode.

getCurrentMirrorType()

int

Get the current mirroring mode.

Playback settings

Method

Return value

Description

isLoop()

boolean

Check whether looping is enabled.

isMute()

boolean

Check whether audio is muted.

isFullscreen()

boolean

Check whether the player is in fullscreen mode.

Definition

Method

Return value

Description

getTrackQualityList()

List

Get the list of available definitions.

getCurrentTrackIndex()

int

Get the index of the current definition.

PlayerState (Playback States)

Constant

Description

PlayerState.UNKNOWN

Unknown state: the player state is unknown or uninitialized.

PlayerState.IDLE

Idle state: the player is created but not yet initialized, or resources are released.

PlayerState.INITIALIZING

Initializing: the player is initializing and preparing to load video resources.

PlayerState.INITIALIZED

Initialized: the player is fully initialized but not yet ready to play.

PlayerState.PREPARING

Preparing: the player is preparing video resources and parsing video information.

PlayerState.PREPARED

Prepared: the player is ready to start playback.

PlayerState.PLAYING

Playing: the player is actively playing video.

PlayerState.PAUSED

Paused: the player is paused.

PlayerState.COMPLETED

Completed: the video playback is finished.

PlayerState.STOPPED

Stopped: the player is stopped.

PlayerState.ERROR

Error: an error occurred during playback.

Event System

PlayerEventBus (Event Bus)

The PlayerEventBus class is the global event bus for publishing and subscribing to player events.

Subscription methods

Method

Parameter

Description

subscribe(Class<T>, EventListener<T>)

eventType, listener

Subscribe to events of the specified type.

unsubscribe(Class<T>, EventListener<T>)

eventType, listener

Unsubscribe from events of the specified type.

unsubscribe(EventListener<?>)

listener

Unsubscribe the listener from all event types.

unsubscribeAll()

-

Clear all subscriptions. Use with caution.

Publishing methods

Method

Parameter

Description

post(PlayerEvent)

event

Publish an event.

Query methods

Method

Return value

Description

getSubscriberCount(Class<?>)

int

Get the number of subscribers for the specified event type.

hasSubscribers(Class<?>)

boolean

Check whether any subscribers exist for the specified event type.

PlayerCommand (Player Commands)

Player commands control player behavior. Publish them using PlayerEventBus.post().

Command class

Parameter

Description

PlayerCommand.Play

playerId

Play command.

PlayerCommand.Pause

playerId

Pause command.

PlayerCommand.Toggle

playerId

Toggle between playing and pausing.

PlayerCommand.Stop

playerId

Stop command.

PlayerCommand.Replay

playerId

Replay command.

PlayerCommand.Seek

playerId, position

Seek command. Position is in milliseconds.

PlayerCommand.SetSpeed

playerId, speed

Set the playback speed (0.3 to 3.0).

PlayerCommand.Snapshot

playerId

Screenshot command.

PlayerCommand.SetLoop

playerId, loop

Set looping.

PlayerCommand.SetMute

playerId, mute

Set mute.

PlayerCommand.SetScaleType

playerId, scaleType

Set the rendering fill mode.

PlayerCommand.SetMirrorType

playerId, mirrorType

Set the mirroring mode.

PlayerCommand.SetRotation

playerId, rotation

Set the rotation angle.

PlayerCommand.SelectTrack

playerId, trackQuality

You can switch resolution.

Usage example

// Post a play command.
PlayerEventBus.getInstance().post(new PlayerCommand.Play(playerId));

// Post a seek command.
PlayerEventBus.getInstance().post(new PlayerCommand.Seek(playerId, 5000));

// Set the playback speed.
PlayerEventBus.getInstance().post(new PlayerCommand.SetSpeed(playerId, 1.5f));     

PlayerEvents (Player Events)

Player state changes are published as events. Subscribe to listen for them.

Event class

Property

Description

PlayerEvents.StateChanged

oldState, newState

Playback state changed.

PlayerEvents.Prepared

duration

Player is prepared.

PlayerEvents.FirstFrameRendered

-

First frame rendered.

PlayerEvents.VideoSizeChanged

width, height

Video size changed.

PlayerEvents.Info

duration, currentPosition, bufferedPosition

Playback information updated.

PlayerEvents.Error

errorCode, errorMsg

Error event.

PlayerEvents.LoadingBegin

-

Loading started.

PlayerEvents.LoadingProgress

percent, netSpeed

Loading progress.

PlayerEvents.LoadingEnd

-

Loading finished.

PlayerEvents.SetSpeedCompleted

speed

Set speed completed.

PlayerEvents.SnapshotCompleted

result, snapshotPath, width, height

Screenshot completed.

PlayerEvents.SetLoopCompleted

loop

Set loop completed.

PlayerEvents.SetMuteCompleted

mute

Set mute completed.

PlayerEvents.SetScaleTypeCompleted

scaleType

Set fill mode completed.

PlayerEvents.SetMirrorTypeCompleted

mirrorType

Set mirroring completed.

PlayerEvents.SetRotationCompleted

rotation

Set rotation completed.

PlayerEvents.TrackQualityListUpdated

trackQualityList

Definition list updated.

PlayerEvents.TrackSelected

trackIndex

Definition selection completed.

Usage example

// Subscribe to a playback event.
PlayerEventBus.getInstance().subscribe(PlayerEvents.Prepared.class, event -> {
    long duration = event.duration;  // Total video duration
});

// Subscribe to an error event.
PlayerEventBus.getInstance().subscribe(PlayerEvents.Error.class, event -> {
    int code = event.errorCode;
    String msg = event.errorMsg;
});         

Logging System

IPlayerLogger (Logging Interface)

The IPlayerLogger interface provides global logging configuration. Retrieve it from AliPlayerKit.getLogger().

Method

Parameter

Return value

Description

enableConsoleLog(boolean)

enable

void

Enable or disable console logging.

isConsoleLogEnabled()

-

boolean

Check whether console logging is enabled.

setLogLevel(int)

level

void

Set the log level.

getLogLevel()

-

int

Get the current log level.

setLogCallback(LoggerCallback)

callback

void

Set the log callback listener.

LogLevel (Log Levels)

Constant

Value

Description

LogLevel.VERBOSE

0

Most detailed level. Logs all debug information.

LogLevel.DEBUG

1

Debug level.

LogLevel.INFO

2

Information level.

LogLevel.WARN

3

Warning level.

LogLevel.ERROR

4

Error level.

LogLevel.NONE

100

Disable all logs.

Preload Interfaces

IPlayerPreloader (Preload Interface)

The IPlayerPreloader interface provides global preload management. Retrieve it from AliPlayerKit.getPreloader().

Method

Parameter

Return value

Description

addTask(PlayerPreloadTask, PreloadCallback)

task, listener

String

Add a preload task and return its ID.

cancelTask(String)

taskId

void

Cancel the specified task.

pauseTask(String)

taskId

void

Pause the specified task.

resumeTask(String)

taskId

void

Resume the specified task.

PreloadCallback (Preload Callback)

Method

Parameter

Description

onCompleted(String, VideoSource)

taskId, source

Preload completed.

onError(String, VideoSource, int, String)

taskId, source, code, message

Preload error.

onCanceled(String, VideoSource)

taskId, source

Preload canceled.

Player Lifecycle Policies

IPlayerLifecycleStrategy (Player Lifecycle Policy Interface)

The IPlayerLifecycleStrategy interface defines how player instances are managed across their lifecycle. It optimizes player instance creation and reuse.

Method

Parameter

Return value

Description

init(IPlayerFactory)

factory

void

Initialize the policy.

acquire(Context, String)

context, uniqueId

IMediaPlayer

Get a player instance.

recycle(IMediaPlayer, String, boolean)

player, uniqueId, force

void

Recycle a player instance.

clear()

-

void

Clear all resources.

preload(Context, int)

context, count

void

Preload player instances.

Built-in policies

Policy class

Description

DefaultLifecycleStrategy

Default policy: create a new instance each time and destroy it immediately after use.

ReusePoolLifecycleStrategy

Reuse pool policy: best for streaming lists of videos.

IdScopedPoolLifecycleStrategy

ID-scoped policy: bind one instance to one ID.

SingletonLifecycleStrategy

Singleton policy: one global instance only.

For more information, see Player lifecycle policies.

Strategy System

StrategyManager (Strategy Manager)

The StrategyManager class manages the lifecycle of all strategies. Retrieve it from AliPlayerController.getStrategyManager().

Method

Parameter

Return value

Description

register(IStrategy)

strategy

void

Register a strategy.

unregister(IStrategy)

strategy

void

Unregister Policy

getStrategy(String)

name

IStrategy

Get a strategy by name.

start(StrategyContext)

context

void

Start all strategies.

stop()

-

void

Stop all strategies.

reset()

-

void

Reset all strategies.

updateContext(StrategyContext)

context

void

Update the context and restart strategies.

destroy()

-

void

Delete Manager

getStrategyCount()

-

int

Get the number of registered strategies.

isStarted()

-

boolean

You can check whether it has started.

IStrategy (Strategy Interface)

Method

Description

getName()

Get the strategy name.

onStart(StrategyContext)

Called when the strategy starts.

onStop()

Called when the strategy stops.

onReset()

Called when the strategy resets.