This module provides basic APIs for manipulating Picture in Picture (PiP). For example, you can use the APIs to check whether the current device supports the PiP feature and create a PiP controller to start or stop a PiP window. In this way, users can continue watching videos in a small window while performing other operations, improving multitasking efficiency. It is applicable to video playback, video calls, and video conferences.
The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version.
For the system capability SystemCapability.Window.SessionManager, use canIUse() to check whether the device supports this system capability and the corresponding APIs.
isPiPEnabled(): boolean
Checks whether the current device supports the PiP feature.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Return value
| Type | Description |
|---|---|
| boolean | Check result for whether the PiP feature is supported. true if supported, false otherwise. |
Example
let enable: boolean = PiPWindow.isPiPEnabled(); // Check whether the PiP window is supported.
console.info('isPiPEnabled:' + enable); create(config: PiPConfiguration): Promise<PiPController>
Creates a PiP controller. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| config | PiPConfiguration | Yes | Options for creating the PiP controller. This parameter cannot be empty, and context and componentController that are used to construct this parameter cannot be empty. When constructing this parameter, templateType (if specified) must be a value defined in PiPTemplateType, and controlGroups (if specified) must match the value of templateType. For details, see PiPControlGroup. |
Return value
| Type | Description |
|---|---|
| Promise<PiPController> | Promise used to return the PiP controller. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Params error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
| 801 | Capability not supported. Failed to call the API due to limited device capabilities. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { BuilderNode, FrameNode, NodeController, UIContext } from '@kit.ArkUI';
class Params {
text: string = '';
constructor(text: string) {
this.text = text;
}
}
// You can use the @Builder decorator to construct layouts.
@Builder
function buildText(params: Params) {
Column() {
Text(params.text)
.fontSize(20)
.fontColor(Color.Red)
}
.width('100%') // The PiP window is displayed at full size in the width direction.
.height('100%') // The PiP window is displayed at full size in the height direction.
}
// You can extend NodeController to customize the UI controller.
class TextNodeController extends NodeController {
private message: string;
private textNode: BuilderNode<[Params]> | null = null;
constructor(message: string) {
super();
this.message = message;
}
// Use BuilderNode to load the custom layouts.
makeNode(context: UIContext): FrameNode | null {
this.textNode = new BuilderNode(context);
this.textNode.build(wrapBuilder<[Params]>(buildText), new Params(this.message));
return this.textNode.getFrameNode();
}
// You can customize this method to update layouts.
update(message: string) {
console.info(`update message: ${message}`);
if (this.textNode !== null) {
this.textNode.update(new Params(message));
}
}
}
@Entry
@Component
struct Index {
private message: string = 'createPiP';
private pipController: PiPWindow.PiPController | undefined = undefined;
private mXComponentController: XComponentController = new XComponentController(); // Use the mXComponentController to initialize the XComponent: XComponent( {id: 'video', type: 'surface', controller: mXComponentController} ). This ensures that the XComponent content can be migrated to the PiP window.
private nodeController: TextNodeController = new TextNodeController('this is custom UI');
private navId: string = "page_1"; // The navigation ID of the current page is page_1. For details, see the definition of PiPConfiguration. The navigation name is customized.
private contentWidth: number = 800; // The content width is 800 px.
private contentHeight: number = 600; // The content height is 600 px.
private pageId: number = this.getUniqueId(); // Obtain the ID of the current page.
private para: Record<string, number> = { 'PropA': 47 };
private localStorage: LocalStorage = new LocalStorage(this.para);
private res: boolean = this.localStorage.setOrCreate('PropB', 121);
private defaultWindowSizeType: number = 1; // Set the window to be a small window when first pulled up in PiP.
private cornerAdsorptionEnabled: boolean = true;
private config: PiPWindow.PiPConfiguration = {
context: this.getUIContext().getHostContext() as Context,
componentController: this.mXComponentController,
navigationId: this.navId,
handleId: this.pageId,
templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
contentWidth: this.contentWidth,
contentHeight: this.contentHeight,
controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
customUIController: this.nodeController, // Optional. Set this parameter if you want to display the custom UI at the top of the PiP window.
localStorage: this.localStorage, // Optional. Set this parameter if you want to track the main window instance.
defaultWindowSizeType: this.defaultWindowSizeType, // Optional. If you need to configure the default window size upon launch, set this parameter.
cornerAdsorptionEnabled: this.cornerAdsorptionEnabled, // Optional. The default value is true. If you do not want the PiP window to automatically snap to screen corners, set this parameter to false.
};
createPiP() {
let promise: Promise<PiPWindow.PiPController> = PiPWindow.create(this.config); // Create a PiP controller.
promise.then((data: PiPWindow.PiPController) => {
this.pipController = data;
console.info(`Succeeded in creating pip controller. Data:${data}`);
}).catch((err: BusinessError) => {
console.error(`Failed to create pip controller. Cause:${err.code}, message:${err.message}`);
});
}
// This is for function testing only. In actual development, you should design components according to the service requirements.
build() {
RelativeContainer() {
Button(this.message)
.onClick(() => {
this.createPiP();
})
}
}
} create(config: PiPConfiguration, contentNode: typeNode.XComponent): Promise<PiPController>
Creates a PiP controller. This API uses typeNode to add a custom UI node for PiP. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| config | PiPConfiguration | Yes | Options for creating the PiP controller. This parameter cannot be empty, and context and componentController that are used to construct this parameter cannot be empty. When constructing this parameter, templateType (if specified) must be a value defined in PiPTemplateType, and controlGroups (if specified) must match the value of templateType. For details, see PiPControlGroup. |
| contentNode | typeNode.XComponent | Yes | Content to be rendered in the PiP window. The parameter value cannot be empty. |
Return value
| Type | Description |
|---|---|
| Promise<PiPController> | Promise used to return the PiP controller. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Params error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
| 801 | Capability not supported. Failed to call the API due to limited device capabilities. |
Example
import { BusinessError } from '@kit.BasicServicesKit';
import { PiPWindow, typeNode, UIContext } from '@kit.ArkUI';
@Entry
@Component
struct Index {
private message = 'createPiP'
private pipController: PiPWindow.PiPController | undefined = undefined;
private xComponentController: XComponentController = new XComponentController();
private context: UIContext | undefined = this.getUIContext(); // You can pass UIContext or use this.getUIContext() in the layout to assign a valid value to context.
private contentWidth: number = 800; // The content width is 800 px.
private contentHeight: number = 600; // The content height is 600 px.
private config: PiPWindow.PiPConfiguration = {
context: this.getUIContext().getHostContext() as Context,
componentController: this.xComponentController,
templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
contentWidth: this.contentWidth,
contentHeight: this.contentHeight,
};
private options: XComponentOptions = {
type: XComponentType.SURFACE,
controller: this.xComponentController
}
private xComponent = typeNode.createNode(this.context, 'XComponent', this.options); // Create an XComponent node to render the PiP content.
createPiP() {
let promise: Promise<PiPWindow.PiPController> = PiPWindow.create(this.config, this.xComponent); // Use typeNode to create a PiP controller.
promise.then((data: PiPWindow.PiPController) => {
this.pipController = data;
console.info(`Succeeded in creating pip controller. Data:${data}`);
}).catch((err: BusinessError) => {
console.error(`Failed to create pip controller. Cause:${err.code}, message:${err.message}`);
});
}
// This is for function testing only. In actual development, you should design components according to the service requirements.
build() {
RelativeContainer() {
Button(this.message)
.onClick(() => {
this.createPiP();
})
}
}
} Defines the parameters for creating a PiP controller.
System capability: SystemCapability.Window.SessionManager
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| context | BaseContext | No | No | Context environment. Atomic service API: This API can be used in atomic services since API version 12. |
| componentController | XComponentController | No | No | Original XComponent controller. Atomic service API: This API can be used in atomic services since API version 12. |
| navigationId | string | No | Yes | ID of the Navigation component. If no value is passed, the page does not need to be cached. 1. When the UIAbility (application component) uses Navigation to manage pages, set the ID of the Navigation component for the PiP controller. This ensures that the original page can be restored from the PiP window. 2. When the UIAbility uses Router to manage pages, you do not need to set the ID of the Navigation component for the PiP controller. 3. If the UIAbility has only one page, you do not need to set the navigation ID. The original page can be restored from the PiP window. Atomic service API: This API can be used in atomic services since API version 12. |
| handleId22+ | number | No | Yes | ID of the subpage under the Navigation component. After the full-screen window button is touched, the specified page is restored. This parameter applies only to the scenario where the UIAbility (application component) uses Navigation to manage pages. You can set this parameter to the ID of a subpage under Navigation. The default value is -1, indicating that the topmost page in the Navigation stack is restored. You are advised to use getUniqueId() to obtain the page ID. When you use page routing provided by Navigation, you are advised to use the system routing table. Otherwise, the page ID obtained by calling getUniqueId() may be incorrect. Atomic service API: This API can be used in atomic services since API version 22. |
| templateType | PiPTemplateType | No | Yes | Template type, which is used to distinguish video playback, video call, video meeting, and live broadcast scenarios. If no value is passed, the video playback template is used by default. Atomic service API: This API can be used in atomic services since API version 12. |
| contentWidth | number | No | Yes | Width of the original content, in px. The value is a positive integer. It is used to determine the aspect ratio of the PiP window. When a PiPController is created using typeNode (that is, the contentNode parameter is passed using PiPWindow.create()), the default value is 1920 if this parameter is not specified. When a PiPController is created without using typeNode (that is, the contentNode parameter is not passed using PiPWindow.create()), the default value is the width of XComponent if this parameter is not specified. Atomic service API: This API can be used in atomic services since API version 12. |
| contentHeight | number | No | Yes | Height of the original content, in px. The value is a positive integer. It is used to determine the aspect ratio of the PiP window. When a PiPController is created using typeNode (that is, the contentNode parameter is passed using PiPWindow.create()), the default value is 1080 if this parameter is not specified. When a PiPController is created without using typeNode (that is, the contentNode parameter is not passed using PiPWindow.create()), the default value is the height of XComponent if this parameter is not specified. Atomic service API: This API can be used in atomic services since API version 12. |
| controlGroups12+ | Array<PiPControlGroup> | No | Yes | A list of optional component groups of the PiP controller. An application can configure whether to display these optional components. If this parameter is not set for the application, the panel displays basic components (such as the play/pause component of the video playback component group). If this parameter is set for the application, a maximum of three components can be selected. If more than three controls are selected, error code 401 is reported by the API. Atomic service API: This API can be used in atomic services since API version 12. |
| customUIController12+ | NodeController | No | Yes | Custom UI controller, which is used to implement the custom UI features on the PiP page. If this parameter is left empty, the custom UI features are not used by default. Atomic service API: This API can be used in atomic services since API version 12. |
| localStorage17+ | LocalStorage | No | Yes | A page-level UI state storage unit. In multi-instance scenarios, it can be used to track the UI state storage object of the main window instance. If no value is passed, you cannot retrieve the main window's UI storage object through the PiP window. Atomic service API: This API can be used in atomic services since API version 17. |
| defaultWindowSizeType19+ | number | No | Yes | Size of the PiP window that the current application starts for the first time. The value range is [0, 2] and the value must be an integer. 0: no size is set. The PiP window is started based on the size before the PiP window of the previous application is closed. 1: small window. 2: large window. If no value is passed, 0 is used. Atomic service API: This API can be used in atomic services since API version 19. |
| cornerAdsorptionEnabled22+ | boolean | No | Yes | Whether the PiP window automatically snaps to screen corners. When this feature is enabled, the screen is divided into four hot zones (top-left, top-right, bottom-left, and bottom-right). When the PiP window is displayed, it appears in the corresponding corner of the screen based on the position where it disappears last time. The user can drag the window freely, and once the user releases the window, it automatically snaps to the screen edge. true: enables corner snapping. false: disables corner snapping. The default value is true. Device behavior differences: This API can be properly called on phones and tablets. If it is called on other device types, it has no effect. Atomic service API: This API can be used in atomic services since API version 22. |
Describes the size of a PiP window.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Window.SessionManager
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| width | number | No | No | Window width, in px. The value must be a positive integer and cannot be greater than the screen width. |
| height | number | No | No | Window height, in px. The value must be a positive integer and cannot be greater than the screen height. |
| scale | number | No | No | Scale factor of the window, representing the display size relative to the width and height. The value is a floating-point number in the range (0.0, 1.0]. The value 1 means that the window matches the specified width and height. |
Describes the PiP window information.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Window.SessionManager
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| windowId | number | No | No | ID of the PiP window, which uniquely identifies the current PiP window instance. |
| size | PiPWindowSize | No | No | Size of the PiP window. |
Enumerates the PiP template types.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Value | Description |
|---|---|---|
| VIDEO_PLAY | 0 | PiP template type for video playback. The system loads the video playback template based on this type. By default, the template contains the play/pause control. |
| VIDEO_CALL | 1 | PiP template type for video calls. The system loads the video call template based on this type. |
| VIDEO_MEETING | 2 | PiP template type for video meetings. The system loads the video meeting template based on this type. |
| VIDEO_LIVE | 3 | PiP template type for livestreaming. The system loads the livestreaming template based on this type. |
Enumerates the PiP states.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Value | Description |
|---|---|---|
| ABOUT_TO_START | 1 | PiP is about to start. |
| STARTED | 2 | PiP is started. |
| ABOUT_TO_STOP | 3 | PiP is about to stop. |
| STOPPED | 4 | PiP is stopped. |
| ABOUT_TO_RESTORE | 5 | The original page is about to restore. |
| ERROR | 6 | An error occurs during the execution of the PiP lifecycle. |
type PiPControlGroup = VideoPlayControlGroup | VideoCallControlGroup | VideoMeetingControlGroup | VideoLiveControlGroup
Describes the optional component groups of the PiP controller. An application can configure whether to display these optional components. This API must match PiPTemplateType when being used. Otherwise, the create API returns error code 401.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Type | Description |
|---|---|
| VideoPlayControlGroup | Video playback component group. |
| VideoCallControlGroup | Video call component group. |
| VideoMeetingControlGroup | Video meeting component group. |
| VideoLiveControlGroup | Live video component group. |
Enumerates the video playback component groups. They are used only when PiPTemplateType is set to VIDEO_PLAY.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Value | Description |
|---|---|---|
| VIDEO_PREVIOUS_NEXT | 101 | Previous/Next component group for video playback. This component group is mutually exclusive with the fast-forward/rewind component group. It cannot be added if the fast-forward/rewind component group is added. |
| FAST_FORWARD_BACKWARD | 102 | Fast-forward/Rewind component group for video playback. This component group is mutually exclusive with the previous/next component group. It cannot be added if the previous/next component group is added. |
Enumerates the video call component groups. They are used only when PiPTemplateType is set to VIDEO_CALL.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Value | Description |
|---|---|---|
| MICROPHONE_SWITCH | 201 | Microphone on/off component group. |
| HANG_UP_BUTTON | 202 | Hang-up component group. |
| CAMERA_SWITCH | 203 | Camera on/off component group. |
| MUTE_SWITCH | 204 | Mute/Unmute component group. |
Enumerates the video meeting component groups. They are used only when PiPTemplateType is set to VIDEO_MEETING.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Value | Description |
|---|---|---|
| HANG_UP_BUTTON | 301 | Hang-up component group. |
| CAMERA_SWITCH | 302 | Camera on/off component group. |
| MUTE_SWITCH | 303 | Mute/Unmute component group. |
| MICROPHONE_SWITCH | 304 | Microphone on/off component group. |
Enumerates the live video component groups. They are used only when PiPTemplateType is set to VIDEO_LIVE.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Value | Description |
|---|---|---|
| VIDEO_PLAY_PAUSE | 401 | Play/Pause component group for live video. |
| MUTE_SWITCH | 402 | Mute/Unmute component group. |
type PiPActionEventType = PiPVideoActionEvent | PiPCallActionEvent | PiPMeetingActionEvent | PiPLiveActionEvent
Enumerates the types of action events of the PiP controller.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Type | Description |
|---|---|
| PiPVideoActionEvent | Action event for components displayed on the video playback controller. |
| PiPCallActionEvent | Action event for components displayed on the video call controller. |
| PiPMeetingActionEvent | Action event for components displayed on the video meeting controller. |
| PiPLiveActionEvent | Action event for components displayed on the live video controller. |
type PiPVideoActionEvent = 'playbackStateChanged' | 'nextVideo' | 'previousVideo' | 'fastForward' | 'fastBackward'
Defines the PiP action event during video playback.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Type | Description |
|---|---|
| 'playbackStateChanged' | The playback status changes. |
| 'nextVideo' | Plays the next video. |
| 'previousVideo' | Plays the previous video. |
| 'fastForward'12+ | Fast forwards the video. This value is supported since API version 12. |
| 'fastBackward'12+ | Rewinds the video. This value is supported since API version 12. |
type PiPCallActionEvent = 'hangUp' | 'micStateChanged' | 'videoStateChanged' | 'voiceStateChanged'
Defines the PiP action event in a video call.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Type | Description |
|---|---|
| 'hangUp' | The video call is hung up. |
| 'micStateChanged' | The microphone is muted or unmuted. |
| 'videoStateChanged' | The camera is turned on or off. |
| 'voiceStateChanged'12+ | The speaker is muted or unmuted. |
type PiPMeetingActionEvent = 'hangUp' | 'voiceStateChanged' | 'videoStateChanged' | 'micStateChanged'
Defines the PiP action event in a video meeting.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Type | Description |
|---|---|
| 'hangUp' | The video meeting is hung up. |
| 'voiceStateChanged' | The speaker is muted or unmuted. |
| 'videoStateChanged' | The camera is turned on or off. |
| 'micStateChanged'12+ | The microphone is muted or unmuted. |
type PiPLiveActionEvent = 'playbackStateChanged' | 'voiceStateChanged'
Defines the PiP action event in a live.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Type | Description |
|---|---|
| 'playbackStateChanged' | The live is played or paused. |
| 'voiceStateChanged'12+ | The speaker is muted or unmuted. |
Enumerates the statuses of components displayed on the PiP controller.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Value | Description |
|---|---|---|
| PLAY | 1 | Playback state. It is used for the VIDEO_PLAY_PAUSE component to indicate that the video is being played. |
| PAUSE | 0 | Paused state. It is used for the VIDEO_PLAY_PAUSE component to indicate that the video is paused. |
| OPEN | 1 | Enabled state. It is used for the MICROPHONE_SWITCH, CAMERA_SWITCH, or MUTE_SWITCH components to indicate that the microphone, camera, or mute feature is enabled. |
| CLOSE | 0 | Disabled state. It is used for the MICROPHONE_SWITCH, CAMERA_SWITCH, or MUTE_SWITCH components to indicate that the microphone, camera, or mute feature is disabled. |
Enumerates the types of components displayed on the PiP controller.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Value | Description |
|---|---|---|
| VIDEO_PLAY_PAUSE | 0 | Play/Pause component. |
| VIDEO_PREVIOUS | 1 | Previous component in video scenarios. |
| VIDEO_NEXT | 2 | Next component in video scenarios. |
| FAST_FORWARD | 3 | Fast-forward component in video scenarios. |
| FAST_BACKWARD | 4 | Rewind component in video scenarios. |
| HANG_UP_BUTTON | 5 | Hang-up component. |
| MICROPHONE_SWITCH | 6 | Microphone on/off component. |
| CAMERA_SWITCH | 7 | Camera on/off component. |
| MUTE_SWITCH | 8 | Mute/Unmute component. |
type ControlPanelActionEventCallback = (event: PiPActionEventType, status?: number) => void
Describes the action event callback of the PiP controller.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| event | PiPActionEventType | Yes | Type of the action event of the PiP controller. The application performs processing based on the action event. For example, if the 'playbackStateChanged' event is triggered, the application starts or stops the video. |
| status | number | No | Current status of a component whose state can be switched. For example, for a microphone component group or camera lens component group that contains the on and off states, the value is 1 when the component is turned on and 0 when the component is turned off. For a mute component group that contains the muted and unmuted states, the value is 1 when the component is unmuted and 0 when the component is muted. For a play/pause component group that contains the played and paused states, the value is 1 when the component is played and 0 when the component is paused. For other components that do not support the switchable state, such as the components for going to the previous/next video, fast-forwarding/rewinding a video, and ending a call, the default value -1 is returned. |
Describes the parameters in the callback of the action event of the PiP controller.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| controlType | PiPControlType | No | No | Callback for the PiP component type. The application performs processing based on the component type. For example, if the video play/pause component is touched, the application starts or stops the video. |
| status | PiPControlStatus | No | Yes | Status of a component that can be switched. For example, for a microphone on/off component group, a camera on/off component group, and a mute/unmute component group, the value PiPControlStatus.OPEN means that the component is enabled and PiPControlStatus.CLOSE means that the component is disabled. For the hang-up component, the default value is -1. |
Implements a PiP controller that starts, stops, or updates a PiP window and registers callbacks.
Before calling any of the following APIs, you must use PiPWindow.create() to create a PiPController instance.
System capability: SystemCapability.Window.SessionManager
startPiP(): Promise<void>
Starts a PiP window. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Window Error Codes.
| ID | Error Message |
|---|---|
| 1300012 | The PiP window state is abnormal. |
| 1300013 | Failed to create the PiP window. |
| 1300014 | PiP internal error. |
| 1300015 | Repeated PiP operation. |
| 1300034 | This operation conflicts with other floating windows. Possible cause: App has already started float view. Applicable versions: 26.0.0+ |
Example
// You can call pipController according to the pipController definition.
let promise : Promise<void> = this.pipController.startPiP(); // Start the PiP window.
promise.then(() => {
console.info(`Succeeded in starting pip.`);
}).catch((err: BusinessError) => {
console.error(`Failed to start pip. Cause:${err.code}, message:${err.message}`);
}); stopPiP(): Promise<void>
Stops a PiP window. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Window Error Codes.
| ID | Error Message |
|---|---|
| 1300011 | Failed to destroy the PiP window. |
| 1300012 | The PiP window state is abnormal. |
| 1300015 | Repeated PiP operation. |
Example
let promise : Promise<void> = this.pipController.stopPiP(); // Stop the PiP window.
promise.then(() => {
console.info(`Succeeded in stopping pip.`);
}).catch((err: BusinessError) => {
console.error(`Failed to stop pip. Cause:${err.code}, message:${err.message}`);
}); setAutoStartEnabled(enable: boolean): void
Sets whether to automatically start the PiP window when the application's main window which can start the PiP window transitions to the background. By default, the PiP window is not automatically started.
When automatic PiP window startup is enabled, if the application's main window is in the multi-window floating window state and is moved to the sidebar on the side, the PiP window will not be automatically started even though the main window has moved to the background.
If the XComponent approach is used to implement PiP and the Navigation component is used for route management, the system caches the top stack information with the specified navigation ID upon the first call of setAutoStartEnabled(true).
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | If the PiP window needs to be automatically started when the application's main window transitions to the background, set this parameter to true. Otherwise, set this parameter to false. If the PiP feature under Settings > System > Multi-window is disabled, the PiP window will not be automatically started when the application's main window transitions to the background even if this parameter is set to true. |
Example
let enable: boolean = true; this.pipController.setAutoStartEnabled(enable); // Set whether to automatically start the PiP window when the application's main window transitions to the background.
updateContentSize(width: number, height: number): void
Updates the media content size when the media content changes.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Device behavior differences: This API can be called properly on phones, tablets, PCs/2-in-1 devices, and TVs. On cars, calling this API does not report an error or take effect.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| width | number | Yes | Width of the media content, in px. The value must be an integer greater than 0. This parameter is used to update the aspect ratio of the PiP window. |
| height | number | Yes | Height of the media content, in px. The value must be an integer greater than 0. This parameter is used to update the aspect ratio of the PiP window. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Params error. Possible causes: The PiPController is not created or destroyed. |
Example
let width: number = 540; // The content width changes to 540 px. let height: number = 960; // The content height changes to 960 px. this.pipController.updateContentSize(width, height); // Update the size of the PiP window content.
updatePiPControlStatus(controlType: PiPControlType, status: PiPControlStatus): void
Updates the PiP controller status.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| controlType | PiPControlType | Yes | Type of the PiP controller. Currently, only the VIDEO_PLAY_PAUSE, MICROPHONE_SWITCH, CAMERA_SWITCH, and MUTE_SWITCH component types are supported. If other component types are passed, they do not take effect and no error is reported. |
| status | PiPControlStatus | Yes | Status of the PiP controller. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Params error. Possible causes: The PiPController is not created or destroyed. |
Example
let controlType: PiPWindow.PiPControlType = PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE; // Play/Pause component displayed on the video playback control panel. let status: PiPWindow.PiPControlStatus = PiPWindow.PiPControlStatus.PLAY; // The Play/Pause component displayed on the video playback control panel is in the playing state. this.pipController.updatePiPControlStatus(controlType, status); // Update the PiP controller status.
updateContentNode(contentNode: typeNode.XComponent): Promise<void>
Updates the PiP node content. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 18.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| contentNode | typeNode.XComponent | Yes | Content to be rendered in the PiP window. The parameter value cannot be empty. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see Universal Error Codes and Window Error Codes.
| ID | Error Message |
|---|---|
| 401 | Params error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed |
| 801 | Capability not supported. Failed to call the API due to limited device capabilities. |
| 1300014 | PiP internal error. |
Example
import { typeNode, UIContext } from '@kit.ArkUI';
let context: UIContext = this.getUIContext(); // Obtain UIContext using this.getUIContext().
try {
let contentNode = typeNode.createNode(context, "XComponent"); // Create an XComponent node to render the PiP window content.
this.pipController.updateContentNode(contentNode); // Update the PiP node content.
} catch (exception) {
console.error(`Failed to update content node. Code: ${exception.code}, message: ${exception.message}`);
} setPiPControlEnabled(controlType: PiPControlType, enabled: boolean): void
Sets the enabled status of the PiP controller.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| controlType | PiPControlType | Yes | Type of the PiP controller. |
| enabled | boolean | Yes | Enabled status of the PiP controller. true if enabled, false otherwise. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Params error. Possible causes: The PiPController is not created or destroyed. |
Example
let controlType: PiPWindow.PiPControlType = PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE; // Play/Pause component displayed on the video playback control panel. let enabled: boolean = false; // The Play/Pause component displayed on the video playback control panel is in the disabled state. this.pipController.setPiPControlEnabled(controlType, enabled); // Set the enabled status of the PiP controller.
getPiPWindowInfo(): Promise<PiPWindowInfo>
Obtains the PIP window information. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Window.SessionManager
Return value
| Type | Description |
|---|---|
| Promise<PiPWindowInfo> | Promise used to return the information about the current PIP window. |
Error codes
For details about the error codes, see Universal Error Codes and Window Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. Failed to call the API due to limited device capabilities. |
| 1300014 | PiP internal error. |
Example
let pipWindowInfo: PiPWindow.PiPWindowInfo | undefined = undefined;
try {
// Obtain the PiP window information.
let promise : Promise<PiPWindow.PiPWindowInfo> = this.pipController.getPiPWindowInfo();
promise.then((data) => {
// Save the obtained PiP window information.
pipWindowInfo = data;
console.info('Success in get pip window info. Info: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error(`Failed to get pip window info. Code: ${err.code}, message: ${err.message}`);
});
} catch (exception) {
console.error(`Failed to get pip window info. Code: ${exception.code}, message: ${exception.message}`);
} getPiPSettingSwitch(): Promise<boolean>
Obtains the status of the auto-start PiP switch in Settings. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.Window.SessionManager
Device behavior differences: This API can be properly called on phones and tablets. If it is called on other device types, error code 801 is returned.
Return value
| Type | Description |
|---|---|
| Promise<boolean> | Promise used to return the auto-start PiP switch status. true if enabled, false otherwise. |
Error codes
For details about the error codes, see Universal Error Codes and Window Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. Failed to call the API due to limited device capabilities. |
| 1300014 | PiP internal error. |
Example
let pipSwitchStatus: boolean | undefined = undefined;
try {
// Obtain the status of the switch for automatically starting the PiP window.
let promise : Promise<boolean> = this.pipController.getPiPSettingSwitch();
promise.then((data) => {
// Save the obtained switch status.
pipSwitchStatus = data;
console.info('Succeeded in getting pip switch status. switchStatus: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error(`Failed to get pip switch status. Code: ${err.code}, message: ${err.message}`);
});
} catch (exception) {
console.error(`Failed to get pip switch status. Code: ${exception.code}, message: ${exception.message}`);
} isPiPActive(): Promise<boolean>
Obtains the active status of the PiP window. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.Window.SessionManager
Return value
| Type | Description |
|---|---|
| Promise<boolean> | Promise used to return the active status of the PiP window. true is returned if the PiP window is visible, and false is returned if the PiP window is invisible (hidden in the sidebar). If this API is called when the PiP lifecycle is not STARTED, false is always returned. |
Error codes
For details about the error codes, see Window Error Codes.
| ID | Error Message |
|---|---|
| 1300014 | PiP internal error. |
Example
let pipActiveStatus: boolean | undefined = undefined;
try {
// Obtain the active status of the PiP window.
let promise : Promise<boolean> | undefined = this.pipController?.isPiPActive();
promise?.then((data) => {
// Save the obtained active status of the PiP window.
pipActiveStatus = data;
console.info('Succeeded in getting pip active status. activeStatus: ' + JSON.stringify(data));
}).catch((err: BusinessError) => {
console.error(`Failed to get pip active status. Code: ${err.code}, message: ${err.message}`);
});
} catch (exception) {
console.error(`Failed to get pip active status. Code: ${exception.code}, message: ${exception.message}`);
} on(type: 'stateChange', callback: (state: PiPState, reason: string) => void): void
Subscribes to PiP state events. To avoid potential memory leaks, you are advised to stop listening when it is no longer needed.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'stateChange', indicating that the PiP state changes. |
| callback | function | Yes | Callback used to return the result, which includes the following information: - state: PiPState, indicating the new PiP state. - reason: a string indicating the reason for the state change. Before HarmonyOS 6.1.0, the value of reason is always 0, which can be ignored. Since HarmonyOS 6.1.0, reason indicates the reason for switching the current lifecycle. The options are as follows: "requestStart": The application calls the startPiP API. "autoStart": The application is automatically started in PiP mode when it is switched to the background. "requestDelete": The application calls the stopPiP API. "panelActionDelete": The user taps the close button in the PiP window. "dragDelete": The user drags the PiP window to delete. "panelActionRestore": The user taps the restore button in the PiP window (or taps the PiP window if there is no restore button) to restore the PiP window. "other": Other reasons, such as the current window or application's main window being closed due to the startup of a new PiP window. |
Example
// Subscribe to PiP state events.
this.pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
let curState: string = '';
switch (state) {
case PiPWindow.PiPState.ABOUT_TO_START:
curState = 'ABOUT_TO_START';
break;
case PiPWindow.PiPState.STARTED:
curState = 'STARTED';
break;
case PiPWindow.PiPState.ABOUT_TO_STOP:
curState = 'ABOUT_TO_STOP';
break;
case PiPWindow.PiPState.STOPPED:
curState = 'STOPPED';
break;
case PiPWindow.PiPState.ABOUT_TO_RESTORE:
curState = 'ABOUT_TO_RESTORE';
break;
case PiPWindow.PiPState.ERROR:
curState = 'ERROR';
break;
default:
break;
}
console.info('stateChange:' + curState + ' reason:' + reason);
}); off(type: 'stateChange'): void
Unsubscribes from PiP state events.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'stateChange', indicating that the PiP state changes. |
Example
// Unsubscribe from PiP state events.
this.pipController.off('stateChange'); on(type: 'controlPanelActionEvent', callback: ControlPanelActionEventCallback): void
Subscribes to PiP controller action events. To avoid potential memory leaks, you are advised to stop listening when it is no longer needed. The on('controlEvent') API is preferred.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'controlPanelActionEvent', indicating the action event of the PiP controller. |
| callback | ControlPanelActionEventCallback | Yes | Action event callback of the PiP controller. |
Example
// Subscribe to PiP controller action events.
this.pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
switch (event) {
case 'playbackStateChanged':
if (status === 0) {
// Stop the video.
} else if (status === 1) {
// Play the video.
}
break;
case 'nextVideo':
// Switch to the next video.
break;
case 'previousVideo':
// Switch to the previous video.
break;
case 'fastForward':
// Fast forward the video.
break;
case 'fastBackward':
// Rewind the video.
break;
default:
break;
}
console.info('registerActionEventCallback, event:' + event);
}); on(type: 'controlEvent', callback: Callback<ControlEventParam>): void
Subscribes to PiP controller action events. To avoid potential memory leaks, you are advised to stop listening when it is no longer needed.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'controlEvent', indicating the action event of the PiP controller. |
| callback | Callback<ControlEventParam> | Yes | Action event callback of the PiP controller. |
Example
// Subscribe to PiP controller action events.
this.pipController.on('controlEvent', (control) => {
switch (control.controlType) {
case PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE:
if (control.status === PiPWindow.PiPControlStatus.PAUSE) {
// Stop the video.
} else if (control.status === PiPWindow.PiPControlStatus.PLAY) {
// Play the video.
}
break;
case PiPWindow.PiPControlType.VIDEO_NEXT:
// Switch to the next video.
break;
case PiPWindow.PiPControlType.VIDEO_PREVIOUS:
// Switch to the previous video.
break;
case PiPWindow.PiPControlType.FAST_FORWARD:
// Fast forward the video.
break;
case PiPWindow.PiPControlType.FAST_BACKWARD:
// Rewind the video.
break;
default:
break;
}
console.info('registerControlEventCallback, controlType:' + control.controlType + ', status' + control.status);
}); off(type: 'controlPanelActionEvent'): void
Unsubscribes from PiP controller action events. The off('controlEvent') API is preferred.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'controlPanelActionEvent', indicating the action event of the PiP controller. |
Example
// Unsubscribe from PiP controller action events.
this.pipController.off('controlPanelActionEvent'); off(type: 'controlEvent', callback?: Callback<ControlEventParam>): void
Unsubscribes from PiP controller action events.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'controlEvent', indicating the action event of the PiP controller. |
| callback | Callback<ControlEventParam> | No | Describes the action event callback of the PiP controller. If no value is passed in, all subscriptions to the specified event are canceled. |
Example
let callbackFunc = (event: PiPWindow.ControlEventParam) => {
console.info(`receive control event: ${event.controlType}, ${event.status}`);
}
// Unsubscribe from PiP controller action events.
this.pipController.off('controlEvent', callbackFunc); on(type: 'pipWindowSizeChange', callback: Callback<PiPWindowSize>): void
Subscribes to PiP window size change events. To avoid potential memory leaks, you are advised to stop listening when it is no longer needed.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'pipWindowSizeChange', indicating that the PiP window size changes. |
| callback | Callback<PiPWindowSize> | Yes | Callback used to return the size of the current PiP window. |
Error codes
For details about the error codes, see Universal Error Codes and Window Error Codes.
| ID | Error Message |
|---|---|
| 401 | Params error. Possible causes: Callback is already registered. |
| 801 | Capability not supported. Failed to call the API due to limited device capabilities. |
| 1300014 | PiP internal error. |
Example
try {
// Subscribe to PiP window size change events.
this.pipController.on('pipWindowSizeChange', (size: PiPWindow.PiPWindowSize) => {
console.info('Succeeded in enabling the listener for pip window size changes. size: ' + JSON.stringify(size));
});
} catch (exception) {
console.error(`Failed to enable the listener for pip window size changes. Code: ${exception.code}, message: ${exception.message}`);
} off(type: 'pipWindowSizeChange', callback?: Callback<PiPWindowSize>): void
Unsubscribes from the PiP window size change event.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'pipWindowSizeChange', indicating that the PiP window size changes. |
| callback | Callback<PiPWindowSize> | No | Callback used to return the size of the current PiP window. If a value is passed in, the corresponding subscription is canceled. If no value is passed in, all subscriptions to the specified event are canceled. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Params error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
| 801 | Capability not supported. Failed to call the API due to limited device capabilities. |
Example
const callback = (size: PiPWindow.PiPWindowSize) => {
// ...
}
try {
// Enable listening through the on API.
this.pipController.on('pipWindowSizeChange', callback);
} catch (exception) {
console.error(`Failed to enable the listener for pip window size changes. Code: ${exception.code}, message: ${exception.message}`);
}
try {
// Disable the listening of a specified callback.
this.pipController.off('pipWindowSizeChange', callback);
// Unregister all the callbacks that have been registered through on().
this.pipController.off('pipWindowSizeChange');
} catch (exception) {
console.error(`Failed to disable the listener for pip window size changes. Code: ${exception.code}, message: ${exception.message}`);
} on(type: 'activeStatusChange', callback: Callback<boolean>): void
Subscribes to PiP window active status change events. To avoid potential memory leaks, you are advised to stop listening when it is no longer needed.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'activeStatusChange', indicating that the PiP window active status changes. |
| callback | Callback<boolean> | Yes | Callback used to return the active status of the PiP window. true is returned if the PiP window is visible, and false is returned if the PiP window is invisible (hidden in the sidebar). |
Example
let callback = (activeStatus: boolean) => {
console.info(`pip window is visible: ${activeStatus}`);
}
// Subscribe to PiP window active status change events.
this.pipController.on('activeStatusChange', callback); off(type: 'activeStatusChange', callback?: Callback<boolean>): void
Unsubscribes from PiP window active status change events.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.Window.SessionManager
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. The value is fixed at 'activeStatusChange', indicating that the PiP window active status changes. |
| callback | Callback<boolean> | No | Callback used to return the active status of the PiP window. true is returned if the PiP window is visible, and false is returned if the PiP window is invisible (hidden in the sidebar). If no value is passed in, all subscriptions to the specified event are canceled. |
Example
let callback = (activeStatus: boolean) => {
console.info(`pip window is visible: ${activeStatus}`);
}
// Unsubscribe from PiP window active status change events.
this.pipController.off('activeStatusChange', callback);