“72ba9ab2796d213b247b1e77b2adf0985b86e107”上不存在“git@gitcode.net:badboy_fzk/gpt-vue-fengzk.git”
提交 cecaa207 编写于 作者: G ge-yafang

update docs

Signed-off-by: Nge-yafang <geyafang@huawei.com>
# Ability Development
- [Ability Framework Overview](ability-brief.md)
- FA Model
- [FA Model Overview](fa-brief.md)
- [Page Ability Development](fa-pageability.md)
- [Service Ability Development](fa-serviceability.md)
- [Data Ability Development](fa-dataability.md)
- [FA Widget Development](fa-formability.md)
- [FA Model Overview](fa-brief.md)
- [Page Ability Development](fa-pageability.md)
- [Service Ability Development](fa-serviceability.md)
- [Data Ability Development](fa-dataability.md)
- [FA Widget Development](fa-formability.md)
- Other
- [Ability Assistant Usage](ability-assistant-guidelines.md)
# Ability Framework Overview
An ability is an abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more **Ability** instances.
The ability framework model has two forms. The first form is the FA model, which applies to application development using API 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service and Data abilities. The stage model is introduced since API 9. In the stage model, there are Page abilities and Extension abilities. The Extension ability is further extended to Service Extension, Form Extension, Data Share Extension, and more.
The stage model is designed to make complex application development easier in a distributed environment. The two models have differences in the following aspects:
* Ability type and API usage
![favsstage](figures/favsstage.png)
* Ability lifecycle
![lifecycle](figures/lifecycle.png)
* Application configuration files and application package structure (The differences are reflected in the application packages generated by the IDE.)
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
......@@ -2,9 +2,9 @@
The application development documents provide reference for you to develop applications using the APIs provided by OpenHarmony. The documents provided walk you through how to use JavaScript \(JS\) APIs to develop applications on the standard system.
To get a glimpse of the basic methods for developing applications, see [Basics](quick-start/Readme-EN.md). For details about the API list and references, see [Reference](reference/Readme-EN.md).
To get a glimpse of the basic methods for developing applications, see [Basics](quick-start/start-overview.md). For details about the API list and references, see [Reference](reference/apis/js-apis-featureAbility.md).
To better understand frequently used modules, see the development guidelines for [UI](ui/Readme-EN.md), [Media](media/Readme-EN.md), and [Connectivity](connectivity/Readme-EN.md).
To better understand frequently used modules, see the development guidelines for [Ability](ability/fa-brief.md), [UI](ui/arkui-overview.md), [Media](media/Readme-EN.md), etc.
For details about the principles and basic information of each subsystem, see the README file in **docs/en/readme**.
- [Application Development Overview](application-dev-guide.md)
- Quick Start
- [Directory Structure](quick-start/package-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md)
- Development
- [Ability Development](ability/Readme-EN.md)
- [Ability Framework Overview](ability/ability-brief.md)
- FA Model
- [FA Model Overview](ability/fa-brief.md)
- [Page Ability Development](ability/fa-pageability.md)
- [Service Ability Development](ability/fa-serviceability.md)
- [Data Ability Development](ability/fa-dataability.md)
- [FA Widget Development](ability/fa-formability.md)
- Other
- [Ability Assistant Usage](ability/ability-assistant-guidelines.md)
- [UI](ui/Readme-EN.md)
- [ArkUI Overview](arkui-overview.md)
- JavaScript-based Web-Like Development Paradigm
......@@ -129,6 +129,7 @@
- [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md)
- Basic Functions
- Window Manager
- Window
......@@ -209,10 +210,13 @@
- Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](dfx/hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md)
- Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md)
- API References
- Compent Reference (JavaScript-based Web-like Development Paradigm)
- Components
......
# Work Scheduler Callbacks
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
```
## WorkSchedulerExtensionAbility.onWorkStart
- **System capability**
SystemCapability.ResourceSchedule.WorkScheduler
- **API**
onWorkStart(workInfo: WorkInfo);
- **Description**
Triggered when the Work Scheduler task starts.
- **Example**
```
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
}
}
```
## WorkSchedulerExtensionAbility.onWorkStop
- **System capability**
SystemCapability.ResourceSchedule.WorkScheduler
- **API**
onWorkStop(workInfo: WorkInfo);
- **Description**
Triggered when the Work Scheduler task stops.
- **Example**
```
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStop(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
}
}
```
......@@ -434,18 +434,6 @@ Enumerates the interrupt types.
| INTERRUPT_TYPE_BEGIN | 1 | Audio playback interruption started. |
| INTERRUPT_TYPE_END | 2 | Audio playback interruption ended. |
## InterruptForceType<sup>9+</sup>
Enumerates the interrupt force types.
**System capability:** SystemCapability.Multimedia.Audio.Renderer
| Name | Default Value | Description |
| :-------------- | :------------ | :----------------------------------------- |
| INTERRUPT_FORCE | 0 | Forced action taken by system. |
| INTERRUPT_SHARE | 1 | App can choose to take action or ignore. |
## InterruptHint
Enumerates the interrupt hints.
......@@ -542,20 +530,6 @@ Describes audio capturer configuration options.
| streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Stream information. |
| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | Capturer information. |
## InterruptEvent<sup>9+</sup>
Describes the interrupt event received by the app when playback is interrupted.
**System capability:** SystemCapability.Multimedia.Audio.Renderer
**Parameters:**
| Name | Type | Mandatory | Description |
| :-------- | :-------------------------------------------- | :-------- | :---------------------------------------------------------------- |
| eventType | [InterruptType](#interrupttype) | Yes | Whether the interruption has started or finished. |
| forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the action is taken by system or to be taken by the app. |
| hintType | [InterruptHint](#interrupthint) | Yes | Type of action. |
## AudioInterrupt
The parameters passed in by the audio listener event.
......@@ -2560,52 +2534,6 @@ audioRenderer.getRenderRate().then((renderRate) => {
});
```
### on('interrupt')<sup>9+</sup>
on(type: 'interrupt', callback: Callback\<InterruptEvent>): void
Subscribes to audio interrupt events. This API uses a callback to get interrupt events. The interrupt event is triggered when audio rendering is interrupted.
**System capability:** SystemCapability.Multimedia.Audio.Renderer
**Parameters:**
| Name | Type | Mandatory | Description |
| :------- | :-------------------------------------------- | :-------- | :---------------------------------------------- |
| type | string | Yes | Type of the playback event to subscribe to. |
| callback | Callback<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to listen for interrupt callback. |
**Example:**
```
audioRenderer.on('interrupt', (interruptEvent) => {
if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
console.log('Force paused. Stop writing');
isPlay = false;
break;
case audio.InterruptHint.INTERRUPT_HINT_STOP:
console.log('Force stopped. Stop writing');
isPlay = false;
break;
}
} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_RESUME:
console.log('Resume force paused renderer or ignore');
startRenderer();
break;
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
console.log('Choose to pause or ignore');
pauseRenderer();
break;
}
}
});
```
### on('markReach')<sup>8+</sup>
on(type: 'markReach', frame: number, callback: (position: number) => {}): void
......
# Camera<a name="EN-US_TOPIC_0000001149807881"></a>
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import camera from '@ohos.multimedia.camera';
```
## Required Permissions
```
ohos.permission.CAMERA
```
## getCameraManager(context: Context, callback: AsyncCallback<CameraManager\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets a **CameraManager** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|-------------------------------|-----------|-----------------------------------------------------|
| context | Context | Yes | Application context |
| callback | AsyncCallback<CameraManager\> | Yes | Callback used to return the CameraManager instance |
**Example**
```
camera.getCameraManager(context, (err, cameraManager) => {
if (err) {
console.error('Failed to get the CameraManager instance ${err.message}');
return;
}
console.log('Callback returned with the CameraManager instance');
});
```
## getCameraManager(context: Context): Promise<CameraManager\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets a **CameraManager** instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------|
| context | Context | Yes | Application context |
**Return values**
| Type | Description |
|-------------------------|--------------------------------------------------------|
| Promise<CameraManager\> | Promise used to return the **CameraManager** instance |
**Example**
```
camera.getCameraManager(context).then((cameraManger) => {
console.log('Promise returned with the CameraManager instance.');
})
```
## CameraStatus<a name="section_camera_status"></a>
Enumerates camera status types.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Default Value | Description |
|---------------------------|---------------|--------------------|
| CAMERA_STATUS_APPEAR | 0 | Camera appear |
| CAMERA_STATUS_DISAPPEAR | 1 | Camera disappear |
| CAMERA_STATUS_AVAILABLE | 2 | Camera available |
| CAMERA_STATUS_UNAVAILABLE | 3 | Camera unavailable |
## CameraPosition<a name="section_camera_position"></a>
Enumerates the camera positions.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Default value | Description |
|-----------------------------|---------------|-----------------------|
| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position |
| CAMERA_POSITION_BACK | 1 | Rear camera |
| CAMERA_POSITION_FRONT | 2 | Front camera |
## CameraType<a name="section_camera_type"></a>
Enumerates the camera types.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Default value | Description |
|-------------------------|---------------|-------------------------|
| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type |
| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera |
| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera |
| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera |
| CAMERA_TYPE_TRUE_DEPTH | 4 | True depth camera |
## ConnectionType<a name="section_ConnectionType"></a>
Enumerates camera connection types.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Default value | Description |
|------------------------------|---------------|----------------------------|
| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera |
| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB |
| CAMERA_CONNECTION_REMOTE | 2 | Remote camera |
## CameraManager<a name="section_CameraManager"></a>
Implements camera management, including getting supported cameras and creating **CameraInput** instances.
### getCameras(callback: AsyncCallback<Array<Camera\>\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets all cameras supported by the device. This method uses an asynchronous callback to return the array of supported cameras.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|--------------------------------|-----------|---------------------------------------------------------|
| callback | AsyncCallback<Array<Camera\>\> | Yes | Callback used to return the array of supported cameras. |
**Example**
```
cameraManager.getCameras((err, cameras) => {
if (err) {
console.error('Failed to get the cameras. ${err.message}');
return;
}
console.log('Callback returned with an array of supported cameras: ' + cameras.length);
})
```
### getCameras(): Promise<Array<Camera\>\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets all cameras supported by the device. This method uses a promise to return the array of supported cameras.
**Return values**
| Type | Description |
|------------------------|--------------------------------------------------------|
| Promise<Array<Camera\>\> | Promise used to return an array of supported cameras |
**Example**
```
cameraManager.getCameras().then((cameraArray) => {
console.log('Promise returned with an array of supported cameras: ' + cameraArray.length);
})
```
### createCameraInput(cameraId: string, callback: AsyncCallback<CameraInput\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **CameraInput** instance with the specified camera ID. This method uses an asynchronous callback to return the instance.
**Parameters**
| Name | Default value | Mandatory | Description |
|----------|------------------------------|-----------|--------------------------------------------------|
| cameraId | string | Yes | Camera ID used to create the instance |
| callback | AsyncCallback<CameraInput\> | Yes | Callback used to return the CameraInput instance |
**Example**
```
cameraManager.createCameraInput(cameraId, (err, cameraInput) => {
if (err) {
console.error('Failed to create the CameraInput instance. ${err.message}');
return;
}
console.log('Callback returned with the CameraInput instance.');
})
```
### createCameraInput(cameraId: string): Promise<CameraInput\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **CameraInput** instance with the specified camera ID. This method uses a promise to return the instance.
**Parameters**
| Name | Default value | Mandatory | Description |
|----------|-----------------------------|-----------|------------------------------------------|
| cameraId | string | Yes | Camera ID used to create the instance |
**Return values**
| Type | Description |
|-------------------------|-------------------------------------------------|
| Promise<CameraInput\> | Promise used to return the CameraInput instance |
**Example**
```
cameraManager.createCameraInput(cameraId).then((cameraInput) => {
console.log('Promise returned with the CameraInput instance');
})
```
### createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback<CameraInput\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **CameraInput** instance with the specified camera position and camera type. This method uses an asynchronous callback to return the instance.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|-----------------------------|-----------|---------------------------------------------------|
| position | CameraPosition | Yes | Camera position |
| type | CameraType | Yes | Camera type |
| callback | AsyncCallback<CameraInput\> | Yes | Callback used to return the CameraInput instance |
**Example**
```
cameraManager.createCameraInput(cameraPosition, cameraType, (err, cameraInput) => {
if (err) {
console.error('Failed to create the CameraInput instance. ${err.message}');
return;
}
console.log('Callback returned with the CameraInput instance');
})
```
### createCameraInput(position: CameraPosition, type: CameraType): Promise<CameraInput\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **CameraInput** instance with the specified camera position and camera type. This method uses a promise to return the instance.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------------|-----------|----------------------------------------|
| position | CameraPosition | Yes | Camera position |
| type | CameraType | Yes | Camera type |
**Return values**
| Type | Description |
|-------------------------|-------------------------------------------------|
| Promise<CameraInput\> | Promise used to return the CameraInput instance |
**Example**
```
cameraManager.createCameraInput(cameraPosition, cameraType).then((cameraInput) => {
console.log('Promise returned with the CameraInput instance.');
})
```
### on(type: 'cameraStatus', callback: Callback<CameraStatusInfo\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for camera status changes. This method uses a callback to get camera status changes.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :--------------------------------------------------- |
| type | string | Yes | Camera status event. |
| callback | Callback<CameraStatusInfo\> | Yes | Callback used to get the camera status change. |
**Example**
```
cameraManager.on('cameraStatus', (cameraStatusInfo) => {
console.log('camera : ' + cameraStatusInfo.camera.cameraId);
console.log('status: ' + cameraStatusInfo.status);
})
```
## Camera<a name="section_Camera"></a>
when we call *cameraManager.getCameras()* API, then it will return the **Camera** class which will have all camera-related metadata such as *cameraId, cameraPosition, cameraType & connectionType*.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Fields**
| Name | Type | Access | Description |
|----------------|----------------|----------|------------------------|
| cameraId | string | readonly | Camera ID |
| cameraPosition | cameraPosition | readonly | Camera position |
| cameraType | cameraType | readonly | Camera type |
| connectionType | connectionType | readonly | Camera connection type |
```
async function getCameraInfo() {
var cameraManager = await camera.getCameraManager();
var cameras = await cameraManager.getCameras();
var cameraObj = cameras[0];
var cameraId = cameraObj.cameraId;
var cameraPosition = cameraObj.cameraPosition;
var cameraType = cameraObj.cameraType;
var cameraId = cameraObj.connectionType;
}
```
## CameraStatusInfo<a name="section_Camera"></a>
This interface is a CameraManager callback API return. **CameraStatusInfo** will have *Camera* class & *CameraStatus* predefine constants.From *Camera* class, we can have all camera-related metadata & from *CameraStatus* constants, we will have information such as *APPEAR, DISAPPEAR, AVAILABLE & UNAVAILABLE*.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Fields**
| Name | Type | Description |
|----------------|----------------|------------------|
| camera | Camera | Camera object |
| status | CameraStatus | Camera status |
## CameraInput<a name="section_CameraInput"></a>
Implements a **CameraInput** instance.
### getCameraId(callback: AsyncCallback<string\>\): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets the camera ID based on which this **CameraInput** instance is created. This method uses an asynchronous callback to return the camera ID.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|------------------------|-----------|---------------------------------------|
| callback | AsyncCallback<string\> | Yes | Callback used to return the camera ID |
```
cameraInput.getCameraId((err, cameraId) => {
if (err) {
console.error('Failed to get the camera ID. ${err.message}');
return;
}
console.log('Callback returned with the camera ID: ' + cameraId);
})
```
### getCameraId(): Promise<string\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets the camera ID based on which this **CameraInput** instance is created. This method uses a promise to return the camera ID.
**Return values**
| Type | Description |
|------------------------|--------------------------------------|
| Promise<string\> | Promise used to return the camera ID |
**Example**
```
cameraInput.getCameraId().then((cameraId) => {
console.log('Promise returned with the camera ID:' + cameraId);
})
```
### hasFlash(callback: AsyncCallback<boolean\>): void; <a name="sec_hasFlash"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Checks whether the device has flash light. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|-------------------------|-----------|----------------------------------------------------|
| callback | AsyncCallback<boolean\> | Yes | Callback used to return the flash light support status |
**Example**
```
cameraInput.hasFlash((err, status) => {
if (err) {
console.error('Failed to check whether the device has flash light. ${err.message}');
return;
}
console.log('Callback returned with flash light support status: ' + status);
})
```
### hasFlash(): Promise<boolean\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Checks whether the device has flash light. This method uses a promise to return the result.
**Return values**
| Type | Description |
|-----------------------|--------------------------------------------------------|
| Promise<boolean\> | Promise used to return the flash light support status |
**Example**
```
cameraInput.hasFlash().then((status) => {
console.log('Promise returned with the flash light support status:' + status);
})
```
### isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean\>): void; <a name="sec_isFlashModeSupported"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Checks whether a specified flash mode is supported. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|------------------------|-----------|----------------------------------------------------|
| flashMode | <a href="#sec_FlashMode">FlashMode</a> | Yes | Flash mode |
| callback | AsyncCallback<boolean\> | Yes | Callback used to return the device flash support status |
**Example**
```
cameraInput.isFlashModeSupported(flashMode, (err, status) => {
if (err) {
console.error('Failed to check whether the flash mode is supported. ${err.message}');
return;
}
console.log('Callback returned with the flash mode support status: ' + status);
})
```
### isFlashModeSupported(flashMode: FlashMode): Promise<boolean\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Checks whether a specified flash mode is supported. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|------------------------|-----------|----------------------------------------------------|
| flashMode | <a href="#sec_FlashMode">FlashMode</a> | Yes | Flash mode |
**Return values**
| Type | Description |
|-----------------------|---------------------------------------------------|
| Promise<boolean\> | Promise used to return flash mode support status. |
**Example**
```
cameraInput.isFlashModeSupported(flashMode).then((status) => {
console.log('Promise returned with flash mode support status.' + status);
})
```
### setFlashMode(flashMode: FlashMode, callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Sets flash mode. This method uses an asynchronous callback to return the result.
Note: Before setting the flash mode, check the support for the flash light (<a href="#sec_hasFlash">hasFlash</a> method) and flash mode support (<a href="#sec_isFlashModeSupported">isFlashModeSupported</a> method);
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|------------------------|-----------|----------------------------------------------------|
| flashMode | <a href="#sec_FlashMode">FlashMode</a> | Yes | Flash mode |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
cameraInput.setFlashMode(flashMode, (err) => {
if (err) {
console.error('Failed to set the flash mode ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setFlashMode.');
})
```
### setFlashMode(flashMode: FlashMode): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Sets flash mode. This method uses a promise to return the result.
Note: Before setting the flash mode, check the support for the flash light (<a href="#sec_hasFlash">hasFlash</a> method) and flash mode support (<a href="#sec_isFlashModeSupported">isFlashModeSupported</a> method);
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|------------------------|-----------|----------------------------------------------------|
| flashMode | <a href="#sec_FlashMode">FlashMode</a> | Yes | Flash mode |
**Return values**
| Type | Description |
|-----------------------|-----------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
cameraInput.setFlashMode(flashMode).then(() => {
console.log('Promise returned with the successful execution of setFlashMode.');
})
```
### getFlashMode(callback: AsyncCallback<FlashMode\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets current flash mode. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|---------------------------|-----------|------------------------------------------------|
| callback | AsyncCallback<FlashMode\> | Yes | Callback used to return the current flash mode |
**Example**
```
cameraInput.getFlashMode((err, flashMode) => {
if (err) {
console.error('Failed to get the flash mode ${err.message}');
return;
}
console.log('Callback returned with current flash mode: ' + flashMode);
})
```
### getFlashMode(): Promise<FlashMode\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets current flash mode. This method uses a promise to return the result.
**Return values**
| Type | Description |
|-----------------------|---------------------------------------------------|
| Promise<FlashMode\> | Promise used to return the flash mode |
**Example**
```
cameraInput.getFlashMode().then((flashMode) => {
console.log('Promise returned with current flash mode : ' + flashMode);
})
```
### isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean\>): void; <a name="sec_isFocusModeSupported"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Checks whether a specified focus mode is supported. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|------------------------|-----------|----------------------------------------------------|
| afMode | <a href="#sec_FocusMode">FocusMode</a> | Yes | Focus mode |
| callback | AsyncCallback<boolean\> | Yes | Callback used to return the device focus support status |
**Example**
```
cameraInput.isFocusModeSupported(afMode, (err, status) => {
if (err) {
console.error('Failed to check whether the focus mode is supported. ${err.message}');
return;
}
console.log('Callback returned with the focus mode support status: ' + status);
})
```
### isFocusModeSupported(afMode: FocusMode): Promise<boolean\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Checks whether a specified focus mode is supported. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|----------------------------------------|-----------|-------------|
| afMode | <a href="#sec_FocusMode">FocusMode</a> | Yes | Focus mode |
**Return values**
| Type | Description |
|-----------------------|---------------------------------------------------|
| Promise<boolean\> | Promise used to return the focus mode support status. |
**Example**
```
cameraInput.isFocusModeSupported(afMode).then((status) => {
console.log('Promise returned with focus mode support status.' + status);
})
```
### setFocusMode(afMode: FocusMode, callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Sets focus mode. This method uses an asynchronous callback to return the result.
Note: Before setting the focus mode, check focus mode support (<a href="#sec_isFocusModeSupported">isFocusModeSupported</a> method);
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|------------------------|-----------|------------------------------------|
| afMode | <a href="#sec_FocusMode">FocusMode</a> | Yes | Focus mode |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
cameraInput.setFocusMode(afMode, (err) => {
if (err) {
console.error('Failed to set the focus mode ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setFocusMode.');
})
```
### setFocusMode(afMode: FocusMode): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Sets focus mode. This method uses a promise to return the result.
Note: Before setting the focus mode, check focus mode support (<a href="#sec_isFocusModeSupported">isFocusModeSupported</a> method);
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|-----------------------------------------|-----------|-------------|
| afMode | <a href="#sec_FocusMode">FocusMode</a> | Yes | Focus mode |
**Return values**
| Type | Description |
|-----------------------|-----------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
cameraInput.setFocusMode(afMode).then(() => {
console.log('Promise returned with the successful execution of setFocusMode.');
})
```
### getFocusMode(callback: AsyncCallback<FocusMode\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets the current focus mode. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|---------------------------|-----------|------------------------------------------------|
| callback | AsyncCallback<FocusMode\> | Yes | Callback used to return the current focus mode |
**Example**
```
cameraInput.getFocusMode((err, afMode) => {
if (err) {
console.error('Failed to get the focus mode ${err.message}');
return;
}
console.log('Callback returned with current focus mode: ' + afMode);
})
```
### getFocusMode(): Promise<FocusMode\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets the current focus mode. This method uses a promise to return the result.
**Return values**
| Type | Description |
|-----------------------|---------------------------------------------------|
| Promise<FocusMode\> | Promise used to return the focus mode |
**Example**
```
cameraInput.getFocusMode().then((afMode) => {
console.log('Promise returned with current focus mode : ' + afMode);
})
```
### getZoomRatioRange\(callback: AsyncCallback<Array<number\>\>\): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets the zoom ratios of all zoom values. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|--------------------------------|-----------|-------------------------------------------------|
| callback | AsyncCallback<Array<number\>\> | Yes | Callback used to return the zoom ratio range |
**Example**
```
cameraInput.getZoomRatioRange((err, zoomRatioRange) => {
if (err) {
console.error('Failed to get the zoom ratio range. ${err.message}');
return;
}
console.log('Callback returned with zoom ratio range: ' + zoomRatioRange.length);
})
```
### getZoomRatioRange\(\): Promise<Array<number\>\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets the zoom ratios of all zoom values. This method uses a promise to return the result.
**Return values**
| Type | Description |
|------------------------|---------------------------------------------|
| Promise<Array<number\>\> | Promise used to return the zoom ratio range |
**Example**
```
cameraInput.getZoomRatioRange().then((zoomRatioRange) => {
console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length);
})
```
### setZoomRatio(zoomRatio: number, callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Sets a zoom ratio. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|------------------------|-----------|------------------------------------|
| zoomRatio | number | Yes | Zoom ratio |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
cameraInput.setZoomRatio(zoomRatio, (err) => {
if (err) {
console.error('Failed to set the zoom ratio value ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setZoomRatio.');
})
```
### setZoomRatio(zoomRatio: number): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Sets a zoom ratio. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|----------|-----------|-------------|
| zoomRatio | number | Yes | zoom ratio |
**Return values**
| Type | Description |
|-----------------------|-----------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
cameraInput.setZoomRatio(zoomRatio).then(() => {
console.log('Promise returned with the successful execution of setZoomRatio.');
})
```
### getZoomRatio(callback: AsyncCallback<number\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets current zoom ratio value. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-----------|---------------------------|-----------|------------------------------------------------------|
| callback | AsyncCallback<number\> | Yes | Callback used to return the current zoom ratio value |
**Example**
```
cameraInput.getZoomRatio((err, zoomRatio) => {
if (err) {
console.error('Failed to get the zoom ratio ${err.message}');
return;
}
console.log('Callback returned with current zoom ratio: ' + zoomRatio);
})
```
### getZoomRatio(): Promise<number\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Gets current zoom ratio value. This method uses a promise to return the result.
**Return values**
| Type | Description |
|-----------------------|---------------------------------------------------|
| Promise<number\> | Promise used to return the zoom ratio vaule |
**Example**
```
cameraInput.getZoomRatio().then((zoomRatio) => {
console.log('Promise returned with current zoom ratio : ' + zoomRatio);
})
```
### release\(callback: AsyncCallback<void\>\): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this **CameraInput** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
cameraInput.release((err) => {
if (err) {
console.error('Failed to release the CameraInput instance ${err.message}');
return;
}
console.log('Callback invoked to indicate that the CameraInput instance is released successfully.');
});
```
### release(): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this **CameraInput** instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
cameraInput.release().then(() => {
console.log('Promise returned to indicate that the CameraInput instance is released successfully.');
})
```
### on(type: 'focusStateChange', callback: Callback<FocusState\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for focus state changes. This method uses a callback to get focus state changes.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :-----------------------------------------------|
| type | string | Yes | Name of the event to listen for. |
| callback | Callback<FocusState\> | Yes | Callback used to get the focus state change. |
**Example**
```
cameraInput.on('focusStateChange', (focusState) => {
console.log('Focus state : ' + focusState);
})
```
### on(type: 'error', callback: Callback<CameraInputError\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for **CameraInput** errors. This method uses a callback to get errors.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :-----------------------------------------------|
| type | string | Yes | Camera input error event. |
| callback | Callback<CameraInputError\> | Yes | Callback used to get the camera input errors. |
**Example**
```
cameraInput.on('error', (cameraInputError) => {
console.log('Camera input error code: ' + cameraInputError.code);
})
```
## FlashMode <a name="sec_FlashMode"></a>
Enumerates the flash modes.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Default value | Description |
|------------------------|---------------|------------------------|
| FLASH_MODE_CLOSE | 0 | Flash mode close |
| FLASH_MODE_OPEN | 1 | Flash mode open |
| FLASH_MODE_AUTO | 2 | Flash mode auto |
| FLASH_MODE_ALWAYS_OPEN | 3 | Flash mode always open |
## FocusMode <a name="sec_FocusMode"></a>
Enumerates the focus modes.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Default value | Description |
|----------------------------|---------------|----------------------------|
| FOCUS_MODE_MANUAL | 0 | Focus mode manual |
| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Focus mode continuous auto |
| FOCUS_MODE_AUTO | 2 | Focus mode auto |
| FOCUS_MODE_LOCKED | 3 | Focus mode locked |
## createCaptureSession\(context: Context, callback: AsyncCallback<CaptureSession\>\): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **CaptureSession** instance. This method uses an asynchronous callback to return the instance.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|--------------------------------|-----------|-----------------------------------------------------|
| context | Context | Yes | Application context |
| callback | AsyncCallback<CaptureSession\> | Yes | Callback used to return the CaptureSession instance |
**Example**
```
captureSession.createCaptureSession((context), (err, captureSession) => {
if (err) {
console.error('Failed to create the CaptureSession instance. ${err.message}');
return;
}
console.log('Callback returned with the CaptureSession instance.' + captureSession);
});
```
## createCaptureSession(context: Context\): Promise<CaptureSession\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **CaptureSession** instance. This method uses a promise to return the instance.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|-------------------------------|-----------|-----------------------------------------------------|
| context | Context | Yes | Application context |
**Return values**
| Type | Description |
|---------------------------|---------------------------------------------------|
| Promise<CaptureSession\> | Promise used to return the CaptureSession instance. |
**Example**
```
captureSession.createCaptureSession(context).then((captureSession) => {
console.log('Promise returned with the CaptureSession instance');
})
```
## CaptureSession<a name="sec_CaptureSession"></a>
Implements session capture.
### beginConfig\(callback: AsyncCallback<void\>\): void;<a name="section84581011418"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Starts configuration for this CaptureSession instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.beginConfig((err) => {
if (err) {
console.error('Failed to start the configuration. ${err.message}');
return;
}
console.log('Callback invoked to indicate the begin config success.');
});
```
### beginConfig\(\): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Starts configuration for this CaptureSession instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|---------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.beginConfig().then(() => {
console.log('Promise returned to indicate the begin config success.');
})
```
### commitConfig\(callback: AsyncCallback<void\>\): void;<a name="section84581011418"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Commits the configuration for this CaptureSession instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|---------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.commitConfig((err) => {
if (err) {
console.error('Failed to commit the configuration. ${err.message}');
return;
}
console.log('Callback invoked to indicate the commit config success.');
});
```
### commitConfig\(\): Promise<void\>;<a name="section189141826104616"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Commits the configuration for this CaptureSession instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|---------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.commitConfig().then(() => {
console.log('Promise returned to indicate the commit config success.');
})
```
### addInput\(cameraInput: CameraInput, callback: AsyncCallback<void\>\): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Add a CameraInput instance to this CaptureSession instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-------------|----------------------|-----------|---------------------------------------------|
| cameraInput | CameraInput | Yes | CameraInput instance to add |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.addInput(cameraInput, (err) => {
if (err) {
console.error('Failed to add the CameraInput instance. ${err.message}');
return;
}
console.log('Callback invoked to indicate that the CameraInput instance is added.');
});
```
### addInput\(cameraInput: CameraInput\): Promise<void\>;<a name="section189141826104616"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Add a CameraInput instance to this CaptureSession instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-------------|---------------------|-----------|-------------------------------|
| cameraInput | CameraInput | Yes | CameraInput instance to add |
**Return values**
| Type | Description |
|----------------|------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.addInput(cameraInput).then(() => {
console.log('Promise used to indicate that the CameraInput instance is added.');
})
```
### addOutput\(previewOutput: PreviewOutput, callback: AsyncCallback<void\>\): void;<a name="section84581011418"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Add a PreviewOutput instance to this CaptureSession instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|----------------------|-----------|-------------------------------------|
| previewOutput | PreviewOutput | Yes | PreviewOutput instance to add |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.addOutput(previewOutput, (err) => {
if (err) {
console.error('Failed to add the PreviewOutput instance ${err.message}');
return;
}
console.log('Callback invoked to indicate that the PreviewOutput instance is added.');
});
```
### addOutput\(previewOutput: PreviewOutput\): Promise<void\>;<a name="section189141826104616"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Add a PreviewOutput instance to this CaptureSession instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|---------------------|-----------|--------------------------------|
| previewOutput | PreviewOutput | Yes | PreviewOutput instance to add |
**Return values**
| Type | Description |
|----------------|-----------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.addOutput(previewOutput).then(() => {
console.log('Promise used to indicate that the PreviewOutput instance is added.');
})
```
### addOutput\(photoOutput: PhotoOutput, callback: AsyncCallback<void\>\): void;<a name="section84581011418"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Add a PhotoOutput instance to this CaptureSession instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|---------------------|-----------|-------------------------------------|
| photoOutput | PhotoOutput | Yes | PhotoOutput instance to add |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.addOutput(photoOutput, (err) => {
if (err) {
console.error('Failed to add the PhotoOutput instance ${err.message}');
return;
}
console.log('Callback invoked to indicate that the PhotoOutput instance is added.');
});
```
### addOutput\(photoOutput: PhotoOutput\): Promise<void\>;<a name="section189141826104616"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Add a PhotoOutput instance to this CaptureSession instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|---------------------|-----------|--------------------------------|
| photoOutput | PhotoOutput | Yes | PhotoOutput instance to add |
**Return values**
| Type | Description |
|---------------|-----------------------------------|
| Promise<void> | Promise used to return the result |
**Example**
```
captureSession.addOutput(photoOutput).then(() => {
console.log('Promise used to indicate that the PhotoOutput instance is added.');
})
```
### addOutput\(videoOutput: VideoOutput, callback: AsyncCallback<void\>\): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Add a VideoOutput instance to this CaptureSession instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|---------------------|-----------|-------------------------------------|
| videoOutput | VideoOutput | Yes | VideoOutput instance to add |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.addOutput(videoOutput, (err) => {
if (err) {
console.error('Failed to add the VideoOutput instance ${err.message}');
return;
}
console.log('Callback invoked to indicate that the VideoOutput instance is added.');
});
```
### addOutput\(videoOutput: VideoOutput\): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Add a VideoOutput instance to this CaptureSession instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|---------------------|-----------|--------------------------------|
| videoOutput | VideoOutput | Yes | VideoOutput instance to add |
**Return values**
| Type | Description |
|----------------|-----------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.addOutput(videoOutput).then(() => {
console.log('Promise used to indicate that the VideoOutput instance is added.');
})
```
### removeInput\(cameraInput: CameraInput, callback: AsyncCallback<void\>\): void;<a name="section84581011418"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Removes a **CameraInput** instance from this **CaptureSession** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-------------|----------------------|-----------|------------------------------------|
| cameraInput | CameraInput | Yes | CameraInput instance to remove |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.removeInput(cameraInput, (err) => {
if (err) {
console.error('Failed to remove the CameraInput instance. ${err.message}');
return;
}
console.log('Callback invoked to indicate that the cameraInput instance is removed.');
});
```
### removeInput\(cameraInput: CameraInput\): Promise<void\>;<a name="section189141826104616"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Removes a **CameraInput** instance from this **CaptureSession** instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|-------------|---------------------|-----------|---------------------------------|
| cameraInput | CameraInput | Yes | CameraInput instance to remove |
**Return values**
| Type | Description |
|----------------|-----------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.removeInput(cameraInput).then(() => {
console.log('Promise returned to indicate that the cameraInput instance is removed.');
})
```
### removeOutput\(previewOutput: PreviewOutput, callback: AsyncCallback<void\>\): void;<a name="section84581011418"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Removes a **PreviewOutput** instance from this **CaptureSession** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|----------------------|-----------|------------------------------------|
| previewOutput | PreviewOutput | Yes | PreviewOutput instance to remove |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.removeOutput(previewOutput, (err) => {
if (err) {
console.error('Failed to remove the PreviewOutput instance. ${err.message}');
return;
}
console.log('Callback invoked to indicate that the PreviewOutput instance is removed.');
});
```
### removeOutput(previewOutput: PreviewOutput): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Removes a **PreviewOutput** instance from this **CaptureSession** instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|---------------------|-----------|-----------------------------------|
| previewOutput | PreviewOutput | Yes | PreviewOutput instance to remove |
**Return values**
| Type | Description |
|---------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.removeOutput(previewOutput).then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is removed.');
})
```
### removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Removes a **PhotoOutput** instance from this **CaptureSession** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|----------------------|-----------|------------------------------------|
| photoOutput | PhotoOutput | Yes | PhotoOutput instance to remove |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.removeOutput(photoOutput, (err) => {
if (err) {
console.error('Failed to remove the PhotoOutput instance. ${err.message}');
return;
}
console.log('Callback invoked to indicate that the PhotoOutput instance is removed.');
});
```
### removeOutput(photoOutput: PhotoOutput): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Removes a **PhotoOutput** instance from this **CaptureSession** instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|---------------------|-----------|---------------------------------|
| photoOutput | PhotoOutput | Yes | PhotoOutput instance to remove |
**Return values**
| Type | Description |
|---------------|------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.removeOutput(photoOutput).then(() => {
console.log('Promise returned to indicate that the PhotoOutput instance is removed.');
})
```
### removeOutput(videoOutput: VideoOutput, callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Removes a **VideoOutput** instance from this **CaptureSession** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|----------------------|-----------|------------------------------------|
| videoOutput | VideoOutput | Yes | VideoOutput instance to remove |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.removeOutput(videoOutput, (err) => {
if (err) {
console.error('Failed to remove the VideoOutput instance. ${err.message}');
return;
}
console.log('Callback invoked to indicate that the VideoOutput instance is removed.');
});
```
### removeOutput(videoOutput: VideoOutput): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Removes a **VideoOutput** instance from this **CaptureSession** instance. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|---------------|---------------------|-----------|---------------------------------|
| videoOutput | VideoOutput | Yes | VideoOutput instance to remove |
**Return values**
| Type | Description |
|----------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.removeOutput(videoOutput).then(() => {
console.log('Promise returned to indicate that the VideoOutput instance is removed.');
})
```
### start\(callback: AsyncCallback<void\>\): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Starts this **CaptureSession** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.start((err) => {
if (err) {
console.error('Failed to start the session ${err.message}');
return;
}
console.log('Callback invoked to indicate the session start success.');
});
```
### start\(\): Promise<void\>;<a name="section189141826104616"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Starts this **CaptureSession** instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|-----------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.start().then(() => {
console.log('Promise returned to indicate the session start success.');
})
```
### stop\(callback: AsyncCallback<void\>\): void;<a name="section84581011418"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Stops this **CaptureSession** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.stop((err) => {
if (err) {
console.error('Failed to stop the session ${err.message}');
return;
}
console.log('Callback invoked to indicate the session stop success.');
});
```
### stop(): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Stops this **CaptureSession** instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|-----------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.stop().then(() => {
console.log('Promise returned to indicate the session stop success.');
})
```
### release\(callback: AsyncCallback<void\>\): void;<a name="section84581011418"></a>
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this **CaptureSession** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
captureSession.release((err) => {
if (err) {
console.error('Failed to release the CaptureSession instance ${err.message}');
return;
}
console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.');
});
```
### release(): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this **CaptureSession** instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
captureSession.release().then(() => {
console.log('Promise returned to indicate that the CaptureSession instance is released successfully.');
})
```
### on(type: 'error', callback: Callback<CaptureSessionError\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for **CaptureSession** errors. This method uses a callback to get errors.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :-----------------------------------------------|
| type | string | Yes | Capture session error event. |
| callback | Callback<CaptureSessionError\> | Yes | Callback used to get the capture session errors. |
**Example**
```
captureSession.on('error', (captureSessionError) => {
console.log('Capture session error code: ' + captureSessionError.code);
})
```
## createPreviewOutput(surfaceId: string, callback: AsyncCallback<PreviewOutput\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **PreviewOutput** instance. This method uses an asynchronous callback to return the instance.
**Parameters**
| Name | Type | Mandatory | Description |
|------------|-------------------------------|-----------|----------------------------------------------------|
| surfaceId | string | Yes | Surface ID received from XComponent view |
| callback | AsyncCallback<PreviewOutput\> | Yes | Callback used to return the PreviewOutput instance |
**Example**
```
camera.createPreviewOutput((surfaceId), (err, previewOutput) => {
if (err) {
console.error('Failed to create the PreviewOutput instance. ${err.message}');
return;
}
console.log('Callback returned with previewOutput instance');
});
```
## createPreviewOutput(surfaceId: string): Promise<PreviewOutput>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **PreviewOutput** instance. This method uses a promise to return the instance.
**Parameters**
| Name | Type | Mandatory | Description |
|------------|-----------------|-----------|----------------------------------------------------|
| surfaceId | string | Yes | Surface ID received from XComponent view |
**Return values**
| Type | Description |
|-------------------------|---------------------------------------------------|
| Promise<PreviewOutput\> | Promise used to return the PreviewOutput instance |
**Example**
```
camera.createPreviewOutput(surfaceId).then((previewOutput) => {
console.log('Promise returned with the PreviewOutput instance');
})
```
## PreviewOutput
Implements preview output.
### release(callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this **PreviewOutput** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
previewOutput.release((err) => {
if (err) {
console.error('Failed to release the PreviewOutput instance ${err.message}');
return;
}
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
});
```
### release(): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this **PreviewOutput** instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|-----------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
previewOutput.release().then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.');
})
```
### on(type: 'frameStart', callback: Callback<number\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for preview frame start events. This method uses a callback to get the event information.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :---------------- | :-------- | :----------------------------------|
| type | string | Yes | Name of the event to listen for. |
| callback | Callback<void\> | Yes | Callback used to return the result |
**Example**
```
previewOutput.on('frameStart', () => {
console.log('Preview frame started');
})
```
### on(type: 'frameEnd', callback: Callback<number\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for preview frame end event. This method uses a callback to get the event information.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :---------------- | :-------- | :----------------------------------|
| type | string | Yes | Name of the event to listen for. |
| callback | Callback<void\> | Yes | Callback used to return the result |
**Example**
```
previewOutput.on('frameEnd', () => {
console.log('Preview frame ended');
})
```
### on(type: 'error', callback: Callback<PreviewOutputError\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for **PreviewOutput** errors. This method uses a callback to get errors.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :-----------------------------------------------|
| type | string | Yes | Preview output error event. |
| callback | Callback<PreviewOutputError\> | Yes | Callback used to get the preview output errors. |
**Example**
```
previewOutput.on('error', (previewOutputError) => {
console.log('Preview output error code: ' + previewOutputError.code);
})
```
## createPhotoOutput(surfaceId: string, callback: AsyncCallback<PhotoOutput\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **PhotoOutput** instance. This method uses an asynchronous callback to return the instance.
**Parameters**
| Name | Type | Mandatory | Description |
|------------|-------------------------------|-----------|----------------------------------------------------|
| surfaceId | string | Yes | Surface ID received from ImageReceiver |
| callback | AsyncCallback<PhotoOutput\> | Yes | Callback used to return the PhotoOutput instance |
**Example**
```
camera.createPhotoOutput((surfaceId), (err, photoOutput) => {
if (err) {
console.error('Failed to create the PhotoOutput instance. ${err.message}');
return;
}
console.log('Callback returned with the PhotoOutput instance.');
});
```
## createPhotoOutput(surfaceId: string): Promise<PhotoOutput\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **PhotoOutput** instance. This method uses a promise to return the PhotoOutput instance.
**Parameters**
| Name | Type | Mandatory | Description |
|------------|-----------------|-----------|----------------------------------------------------|
| surfaceId | string | Yes | Surface ID received from ImageReceiver |
**Return values**
| Type | Description |
|-------------------------|--------------------------------------------------|
| Promise<PhotoOutput\> | Promise used to return the PhotoOutput instance |
**Example**
```
camera.createPhotoOutput(surfaceId).then((photoOutput) => {
console.log('Promise returned with PhotoOutput instance');
})
```
## ImageRotation
Enumerates the image rotation angles.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Default Value | Description |
|--------------|---------------|----------------------------------------|
| ROTATION_0 | 0 | The capture image rotates 0 degrees |
| ROTATION_90 | 90 | The capture image rotates 90 degrees |
| ROTATION_180 | 180 | The capture image rotates 180 degrees |
| ROTATION_270 | 270 | The capture image rotates 270 degrees |
## Location
Defines the location of a captured image.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Type | Access | Description |
|-----------|--------|--------------|-------------|
| latitude | number | read / write | Latitude |
| longitude | number | read / write | Longitude |
## QualityLevel
Enumerates the image quality levels.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Default value | Description |
|----------------------|---------------|----------------------|
| QUALITY_LEVEL_HIGH | 0 | High image quality |
| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality |
| QUALITY_LEVEL_LOW | 2 | Low image quality |
## PhotoCaptureSetting
Defines the settings for image capture.
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
| Name | Type | Mandatory | Description |
|----------|---------------|-----------|---------------------|
| quality | QualityLevel | Optional | Photo image quality |
| rotation | ImageRotation | Optional | Photo rotation |
## PhotoOutput
Implements photo output.
### capture(callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Captures a photo. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|---------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
photoOutput.capture((err) => {
if (err) {
console.error('Failed to capture the photo ${err.message}');
return;
}
console.log('Callback invoked to indicate the photo capture request success.');
});
```
### capture(setting: PhotoCaptureSetting, callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Captures a photo with the specified capture settings. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------------------------|
| setting | PhotoCaptureSetting | Yes | Photo capture settings |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
photoOutput.capture(settings, (err) => {
if (err) {
console.error('Failed to capture the photo ${err.message}');
return;
}
console.log('Callback invoked to indicate the photo capture request success.');
});
```
### capture(setting?: PhotoCaptureSetting): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Captures a photo with the specified capture settings. This method uses a promise to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|---------------------|-----------|----------------------------------------------|
| setting | PhotoCaptureSetting | No | Photo capture settings |
**Return values**
| Type | Description |
|----------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
photoOutput.capture().then(() => {
console.log('Promise returned to indicate that photo capture request success.');
})
```
### release(callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this **PhotoOutput** instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
photoOutput.release((err) => {
if (err) {
console.error('Failed to release the PhotoOutput instance ${err.message}');
return;
}
console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.');
});
```
### release(): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this **PhotoOutput** instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
photoOutput.release().then(() => {
console.log('Promise returned to indicate that the PhotoOutput instance is released successfully.');
})
```
### on(type: 'captureStart', callback: Callback<number\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for photo capture start events. This method uses a callback to get the event information.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :-----------------------------------------------|
| type | string | Yes | Name of the event to listen for. |
| callback | Callback<number\> | Yes | Callback used to get the capture ID. |
**Example**
```
photoOutput.on('captureStart', (captureId) => {
console.log('photo capture stated, captureId : ' + captureId);
})
```
### on(type: 'frameShutter', callback: Callback<FrameShutterInfo\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for frame shutter events. This method uses a callback to get the event information.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :-----------------------------------------------|
| type | string | Yes | Name of the event to listen for. |
| callback | Callback<FrameShutterInfo\> | Yes | Callback used to get the frame shutter information.|
**Example**
```
photoOutput.on('frameShutter', (frameShutterInfo) => {
console.log('photo capture end, captureId : ' + frameShutterInfo.captureId);
console.log('Timestamp for frame : ' + frameShutterInfo.timestamp);
})
```
### on(type: 'captureEnd', callback: Callback<CaptureEndInfo\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for photo capture end events. This method uses a callback to get the event information.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :------------------------------------------------|
| type | string | Yes | Name of the event to listen for. |
| callback | Callback<CaptureEndInfo\> | Yes | Callback used to get the capture end information |
**Example**
```
photoOutput.on('captureEnd', (captureEndInfo) => {
console.log('photo capture end, captureId : ' + captureEndInfo.captureId);
console.log('frameCount : ' + captureEndInfo.frameCount);
})
```
### on(type: 'error', callback: Callback<PhotoOutputError\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for **PhotoOutput** errors. This method uses a callback to get errors.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :-----------------------------------------------|
| type | string | Yes | Photo output error event. |
| callback | Callback<PhotoOutputError\> | Yes | Callback used to get the photo output errors. |
**Example**
```
photoOutput.on('error', (photoOutputError) => {
console.log('Photo output error code: ' + photoOutputError.code);
})
```
## createVideoOutput(surfaceId: string, callback: AsyncCallback<VideoOutput\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **VideoOutput** instance. This method uses an asynchronous callback to return the instance.
**Parameters**
| Name | Type | Mandatory | Description |
|------------|-------------------------------|-----------|----------------------------------------------------|
| surfaceId | string | Yes | Surface ID received from VideoRecorder |
| callback | AsyncCallback<VideoOutput\> | Yes | Callback used to return the VideoOutput instance |
**Example**
```
camera.createVideoOutput((surfaceId), (err, videoOutput) => {
if (err) {
console.error('Failed to create the VideoOutput instance. ${err.message}');
return;
}
console.log('Callback returned with the VideoOutput instance');
});
```
## createVideoOutput(surfaceId: string): Promise<VideoOutput\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Creates a **VideoOutput** instance. This method uses a promise to return the VideoOutput instance.
**Parameters**
| Name | Type | Mandatory | Description |
|------------|-----------------|-----------|----------------------------------------------------|
| surfaceId | string | Yes | Surface ID received from VideoRecorder |
**Return values**
| Type | Description |
|---------------------------------------|-------------------------------------------------|
| Promise<[VideoOutput](#videooutput)\> | Promise used to return the VideoOutput instance |
**Example**
```
camera.createVideoOutput(surfaceId).then((videoOutput) => {
console.log('Promise returned with the VideoOutput instance');
})
```
## VideoOutput
Implements video output.
### start(callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Starts the video output. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
videoOutput.start((err) => {
if (err) {
console.error('Failed to start the video output ${err.message}');
return;
}
console.log('Callback invoked to indicate the video output start success.');
});
```
### start(): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Starts the video output. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
videoOutput.start().then(() => {
console.log('Promise returned to indicate that start method execution success.');
})
```
### stop(callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Stops the video output. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
videoOutput.stop((err) => {
if (err) {
console.error('Failed to stop the video output ${err.message}');
return;
}
console.log('Callback invoked to indicate the video output stop success.');
});
```
### stop(): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Stops the video output. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
videoOutput.start().then(() => {
console.log('Promise returned to indicate that stop method execution success.');
})
```
### release(callback: AsyncCallback<void\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this VideoOutput instance. This method uses an asynchronous callback to return the result.
**Parameters**
| Name | Type | Mandatory | Description |
|----------|----------------------|-----------|----------------------------------------------|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result |
**Example**
```
videoOutput.release((err) => {
if (err) {
console.error('Failed to release the VideoOutput instance ${err.message}');
return;
}
console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.');
});
```
### release(): Promise<void\>;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Releases this VideoOutput instance. This method uses a promise to return the result.
**Return values**
| Type | Description |
|----------------|---------------------------------------------|
| Promise<void\> | Promise used to return the result |
**Example**
```
videoOutput.release().then(() => {
console.log('Promise returned to indicate that the VideoOutput instance is released successfully.');
})
```
### on(type: 'frameStart', callback: Callback<number\>): void;
**System Capabilities:**
SystemCapability.Multimedia.Camera.Core
**Description**
Listens for video frame start events. This method uses a callback to get the event information.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :---------------- | :-------- | :----------------------------------|
| type | string | Yes | Name of the event to listen for. |
| callback | Callback<void\> | Yes | Callback used to return the result |
**Example**
```
videoOutput.on('frameStart', () => {
console.log('Video frame started');
})
```
### on(type: 'frameEnd', callback: Callback<number\>): void;
Listens for video frame end events. This method uses a callback to get the event information.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :---------------- | :-------- | :----------------------------------|
| type | string | Yes | Name of the event to listen for. |
| callback | Callback<void\> | Yes | Callback used to return the result |
**Example**
```
videoOutput.on('frameEnd', () => {
console.log('Video frame ended');
})
```
### on(type: 'error', callback: Callback<VideoOutputError\>): void;
Listens for **VideoOutput** errors. This method uses a callback to get errors.
**Parameters**
| Name | Type | Mandatory | Description |
| :------- | :--------------------- | :-------- | :-----------------------------------------------|
| type | string | Yes | Video output error event. |
| callback | Callback<VideoOutputError\> | Yes | Callback used to get the video output errors. |
**Example**
```
videoOutput.on('error', (VideoOutputError) => {
console.log('Video output error code: ' + VideoOutputError.code);
})
```
\ No newline at end of file
......@@ -125,73 +125,6 @@ Creates an **AudioRecorder** instance to control audio recording.
let audiorecorder = media.createAudioRecorder();
```
## media.createVideoRecorder<sup>9+</sup>
createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>): void
Creates a **VideoRecorder** instance in asynchronous mode. This API uses a callback to return the result.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the **VideoRecorder** instance created.|
**Example**
```js
let videoRecorder
media.createVideoRecorder((error, video) => {
if (typeof(video) != 'undefined') {
videoRecorder = video;
console.info('video createVideoRecorder success');
} else {
console.info(`video createVideoRecorder fail, error:${error.message}`);
}
});
```
## media.createVideoRecorder<sup>9+</sup>
createVideoRecorder(): Promise<[VideoRecorder](#videorecorder9)>
Creates a **VideoRecorder** instance in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value**
| Type | Description |
| ----------------------------------------- | ----------------------------------- |
| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance created.|
**Example**
```js
let videoRecorder
function failureCallback(error) {
console.info(`video failureCallback, error:${error.message}`);
}
function catchCallback(error) {
console.info(`video catchCallback, error:${error.message}`);
}
await media.createVideoRecorder.then((video) => {
if (typeof(video) != 'undefined') {
videoRecorder = video;
console.info('video createVideoRecorder success');
} else {
console.info('video createVideoRecorder fail');
}
}, failureCallback).catch(catchCallback);
```
## MediaErrorCode<sup>8+</sup>
Enumerates the media error codes.
......@@ -1836,662 +1769,6 @@ Enumerates the audio output formats.
| AMR_WB | 4 | AMR_WB.<br>This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.|
| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.|
## VideoRecorder<sup>9+</sup>
Implements video recording. Before calling an API of the **VideoRecorder** class, you must call [createVideoRecorder()](#mediacreatevideorecorder9) to create a [VideoRecorder](#videorecorder9) instance.
For details about the video recording demo, see [Video Recording Development](../../media/video-recorder.md).
### Attributes
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
| Name | Type | Readable| Writable| Description |
| ------------------ | -------------------------------------- | ---- | ---- | ---------------- |
| state<sup>8+</sup> | [VideoRecordState](#videorecordstate9) | Yes | No | Video recording state.|
### prepare<sup>9+</sup><a name=videorecorder_prepare1></a>
prepare(config: VideoRecorderConfig, callback: AsyncCallback\<void>): void;
Sets video recording parameters in asynchronous mode. This API uses a callback to return the result.
**Required permissions:** ohos.permission.MICROPHONE and ohos.permission.CAMERA
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ----------------------------------- |
| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
let videoProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 48000,
videoCodec : 'video/mp4v-es',
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
}
let videoConfig = {
audioSourceType : 1,
videoSourceType : 0,
profile : videoProfile,
url : 'fd://xx', // The file must be created by the caller and granted with proper permissions.
orientationHint : 0,
location : { latitude : 30, longitude : 130 },
}
// asyncallback
let videoRecorder = null;
let events = require('events');
let eventEmitter = new events.EventEmitter();
eventEmitter.on('prepare', () => {
videoRecorder.prepare(videoConfig, (err) => {
if (typeof (err) == 'undefined') {
console.info('prepare success');
} else {
console.info('prepare failed and error is ' + err.message);
}
});
});
media.createVideoRecorder((err, recorder) => {
if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') {
videoRecorder = recorder;
console.info('createVideoRecorder success');
eventEmitter.emit('prepare'); // Trigger the 'prepare' event.
} else {
console.info('createVideoRecorder failed and error is ' + err.message);
}
});
```
### prepare<sup>9+</sup><a name=videorecorder_prepare2></a>
prepare(config: VideoRecorderConfig): Promise\<void>;
Sets video recording parameters in asynchronous mode. This API uses a promise to return the result.
**Required permissions:** ohos.permission.MICROPHONE and ohos.permission.CAMERA
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------------------------------------------- | ---- | ------------------------ |
| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set.|
**Return value**
| Type | Description |
| -------------- | ---------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
let videoProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 48000,
videoCodec : 'video/mp4v-es',
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
}
let videoConfig = {
audioSourceType : 1,
videoSourceType : 0,
profile : videoProfile,
url : 'fd://xx', // The file must be created by the caller and granted with proper permissions.
orientationHint : 0,
location : { latitude : 30, longitude : 130 },
}
// promise
let videoRecorder = null;
await media.createVideoRecorder().then((recorder) => {
if (typeof (recorder) != 'undefined') {
videoRecorder = recorder;
console.info('createVideoRecorder success');
} else {
console.info('createVideoRecorder failed');
}
}, (err) => {
console.info('error hanppend message is ' + err.message);
}).catch((err) => {
console.info('catch err error message is ' + err.message);
});
await videoRecorder.prepare(videoConfig).then(() => {
console.info('prepare success');
}, (err) => {
console.info('prepare failed and error is ' + err.message);
}).catch((err) => {
console.info('prepare failed and catch error is ' + err.message);
});
```
### getInputSurface<sup>9+</sup>
getInputSurface(callback: AsyncCallback\<string>): void;
Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data.
Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time.
This API can be called only after [prepare()](#videorecorder_prepare1) is called.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | --------------------------- |
| callback | AsyncCallback\<string> | Yes | Callback used to obtain the result.|
**Example**
```js
// asyncallback
let surfaceID = null; // Surface ID passed to the external system.
videoRecorder.getInputSurface((err, surfaceId) => {
if (typeof (err) == 'undefined') {
console.info('getInputSurface success');
surfaceID = surfaceId;
} else {
console.info('getInputSurface failed and error is ' + err.message);
}
});
```
### getInputSurface<sup>9+</sup>
getInputSurface(): Promise\<string>;
Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data.
Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time.
This API can be called only after [prepare()](#videorecorder_prepare1) is called.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value**
| Type | Description |
| ---------------- | -------------------------------- |
| Promise\<string> | Promise used to return the result.|
**Example**
```js
// promise
let surfaceID = null; // Surface ID passed to the external system.
await videoRecorder.getInputSurface().then((surfaceId) => {
console.info('getInputSurface success');
surfaceID = surfaceId;
}, (err) => {
console.info('getInputSurface failed and error is ' + err.message);
}).catch((err) => {
console.info('getInputSurface failed and catch error is ' + err.message);
});
```
### start<sup>9+</sup><a name=videorecorder_start1></a>
start(callback: AsyncCallback\<void>): void;
Starts video recording in asynchronous mode. This API uses a callback to return the result.
This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
// asyncallback
videoRecorder.start((err) => {
if (typeof (err) == 'undefined') {
console.info('start videorecorder success');
} else {
console.info('start videorecorder failed and error is ' + err.message);
}
});
```
### start<sup>9+</sup><a name=videorecorder_start2></a>
start(): Promise\<void>;
Starts video recording in asynchronous mode. This API uses a promise to return the result.
This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value**
| Type | Description |
| -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
// promise
await videoRecorder.start().then(() => {
console.info('start videorecorder success');
}, (err) => {
console.info('start videorecorder failed and error is ' + err.message);
}).catch((err) => {
console.info('start videorecorder failed and catch error is ' + err.message);
});
```
### pause<sup>9+</sup><a name=videorecorder_pause1></a>
pause(callback: AsyncCallback\<void>): void;
Pauses video recording in asynchronous mode. This API uses a callback to return the result.
This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1).
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
// asyncallback
videoRecorder.pause((err) => {
if (typeof (err) == 'undefined') {
console.info('pause videorecorder success');
} else {
console.info('pause videorecorder failed and error is ' + err.message);
}
});
```
### pause<sup>9+</sup><a name=videorecorder_pause2></a>
pause(): Promise\<void>;
Pauses video recording in asynchronous mode. This API uses a promise to return the result.
This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1).
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value**
| Type | Description |
| -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
// promise
await videoRecorder.pause().then(() => {
console.info('pause videorecorder success');
}, (err) => {
console.info('pause videorecorder failed and error is ' + err.message);
}).catch((err) => {
console.info('pause videorecorder failed and catch error is ' + err.message);
});
```
### resume<sup>9+</sup><a name=videorecorder_resume1></a>
resume(callback: AsyncCallback\<void>): void;
Resumes video recording in asynchronous mode. This API uses a callback to return the result.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
// asyncallback
videoRecorder.resume((err) => {
if (typeof (err) == 'undefined') {
console.info('resume videorecorder success');
} else {
console.info('resume videorecorder failed and error is ' + err.message);
}
});
```
### resume<sup>9+</sup><a name=videorecorder_resume2></a>
resume(): Promise\<void>;
Resumes video recording in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value**
| Type | Description |
| -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
// promise
await videoRecorder.resume().then(() => {
console.info('resume videorecorder success');
}, (err) => {
console.info('resume videorecorder failed and error is ' + err.message);
}).catch((err) => {
console.info('resume videorecorder failed and catch error is ' + err.message);
});
```
### stop<sup>9+</sup><a name=videorecorder_stop1></a>
stop(callback: AsyncCallback\<void>): void;
Stops video recording in asynchronous mode. This API uses a callback to return the result.
To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
// asyncallback
videoRecorder.stop((err) => {
if (typeof (err) == 'undefined') {
console.info('stop videorecorder success');
} else {
console.info('stop videorecorder failed and error is ' + err.message);
}
});
```
### stop<sup>9+</sup><a name=videorecorder_stop2></a>
stop(): Promise\<void>;
Stops video recording in asynchronous mode. This API uses a promise to return the result.
To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value**
| Type | Description |
| -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
// promise
await videoRecorder.stop().then(() => {
console.info('stop videorecorder success');
}, (err) => {
console.info('stop videorecorder failed and error is ' + err.message);
}).catch((err) => {
console.info('stop videorecorder failed and catch error is ' + err.message);
});
```
### release<sup>9+</sup><a name=videorecorder_release1></a>
release(callback: AsyncCallback\<void>): void;
Releases the video recording resource in asynchronous mode. This API uses a callback to return the result.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
// asyncallback
videoRecorder.release((err) => {
if (typeof (err) == 'undefined') {
console.info('release videorecorder success');
} else {
console.info('release videorecorder failed and error is ' + err.message);
}
});
```
### release<sup>9+</sup><a name=videorecorder_release2></a>
release(): Promise\<void>;
Releases the video recording resource in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value**
| Type | Description |
| -------------- | ----------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
// promise
await videoRecorder.release().then(() => {
console.info('release videorecorder success');
}, (err) => {
console.info('release videorecorder failed and error is ' + err.message);
}).catch((err) => {
console.info('release videorecorder failed and catch error is ' + err.message);
});
```
### reset<sup>9+</sup><a name=videorecorder_reset1></a>
reset(callback: AsyncCallback\<void>): void;
Resets video recording in asynchronous mode. This API uses a callback to return the result.
To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Example**
```js
// asyncallback
videoRecorder.reset((err) => {
if (typeof (err) == 'undefined') {
console.info('reset videorecorder success');
} else {
console.info('reset videorecorder failed and error is ' + err.message);
}
});
```
### reset<sup>9+</sup><a name=videorecorder_reset2></a>
reset(): Promise\<void>;
Resets video recording in asynchronous mode. This API uses a promise to return the result.
To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Return value**
| Type | Description |
| -------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
// promise
await videoRecorder.reset().then(() => {
console.info('reset videorecorder success');
}, (err) => {
console.info('reset videorecorder failed and error is ' + err.message);
}).catch((err) => {
console.info('reset videorecorder failed and catch error is ' + err.message);
});
```
### on('error')<sup>9+</sup>
on(type: 'error', callback: ErrorCallback): void
Subscribes to the video recording error event.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.<br>The 'error' event is triggered when an error occurs during video recording.|
| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. |
**Example**
```js
videoRecorder.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`); // Print the error name.
console.info(`audio error called, errCode is ${error.code}`); // Print the error code.
console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type.
});
// This event is reported when an error occurs during the retrieval of videoRecordState.
```
## VideoRecordState<sup>9+</sup>
Enumerates the video recording states. You can obtain the state through the **state** attribute.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
| Name | Type | Description |
| -------- | ------ | ---------------------- |
| idle | string | The video recorder is idle. |
| prepared | string | The video recording parameters are set.|
| playing | string | Video recording is in progress. |
| paused | string | Video recording is paused. |
| stopped | string | Video recording is stopped. |
| error | string | Audio playback is in the error state. |
## VideoRecorderConfig<sup>9+</sup>
Describes the video recording parameters.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
| Name | Type | Mandatory| Description |
| --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ |
| audioSourceType | [AudioSourceType](#audiosourcetype9) | Yes | Type of the audio source for video recording. |
| videoSourceType | [VideoSourceType](#videosourcetype9) | Yes | Type of the video source for video recording. |
| profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. |
| rotation | number | No | Rotation angle of the recorded video. |
| location | [Location](#location) | No | Geographical location of the recorded video. |
| url | string | Yes | Video output URL. Supported: fd://xx&nbsp;(fd&nbsp;number)<br>![](figures/en-us_image_url.png) <br>The file must be created by the caller and granted with proper permissions.|
## AudioSourceType<sup>9+</sup>
Enumerates the audio source types for video recording.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
| Name | Value | Description |
| ------------------------- | ---- | ---------------------- |
| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.|
| AUDIO_SOURCE_TYPE_MIC | 1 | Mic audio input source. |
## VideoSourceType<sup>9+</sup>
Enumerates the video source types for video recording.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
| Name | Value | Description |
| ----------------------------- | ---- | ------------------------------- |
| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.|
| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data. |
## VideoRecorderProfile<sup>9+</sup>
Describes the video recording profile.
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
| Name | Type | Mandatory| Description |
| ---------------- | -------------------------------------------- | ---- | ---------------- |
| audioBitrate | number | Yes | Audio encoding bit rate.|
| audioChannels | number | Yes | Number of audio channels.|
| audioCodec | [CodecMimeType](#codecmimetype8) | Yes | Audio encoding format. |
| audioSampleRate | number | Yes | Audio sampling rate. |
| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file.|
| videoBitrate | number | Yes | Video encoding bit rate.|
| videoCodec | [CodecMimeType](#codecmimetype8) | Yes | Video encoding format. |
| videoFrameWidth | number | Yes | Width of the recorded video frame.|
| videoFrameHeight | number | Yes | Height of the recorded video frame.|
| videoFrameRate | number | Yes | Video frame rate. |
## ContainerFormatType<sup>8+</sup>
Enumerates the container format types (CFTs).
......
# Work Scheduler
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import workScheduler from '@ohos.workScheduler'
```
## workScheduler.startWork
startWork(work: WorkInfo): boolean
Instructs the **WorkSchedulerService** to add the specified task to the execution queue.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | --------------------- | ---- | -------------- |
| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.|
**Return value**
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the task is added to the execution queue; returns **false** otherwise.|
**Example**
```
let workInfo = {
workId: 1,
batteryLevel:50,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension"
}
var res = workScheduler.startWork(workInfo);
console.info("workschedulerLog res:" + res);
```
## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): boolean
Instructs the **WorkSchedulerService** to stop the specified task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | --------------------- | ---- | ---------- |
| work | [WorkInfo](#workinfo) | Yes | Task to stop. |
| needCancel | boolean | Yes | Whether to cancel the task.|
**Return value**
| Type | Description |
| ------- | ----------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```
let workInfo = {
workId: 1,
batteryLevel:50,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension"
}
var res = workScheduler.stopWork(workInfo, false);
console.info("workschedulerLog res:" + res);
```
## workScheduler.getWorkStatus
getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void
Obtains the latest task status. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. |
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.|
**Example**
```
workScheduler.getWorkStatus(50, (err, res) => {
if (err) {
console.info('workschedulerLog getWorkStatus failed, because:' + err.data);
} else {
for (let item in res) {
console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
}
}
});
```
## workScheduler.getWorkStatus
getWorkStatus(workId: number): Promise\<WorkInfo>
Obtains the latest task status. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
| workId | number | Yes | Task ID.|
**Return value**
| Type | Description |
| ------------------------------- | ---------------------------------------- |
| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.|
**Example**
```
workScheduler.getWorkStatus(50).then((res) => {
for (let item in res) {
console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
}
}).catch((err) => {
console.info('workschedulerLog getWorkStatus failed, because:' + err.data);
})
```
## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return all tasks associated with the current application.|
**Return value**
| Type | Description |
| ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.|
**Example**
```
workScheduler.obtainAllWorks((err, res) =>{
if (err) {
console.info('workschedulerLog obtainAllWorks failed, because:' + err.data);
} else {
console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
}
});
```
## workScheduler.obtainAllWorks
obtainAllWorks(): Promise<Array\<WorkInfo>>
Obtains all tasks associated with this application. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Return value**
| Type | Description |
| -------------------------------------- | ------------------------------ |
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all tasks associated with the current application.|
**Example**
```
workScheduler.obtainAllWorks().then((res) => {
console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
}).catch((err) => {
console.info('workschedulerLog obtainAllWorks failed, because:' + err.data);
})
```
## workScheduler.stopAndClearWorks
stopAndClearWorks(): boolean
Stops and cancels all tasks associated with the current application.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Example**
```
let res = workScheduler.stopAndClearWorks();
console.info("workschedulerLog res:" + res);
```
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
**Example**
```
workScheduler.isLastWorkTimeOut(500, (err, res) =>{
if (err) {
console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.data);
} else {
console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
}
});
```
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean>
Checks whether the last execution of the specified task timed out. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
| workId | number | Yes | Task ID.|
**Return value**
| Type | Description |
| ----------------- | ---------------------------------------- |
| Promise\<boolean> | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
**Example**
```
workScheduler.isLastWorkTimeOut(500)
.then(res => {
console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
})
.catch(err => {
console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.data);
});
```
## WorkInfo
Provides detailed information about the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Type | Mandatory | Description |
| --------------- | --------------------------------- | ---- | ---------------- |
| workId | number | Yes | Task ID. |
| bundleName | string | Yes | Name of the Work Scheduler task bundle. |
| abilityName | string | Yes | Name of the component to be notified by a Work Scheduler callback.|
| networkType | [NetworkType](#networktype) | No | Network type. |
| isCharging | boolean | No | Whether the device is charging. |
| chargerType | [ChargingType](#chargingtype) | No | Charging type. |
| batteryLevel | number | No | Battery level. |
| batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. |
| storageRequest | [StorageRequest](#storagerequest) | No | Storage status. |
| isRepeat | boolean | No | Whether the task is repeated. |
| repeatCycleTime | number | No | Repeat interval. |
| repeatCount | number | No | Number of repeat times. |
## NetworkType
Enumerates the network types that can trigger the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Default Value | Description |
| ---------------------- | ---- | ----------------------- |
| NETWORK_TYPE_ANY | 0 | Any network type. |
| NETWORK_TYPE_MOBILE | 1 | Mobile network. |
| NETWORK_TYPE_WIFI | 2 | Wi-Fi network. |
| NETWORK_TYPE_BLUETOOTH | 3 | Bluetooth network.|
| NETWORK_TYPE_WIFI_P2P | 4 | Wi-Fi P2P network. |
| NETWORK_TYPE_ETHERNET | 5 | Ethernet. |
## ChargingType
Enumerates the charging types that can trigger the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Default Value | Description |
| ------------------------- | ---- | -------------------- |
| CHARGING_PLUGGED_ANY | 0 | Any charging type.|
| CHARGING_PLUGGED_AC | 1 | DC charging. |
| CHARGING_PLUGGED_USB | 2 | USB charging. |
| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. |
## BatteryStatus
Enumerates the battery status that can trigger the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Default Value | Description |
| -------------------------- | ---- | -------------------------- |
| BATTERY_STATUS_LOW | 0 | A low battery alert is displayed. |
| BATTERY_STATUS_OKAY | 1 | The battery level is restored from low to normal. |
| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.|
## StorageRequest
Enumerates the storage status that can trigger the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
|Name |Default Value |Description|
| -------- | -------- | -------- |
|STORAGE_LEVEL_LOW |0 |The storage space is insufficient.
|STORAGE_LEVEL_OKAY |1 |The storage space is restored from insufficient to normal.
|STORAGE_LEVEL_LOW_OR_OKAY |2 |The storage space is restored from insufficient to normal, or the storage space is insufficient.
......@@ -60,6 +60,7 @@
- [ImageAnimator](ts-basic-components-imageanimator.md)
- [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.md)
- [Navigation](ts-basic-components-navigation.md)
- [PatternLock](ts-basic-components-patternlock.md)
- [PluginComponent](ts-basic-components-plugincomponent.md)
- [Progress](ts-basic-components-progress.md)
......@@ -67,6 +68,9 @@
- [Radio](ts-basic-components-radio.md)
- [Rating](ts-basic-components-rating.md)
- [RichText](ts-basic-components-richtext.md)
- [Stepper](ts-basic-components-stepper.md)
- [StepperItem](ts-basic-components-stepperitem.md)
- [ScrollBar](ts-basic-components-scrollbar.md)
- [Search](ts-basic-components-search.md)
- [Select](ts-basic-components-select.md)
- [Slider](ts-basic-components-slider.md)
......@@ -94,17 +98,14 @@
- [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md)
- [Navigator](ts-container-navigator.md)
- [Navigation](ts-basic-components-navigation.md)
-
- [Panel](ts-container-panel.md)
- [Refresh](ts-container-refresh.md)
- [Row](ts-container-row.md)
- [RowSplit](ts-container-rowsplit.md)
- [Scroll](ts-container-scroll.md)
- [ScrollBar](ts-basic-components-scrollbar.md)
- [SideBarContainer](ts-container-sidebarcontainer.md)
- [Stack](ts-container-stack.md)
- [Stepper](ts-basic-components-stepper.md)
- [StepperItem](ts-basic-components-stepperitem.md)
- [Swiper](ts-container-swiper.md)
- [Tabs](ts-container-tabs.md)
- [TabContent](ts-container-tabcontent.md)
......
# OpenHarmony Application Development Documentation
- [Application Development Overview](application-dev-guide.md)
- Quick Start
- [Directory Structure](quick-start/package-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md)
- Development
- [Ability Development](ability/Readme-EN.md)
- [Ability Framework Overview](ability/ability-brief.md)
- FA Model
- [FA Model Overview](ability/fa-brief.md)
- [Page Ability Development](ability/fa-pageability.md)
- [Service Ability Development](ability/fa-serviceability.md)
......@@ -15,6 +16,7 @@
- Other
- [Ability Assistant Usage](ability/ability-assistant-guidelines.md)
- [UI](ui/Readme-EN.md)
- [ArkUI Overview](arkui-overview.md)
- JavaScript-based Web-Like Development Paradigm
......@@ -130,6 +132,7 @@
- [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md)
- Basic Functions
- Window Manager
- Window
......@@ -210,10 +213,13 @@
- Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](dfx/hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](dfx/hitracechain-guidelines.md)
- Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md)
- API References
- Compent Reference (JavaScript-based Web-like Development Paradigm)
- Components
......@@ -376,6 +382,7 @@
- [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md)
- [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md)
- [Marquee](reference/arkui-ts/ts-basic-components-marquee.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [PatternLock](reference/arkui-ts/ts-basic-components-patternlock.md)
- [PluginComponent](reference/arkui-ts/ts-basic-components-plugincomponent.md)
- [Progress](reference/arkui-ts/ts-basic-components-progress.md)
......@@ -383,6 +390,7 @@
- [Radio](reference/arkui-ts/ts-basic-components-radio.md)
- [Rating](reference/arkui-ts/ts-basic-components-rating.md)
- [RichText](reference/arkui-ts/ts-basic-components-richtext.md)
- [ScrollBar](reference/arkui-ts/ts-basic-components-scrollbar.md)
- [Search](reference/arkui-ts/ts-basic-components-search.md)
- [Select](reference/arkui-ts/ts-basic-components-select.md)
- [Slider](reference/arkui-ts/ts-basic-components-slider.md)
......@@ -412,13 +420,11 @@
- [List](reference/arkui-ts/ts-container-list.md)
- [ListItem](reference/arkui-ts/ts-container-listitem.md)
- [Navigator](reference/arkui-ts/ts-container-navigator.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [Panel](reference/arkui-ts/ts-container-panel.md)
- [Refresh](reference/arkui-ts/ts-container-refresh.md)
- [Row](reference/arkui-ts/ts-container-row.md)
- [RowSplit](reference/arkui-ts/ts-container-rowsplit.md)
- [Scroll](reference/arkui-ts/ts-container-scroll.md)
- [ScrollBar](reference/arkui-ts/ts-basic-components-scrollbar.md)
- [SideBarContainer](reference/arkui-ts/ts-container-sidebarcontainer.md)
- [Stack](reference/arkui-ts/ts-container-stack.md)
- [Swiper](reference/arkui-ts/ts-container-swiper.md)
......
......@@ -384,15 +384,9 @@
- [HiSysEvent Tool Usage](subsystems/subsys-dfx-hisysevent-tool.md)
- Featured Topics
- HPM Bundle
- [Development Specifications](bundles/bundles-standard-rules.md)
- Development Guidelines
- [Bundle Development](bundles/bundles-guide-overview.md)
- [Preparations](bundles/bundles-guide-prepare.md)
- [Bundle Development](bundles/bundles-guide-develop.md)
- HPM User Guide
- [Introduction](bundles/bundles-demo-hpmdescription.md)
- [Preparations](bundles/bundles-demo-environment.md)
- [Development Example](bundles/bundles-demo-devsample.md)
- [HPM Part Overview](bundles/hpm-part-about.md)
- [HPM Part Development](bundles/hpm-part-development.md)
- [HPM Part Reference](bundles/hpm-part-reference.md)
- Device Development Examples
- [Mini- and Small-System Devices](guide/device-lite.md)
- [WLAN-connected Products](guide/device-wlan.md)
......
# Ability开发
- [Ability框架概述](ability-brief.md)
- FA模型
- [FA模型综述](fa-brief.md)
- [PageAbility开发指导](fa-pageability.md)
- [ServiceAbility开发指导](fa-serviceability.md)
- [DataAbility开发指导](fa-dataability.md)
- [FA卡片开发指导](fa-formability.md)
- Stage模型
- [Stage模型综述](stage-brief.md)
- [Ability开发指导](stage-ability.md)
- [ServiceExtensionAbility开发指导](stage-serviceextension.md)
- [跨端迁移开发指导](stage-ability-continuation.md)
- [Call调用开发指导](stage-call.md)
- [Stage卡片开发指导](stage-formextension.md)
- 其他
- [FA模型综述](fa-brief.md)
- [PageAbility开发指导](fa-pageability.md)
- [ServiceAbility开发指导](fa-serviceability.md)
- [DataAbility开发指导](fa-dataability.md)
- [FA卡片开发指导](fa-formability.md)
- 其他
- [WantAgent开发指导](wantagent.md)
- [Ability助手使用指导](ability-assistant-guidelines.md)
- [测试框架使用指导](ability-delegator.md)
# Ability框架概述
​ Ability是应用所具备能力的抽象,也是应用程序的重要组成部分。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件,一个应用可以包含一个或多个Ability。
​ Ability框架模型结构具有两种框架形态:
- 第一种形态为FA模型。API 8及其更早版本的应用程序只能使用FA模型进行开发。 FA模型将Ability分为FA(Feature Ability)和PA(Particle Ability)两种类型,其中FA支持Page Ability,PA支持Service Ability、Data Ability、以及FormAbility。
- 第二种形态为Stage模型。从API 9开始,Ability框架引入了Stage模型作为第二种应用框架形态,Stage模型将Ability分为Ability和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等等一系列ExtensionAbility,以便满足更多的使用场景。
​ Stage模型的设计,主要是为了方便开发者更加方便地开发出分布式环境下的复杂应用。下表给出了两种模型在设计上的差异:
| 对比 | FA模型 | Stage模型 |
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| 开发方式 | 提供类Web的 api,UI开发与Stage模型一致。 | 提供面向对象的开发方式,UI开发与FA模型一致。 |
| 引擎实例 | 每个进程内的每个Ability独享一个JS VM引擎实例。 | 每个进程内的多个Ability实例共享一个JS VM引擎实例。 |
| 进程内对象共享 | 不支持。 | 支持。 |
| 包描述文件 | 使用config.json描述HAP包和组件信息,组件必须使用固定的文件名。 | 使用module.json描述HAP包和组件信息,可以指定入口文件名。 |
| 组件 | 提供PageAbility(页面展示),ServiceAbility(服务),DataAbility(数据分享), FormAbility(卡片)。 | 提供Ability(页面展示)、Extension(基于场景的服务扩展)。 |
​ 除了上述设计上的差异外,对于开发者而言,两种模型的主要区别在于:
* Ability类型存在差异;
![favsstage](figures/favsstage.png)
* Ability生命周期存在差异;
![lifecycle](figures/lifecycle.png)
​ 两种模型的基本介绍,详见[FA模型综述](fa-brief.md)[Stage模型综述](stage-brief.md)
\ No newline at end of file
# FA模型综述
# Ability综述
## 整体架构
OpenHarmony用户程序的开发本质上就是开发Ability。OpenHarmony系统是通过对Ability调度,结合系统提供的一致性调度契约对Ability进行生命周期管理,从而实现对用户程序的调度。
......
# 跨端迁移开发指导
## 场景介绍
迁移的主要工作是实现将应用当前任务,包括页面控件状态变量、分布式对象等,迁移到远端设备。页面控件状态变量用于同步页面UI数据,分布式对象用于同步内存中的数据。
## 接口说明
迁移提供的能力如下,具体的API详见[接口文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-application-ability.md)
**表1** 应用迁移API接口功能介绍
|接口名 | 描述|
|:------ | :------|
| onContinue(wantParams : {[key: string]: any}): OnContinueResult | 迁移**发起端**在该回调中保存迁移所需要的数据,同时返回是否同意迁移:0表示同意,拒绝返回相应错误码。 |
| onCreate(want: Want,param:LaunchParam): void | 迁移**目标端**在该回调中完成数据恢复,并触发页面恢复。 |
| **enum** OnContinueResult | onContinue的返回值类型:AGREE表示同意;REJECT表示拒绝;MISMATCH表示版本不匹配 |
**图1** 迁移开发示意图
![continuation_dev](figures/continuation-info.png)
## 开发步骤
### 迁移应用
1. 配置
- 配置应用支持迁移
在module.json5中配置continuable字段:true表示支持迁移,false表示不支持,默认为false。配置为false的应用将被系统识别为无法迁移。
```javascript
"continuable": true
```
* 配置应用启动类型
迁移当前只支持多实例应用,需要在在module.json5中配置launchType字段为standard。
```javascript
"launchType": "standard"
```
* 申请分布式权限
支持跨端迁移的应用需要在module.json5申请分布式权限 DISTRIBUTED_DATASYNC。
```javascript
"requestPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
},
```
这个权限需要在应用首次启动的时候弹窗让用户授予,可以通过在ability的onWindowStageCreate中添加如下代码实现:
```javascript
requestPermissions = async () => {
let permissions: Array<string> = [
"ohos.permission.DISTRIBUTED_DATASYNC"
];
let needGrantPermission = false
let accessManger = accessControl.createAtManager()
Logger.info("app permission get bundle info")
let bundleInfo = await bundle.getApplicationInfo(BUNDLE_NAME, 0, 100)
Logger.info(`app permission query permission ${bundleInfo.accessTokenId.toString()}`)
for (const permission of permissions) {
Logger.info(`app permission query grant status ${permission}`)
try {
let grantStatus = await accessManger.verifyAccessToken(bundleInfo.accessTokenId, permission)
if (grantStatus === PERMISSION_REJECT) {
needGrantPermission = true
break;
}
} catch (err) {
Logger.error(`app permission query grant status error ${permission} ${JSON.stringify(err)}`)
needGrantPermission = true
break;
}
}
if (needGrantPermission) {
Logger.info("app permission needGrantPermission")
try {
await this.context.requestPermissionsFromUser(permissions)
} catch (err) {
Logger.error(`app permission ${JSON.stringify(err)}`)
}
} else {
Logger.info("app permission already granted")
}
}
```
2. 实现onContinue接口
onContinue接口在**发起端**被调用,主要用于在迁移发起时,通知开发者保存控件状态变量和内存中数据,准备迁移。当应用准备完成后,需要返回OnContinueResult.AGREE(0)表示同意迁移,否则返回相应的错误码拒绝迁移。如果不实现该接口,系统将默认为拒绝迁移。
导入模块
```javascript
import Ability from '@ohos.application.Ability';
import AbilityConstant from '@ohos.application.AbilityConstant';
```
- 要实现迁移,此接口必须实现并返回AGREE,否则默认为拒绝迁移。
- 示例
```javascript
onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject")
// set user input data into want params
wantParam["input"] = AppStorage.Get<string>('ContinueInput');
Logger.info(`onContinue input = ${wantParam["input"]}`);
return AbilityConstant.OnContinueResult.AGREE
}
```
3. 在onCreate接口中实现迁移逻辑
onCreate接口在迁移**目标端**被调用,在目标端ability被拉起时,通知开发者同步已保存的内存数据和控件状态,完成后触发页面的恢复。如果不实现该接口中迁移相关逻辑,ability将会作为普通的启动方式拉起,无法恢复页面。
- 远端设备上,在onCreate中根据launchReason判断该次启动是否为迁移LaunchReason.CONTINUATION
- 完成数据恢复后,开发者需要调用**restoreWindowStage**来触发页面恢复。
* 示例
```javascript
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
let input = want.parameters.input // get user data from want params
AppStorage.SetOrCreate<string>('ContinueInput', input)
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
this.contentStorage = new ContentStorage();
this.context.restoreWindowStage(this.contentStorage);
}
}
```
### 迁移数据
1. 使用分布式对象
分布式数据对象提供了与本地变量类似的操作,实现两个设备的数据同步,当设备1的应用A的分布式数据对象增、删、改数据后,设备2的应用A也可以获取到对应的数据变化,同时还能监听数据变更以及对端数据对象的上下线。用法详见[分布式对象指导文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/database/database-distributedobject-guidelines.md)
迁移场景中,分布式对象(distributedDataObject)主要用于将本机内存数据同步到目标设备。
- 发起端在onContinue中,将待迁移的数据存入分布式对象中,然后设置好session id,并通过wantParams将session id传到远端设备。
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability {
contentStorage : ContenStorage
sessionId : string;
onContinue(wantParam : {[key: string]: any}) {
Logger.info("onContinue using distributedObject")
this.sessionId = distributedObject.genSessionId();
//set distributed data object session id
g_object.setSessionId(this.sessionId);
g_object.name = "Amy";
// set session id into want params
wantParam["session"] = this.sessionId;
return AbilityConstant.OnContinueResult.AGREE
}
```
- 目标设备在onCreate中,取出发起端传过来的session id,建立分布式对象并关联该session id,这样就能实现分布式对象的同步。需要注意的是,在调用restoreWindowStage之前,迁移需要的分布式对象必须全部关联完,保证能够获取到正确的数据。
```javascript
import Ability from '@ohos.application.Ability';
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:undefined});
export default class MainAbility extends Ability {
contentStorage : ContentStorage
sessionId : string;
statusCallback(sessionId, networkid, status) {
Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`)
}
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
// get distributed data object session id from want params
this.sessionId = want.parameters.session
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
g_object.on("status", this.statusCallback);
// set session id, so it will sync data from remote device
g_object.setSessionId(this.sessionId);
this.contentStorage = new ContentStorage();
this.context.restoreWindowStage(this.contentStorage);
}
}
}
```
以上完整的示例见sample
# Ability开发指导
## 场景介绍
Stage模型是基于API version 9的应用开发模型,对此模型的介绍详见[Stage模型综述](stage-brief.md)。基于Stage模型的Ability应用开发,主要涉及如下功能逻辑:
- 创建Page Ability应用,如视频播放、新闻资讯等,需要通过屏幕进行浏览的应用,以及支持人机交互。
- 获取Ability的配置信息,如ApplicationInfo、AbilityInfo及HapModuleInfo等。
- 启动/带参数启动/带返回结果启动/带AccountId启动其他Ability。
- 应用向用户申请授权。
- 系统环境变化通知给AbilityStage及Ability。
- 通用组件Call功能,详见[Call调用开发指导](stage-call.md)
- 连接ServiceAbility,与ServiceAbility断开连接,详见[ServiceExtensionAbility开发指导](stage-serviceextension.md)
- 应用迁移,详见[应用迁移开发指导](stage-ability-continuation.md)
## 接口说明
AbilityStage功能如下(AbilityStage类,拥有context属性,具体的API详见[接口文档](../reference/apis/js-apis-application-abilitystage.md)):
**表1** AbilityStage API接口功能介绍
|接口名|描述|
|:------|:------|
|void onCreate()|AbilityStage初始化时被调用。|
|string onAcceptWant(want: Want)|启动指定Ability时被调用。|
|void onConfigurationUpdated(config: Configuration)|全局配置发生变更时被调用。|
Ability功能如下(Ability类,具体的API详见[接口文档](../reference/apis/js-apis-application-ability.md)):
**表2** Ability API接口功能介绍
|接口名|描述|
|:------|:------|
|void onCreate(want: Want, param: AbilityConstant.LaunchParam)|Ability生命周期回调,Ability启动时被调用。|
|void onDestroy()|Ability生命周期回调,Ability销毁时被调用。|
|void onWindowStageCreate(windowStage: window.WindowStage)|Ability生命周期回调,创建window stage时被调用,应用开发者可通过window.WindowStage的接口执行页面加载等操作。|
|void onWindowStageDestroy()|Ability生命周期回调,销毁window stage时被调用。|
|void onForeground()|Ability生命周期回调,Ability切换至前台时被调用。|
|void onBackground()|Ability生命周期回调,Ability切换至后台时被调用。|
|void onNewWant(want: Want)|Ability回调,Ability的启动模式设置为单例时被调用。|
|void onConfigurationUpdated(config: Configuration)|Ability回调,Ability的系统配置更新时被调用。|
Ability类拥有context属性,context属性为AbilityContext类,AbilityContext类拥有abilityInfo、currentHapModuleInfo等属性,具体的API详见[接口文档](../reference/apis/js-apis-ability-context.md)
**表3** AbilityContext API接口功能介绍
|接口名|描述|
|:------|:------|
|void startAbility(want: Want, callback: AsyncCallback<void>)|启动Ability。|
|void startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>)|启动Ability。|
|void startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback<void>)|带AccountId启动Ability。|
|void startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback<void>)|带AccountId启动Ability。|
|void startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>)|带返回结果启动Ability。|
|void startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>)|带返回结果启动Ability。|
|void startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback<AbilityResult>)|带返回结果及AccountId启动Ability。|
|void startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback<void>)|带返回结果及AccountId启动Ability。|
|void terminateSelf(callback: AsyncCallback<void>)|销毁当前的Page Ability。|
|void terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>)|带返回结果销毁当前的Page Ability。|
## 开发步骤
### 创建Page Ability应用
创建Stage模型的Page Ability应用,需实现AbilityStage接口及Ability生命周期接口,并使用窗口提供的方法设置页面。具体示例代码如下:
1. 导入AbilityStage模块。
```
import AbilityStage from "@ohos.application.AbilityStage"
```
2. 实现AbilityStage接口。
```ts
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
}
}
```
3. 导入Ability模块。
```js
import Ability from '@ohos.application.Ability'
```
4. 实现Ability生命周期接口。
`onWindowStageCreate(windowStage)`中通过loadContent接口设置应用要加载的页面,window接口的使用详见[窗口开发指导](../windowmanager/window-guidelines.md)
```ts
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("MainAbility onCreate")
}
onDestroy() {
console.log("MainAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => {
console.log("MainAbility load content succeed with data: " + JSON.stringify(data))
}).catch((error) => {
console.error("MainAbility load content failed with error: "+ JSON.stringify(error))
})
}
onWindowStageDestroy() {
console.log("MainAbility onWindowStageDestroy")
}
onForeground() {
console.log("MainAbility onForeground")
}
onBackground() {
console.log("MainAbility onBackground")
}
}
```
### 获取AbilityStage及Ability的配置信息
AbilityStage类及Ability类均拥有context属性,应用可以通过`this.context`获取Ability实例的上下文,进而获取详细的配置信息。如下示例展示了AbilityStage通过context属性获取包代码路径、hap包名、ability名以及系统语言的方法。具体示例代码如下:
```ts
import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
let context = this.context
console.log("MyAbilityStage bundleCodeDir" + context.bundleCodeDir)
let currentHapModuleInfo = context.currentHapModuleInfo
console.log("MyAbilityStage hap module name" + currentHapModuleInfo.name)
console.log("MyAbilityStage hap module mainAbilityName" + currentHapModuleInfo.mainAbilityName)
let config = this.context.config
console.log("MyAbilityStage config language" + config.language)
}
}
```
如下示例展示了Ability通过context属性获取包代码路径、hap包名、ability名以及系统语言的方法。具体示例代码如下:
```ts
import Ability from '@ohos.application.Ability'
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("MainAbility onCreate")
let context = this.context
console.log("MainAbility bundleCodeDir" + context.bundleCodeDir)
let abilityInfo = this.context.abilityInfo;
console.log("MainAbility ability bundleName" + abilityInfo.bundleName)
console.log("MainAbility ability name" + abilityInfo.name)
let config = this.context.config
console.log("MyAbilityStage config language" + config.language)
}
}
```
### 启动Ability
应用可以通过`this.context`获取Ability实例的上下文,进而使用AbilityContext中的StartAbility相关接口启动Ability。启动Ability可指定Want、StartOptions、accountId,通过callback形式或promise形式实现。具体示例代码如下:
```ts
let context = this.context
var want = {
"deviceId": "",
"bundleName": "com.example.MyApplication",
"abilityName": "MainAbility"
};
var options = {
windowMode: 0,
displayId: 2
};
context.startAbility(want, options).then((data) => {
console.log("Succeed to start ability with data: " + JSON.stringify(data))
}).catch((error) => {
console.error("Failed to start ability with error: "+ JSON.stringify(error))
})
```
### 跨设备启动Ability(当前仅对系统应用开放)
>说明:由于DeviceManager的getTrustedDeviceListSync接口仅对系统应用开放,当前跨设备启动Ability仅支持系统应用
跨设备场景下,需指定对端设备deviceId,具体示例代码如下:
```ts
let context = this.context
var want = {
"deviceId": getRemoteDeviceId(),
"bundleName": "com.example.MyApplication",
"abilityName": "MainAbility"
};
context.startAbility(want).then((data) => {
console.log("Succeed to start remote ability with data: " + JSON.stringify(data))
}).catch((error) => {
console.error("Failed to start remote ability with error: "+ JSON.stringify(error))
})
```
从DeviceManager获取指定设备的deviceId。具体示例代码如下:
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) {
var list = dmClass.getTrustedDeviceListSync();
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
return;
}
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
return list[0].deviceId;
} else {
console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
}
}
```
### 应用向用户申请授权
应用需要某些权限如存储、位置信息、访问日历时,需要向用户申请授权。明确需要申请的权限后,在`module.json`中添加待申请的权限,同时通过接口`requestPermissionsFromUser`以动态弹窗的方式向用户申请授权。以访问日历为例,具体示例代码如下:
module.json的修改:
```json
"requestPermissions": [
{
"name": "ohos.permission.READ_CALENDAR"
}
]
```
通过动态弹窗向用户申请授权:
```ts
let context = this.context
let permissions: Array<string> = ['ohos.permission.READ_CALENDAR']
context.requestPermissionsFromUser(permissions).then((data) => {
console.log("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => {
console.log("Failed to request permission from user with error: "+ JSON.stringify(error))
})
```
在跨设备场景下,需要向用户申请数据同步的权限。具体示例代码如下:
```ts
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
console.log("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => {
console.log("Failed to request permission from user with error: "+ JSON.stringify(error))
})
```
### 系统环境变化通知给AbilityStage及Ability
全局配置,比如系统语言和颜色模式发生变化时,通过`onConfigurationUpdated`接口通知给AbilityStage和Ability。系统应用可以通过`updateConfiguration`接口更新系统语言和颜色模式。如下示例展示了AbilityStage的`onConfigurationUpdated`回调实现,系统语言和颜色模式发生变化时触发该回调。具体示例代码如下:
```ts
import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
export default class MyAbilityStage extends AbilityStage {
onConfigurationUpdated(config) {
console.log("MyAbilityStage onConfigurationUpdated")
console.log("MyAbilityStage config language" + config.language)
console.log("MyAbilityStage config colorMode" + config.colorMode)
}
}
```
如下示例展示了Ability的`onConfigurationUpdated`回调实现,系统语言、颜色模式以及Display相关的参数,比如方向、Density,发生变化时触发该回调。具体示例代码如下:
```ts
import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
export default class MainAbility extends Ability { {
onConfigurationUpdated(config) {
console.log("MainAbility onConfigurationUpdated")
console.log("MainAbility config language" + config.language)
console.log("MainAbility config colorMode" + config.colorMode)
console.log("MainAbility config direction" + config.direction)
console.log("MainAbility config screenDensity" + config.screenDensity)
console.log("MainAbility config displayId" + config.displayId)
}
}
```
## 开发实例
针对Stage模型Ability开发,有以下示例工程可供参考:
[eTSStageCallAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/eTSStageCallAbility)
本示例eTSStageCallAbility中,在Application目录的AbilityStage.ts中实现AbilityStage的接口,在MainAbility目录实现Ability的接口并设置"pages/index"为Ability的页面,在CalleeAbility目录实现另一个Ability并设置"pages/second"为Ability的页面。支持MainAbility启动CalleeAbility。
# Stage模型综述
### 设计思想
​ Stage模型的设计,主要是为了解决FA模型无法解决的开发场景问题,方便开发者更加方便地开发出分布式环境下的复杂应用。
​ Stage模型的设计思想如下图所示。
![stagedesign](figures/stagedesign.png)
​ Stage模型的设计基于如下三个出发点:
- **应用的能力与系统总体功能和功耗的平衡**
​ 在系统运行过程中,前台应用的资源占用会被优先保障,与此同时由于应用能力不同而产生的功耗,也需要符合系统整体功耗的要求。Stage模型通过Ability与UI分离、严格的后台管控、基于场景的服务机制及单进程模型来达成这种应用能力与整体系统功耗的平衡。
- **原生支持组件级的迁移和协同**
​ OpenHarmony是原生支持分布式的操作系统,应用框架需要从架构设计上使得组件更易于实现迁移和协同。Stage模型通过Ability与UI分离及UI展示与服务能力合一等模型特性,实现这一设计目标。
- **支持多设备和多窗口形态的特点**
​ 为了支持多种设备形态和更易于实现多种不同的窗口形态,需要组件管理服务和窗口管理服务在架构层面上是解耦的,从而方便裁剪,更有利于定制不同的窗口形态。Stage模型通过重新定义了Ability生命周期定义和设计组件管理服务和窗口管理服务的单项依赖解决这一问题。
### 基本概念
​ 下图展示了Stage模型中的基本概念。
![stageconcept](figures/stageconcept.png)
- **HAP**:即HarmonyAbilityPackage,OpenHarmony应用编译、分发、加载的基本单位,也称为module,每个HAP都有一个应用内唯一的名称,成为moduleName;
- **Bundle**:通过appid标识的OpenHarmony应用,Bundle可以包含多个HAP,每个应用都有一个bundleName,但是bundleName并不能唯一标识一个应用,appid中包含bundleName以及其他的更多信息,能够唯一标识一个应用;
- **AbilityStage**:对应HAP的运行期类,在HAP首次加载到进程中时创建,运行期开发者可见;
- **Application**:对应Bundle的运行期类,运行期开发者不可见;
- **Context**:提供运行期开发者可以调用的各种能力,Ability组件和各种ExtensionAbility都有各自不同的context类,他们都继承自基类Context,基类提供包名、moduleName、路径等信息;
- **Ability**:提供生命周期回调,持有AbilityContext,支持组件迁移/协同;
- **ExtensionAbility**:基于场景的服务扩展能力统称,系统定义了多种基于场景的ExtensionAbility类,它们持有各自的ExtensionAbilityContext;
- **WindowStage**:本地窗口管理器;
- **Window**:窗口 管理器管理的基本单元,持有一个ArkUI引擎实例;
- **Ark UI Page**:Ark声明式UI展示。
### 生命周期
​ Ability及AbilityStage的生命周期是应用的基本流程中最重要的概念。在[Ability框架概述](ability-brief.md)中,给出了FA模型与Stage模型的生命周期对比,这里重点对Ability生命周期切换以及和AbilityStage、WindowStage之间的调度关系进行介绍。
![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png)
​ 为了实现多设备形态上的裁剪和多窗口的可扩展性,OpenHarmony对组件管理和窗口管理进行了解耦。Stage模型定义Ability组件的生命周期,只包含创建、销毁、前后台等状态,而将与界面相关内容强相关的获焦、失焦状态放在WindowStage之中,从而实现Ability与窗口之间的弱耦合;在服务侧,窗口管理服务依赖于组件管理服务,前者通知后者前后台变化,这样组件管理服务仅感知前后台变化,不感知焦点变化。
### ExtensionAbility机制
​ 不同于用于页面展示的Ability,ExtensionAbility提供的是一种受限的服务运行环境。ExtensionAbility具有如下特点:
- 独立于主进程的单独进程运行,与主进程无IPC,共享一个存储沙箱;
- 独立的Context提供基于业务场景的api能力;
- 由系统触发创建,应用不能直接创建;
- ExtensionAbility和进程的生命周期受系统管理。
​ 下图以卡片服务使用场景为例进行展示,系统提供了FormExtensionAbility基类,开发者通过派生提供卡片的具体信息。FormExtensionAbility实例及其所在的ExtensionAbility进程的整个生命周期,都是由系统服务FormManagerService进行管理。
![ExtensionAbility](figures/ExtensionAbility.png)
### 进程模型
​ OpenHarmony系统中的应用均满足单进程模型。所谓的单进程模型,是指不允许应用配置多进程,应用中所有的进程都是由系统创建和管理的。每个应用至多并存三类进程:
- 主进程:运行所有的Ability组件、页面和业务逻辑;
- Extension进程:运行应用中的ExtensionAbility派生类,该进程由系统中的特定场景的服务管理其生命周期;
- Render进程:专门为webview创建的进程,用于加载webview的渲染库。
下图展示了应用的进程模型。
![stageprocessmodel](figures/stageprocessmodel.png)
# Call调用开发指导
## 场景介绍
Ability Call调用是Ability能力的扩展,它为Ability提供一种能够被外部调用的能力。使Ability既能被拉起到前台展示UI,也支持Ability在后台被创建并运行。应用开发者可通过Call调用,使用IPC通信实现不同Ability之间的数据共享。Call调用的场景主要包括:
- 创建Callee被调用端。
- 访问Callee被调用端。
本文中的Caller和Callee分别表示调用者和被调用者,Call调用流程示意图如下。
![stage-call](figures/stage-call.png)
## 接口说明
Caller及Callee功能如下:具体的API详见[接口文档](../reference/apis/js-apis-application-ability.md#caller)
**表1** Call API接口功能介绍
|接口名|描述|
|:------|:------|
|Promise<Caller> startAbilityByCall(want: Want)|获取指定通用组件的Caller通信接口,拉起指定通用组件并将其切换到后台。|
|void on(method: string, callback: CaleeCallBack)|Callee.on,通用组件Callee注册method对应的callback方法。|
|void off(method: string)|Callee.off,通用组件Callee去注册method的callback方法。|
|Promise<void> call(method: string, data: rpc.Sequenceable)|Caller.call,向通用组件Callee发送约定序列化数据。|
|Promise<rpc.MessageParcel> callWithResult(method: string, data: rpc.Sequenceable)|Caller.callWithResult,向通用组件Callee发送约定序列化数据, 并将返回的约定序列化数据带回。|
|void release()|Caller.release,释放通用组件的Caller通信接口。|
|void onRelease(callback: OnReleaseCallBack)|Caller.onRelease,注册通用组件通信断开监听通知。|
## 开发步骤
### 创建Callee被调用端
Callee被调用端,需要实现指定方法的数据接收回调函数、数据的序列化及反序列化方法。在需要接收数据期间,通过on接口注册监听,无需接收数据时通过off接口解除监听。
1. 配置Ability的启动模式
配置module.json5,将Callee被调用端所在的Ability配置为单实例"singleton"。
|Json字段|字段说明|
|:------|:------|
|"launchType"|Ability的启动模式,设置为"singleton"类型 |
Ability配置标签示例如下:
```json
"abilities":[{
"name": ".CalleeAbility",
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"launchType": "singleton",
"description": "$string:CalleeAbility_desc",
"icon": "$media:icon",
"label": "$string:CalleeAbility_label",
"visible": true
}]
```
2. 导入Ability模块
```
import Ability from '@ohos.application.Ability'
```
3. 定义约定的序列化数据
调用端及被调用端发送接收的数据格式需协商一致,如下示例约定数据由number和string组成。具体示例代码如下:
```ts
export default class MySequenceable {
num: number = 0
str: String = ""
constructor(num, string) {
this.num = num
this.str = string
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num)
messageParcel.writeString(this.str)
return true
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt()
this.str = messageParcel.readString()
return true
}
}
```
4. 实现Callee.on监听及Callee.off解除监听
被调用端Callee的监听函数注册时机, 取决于应用开发者。注册监听之前的数据不会被处理,取消监听之后的数据不会被处理。如下示例在Ability的onCreate注册'CalleeSortMethod'监听,在onDestroy取消监听,收到序列化数据后作相应处理并返回,应用开发者根据实际需要做相应处理。具体示例代码如下:
```ts
const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg'
function sendMsgCallback(data) {
Logger.log(TAG, 'CalleeSortFunc called')
// 获取Caller发送的序列化数据
let receivedData = new MySequenceable(0, '')
data.readSequenceable(receivedData)
Logger.log(TAG, `receiveData[${receivedData.num}, ${receivedData.str}]`)
// 作相应处理
// 返回序列化数据result给Caller
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`)
}
export default class CalleeAbility extends Ability {
onCreate(want, launchParam) {
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
} catch (error) {
Logger.error(TAG, `${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
}
}
onDestroy() {
try {
this.callee.off(MSG_SEND_METHOD)
} catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`)
}
}
}
```
### 访问Callee被调用端
1. 导入Ability模块
```
import Ability from '@ohos.application.Ability'
```
2. 获取Caller通信接口
Ability的context属性实现了startAbilityByCall方法,用于获取指定通用组件的Caller通信接口。如下示例通过`this.context`获取Ability实例的context属性,使用startAbilityByCall拉起Callee被调用端并获取Caller通信接口,注册Caller的onRelease监听。应用开发者根据实际需要做相应处理。具体示例代码如下:
```ts
async onButtonGetCaller() {
try {
this.caller = await context.startAbilityByCall({
bundleName: 'com.samples.CallApplication',
abilityName: 'CalleeAbility'
})
if (this.caller === undefined) {
Logger.error(TAG, 'get caller failed')
return
}
Logger.log(TAG, 'get caller success')
this.regOnRelease(this.caller)
} catch (error) {
Logger.error(TAG, `get caller failed with ${error}`)
}
}.catch((error) => {
console.error(TAG + 'get caller failed with ' + error)
})
```
在跨设备场景下,需指定对端设备deviceId。具体示例代码如下:
```ts
let TAG = '[MainAbility] '
var caller = undefined
let context = this.context
context.startAbilityByCall({
deviceId: getRemoteDeviceId(),
bundleName: 'com.samples.CallApplication',
abilityName: 'CalleeAbility'
}).then((data) => {
if (data != null) {
caller = data
console.log(TAG + 'get remote caller success')
// 注册caller的release监听
caller.onRelease((msg) => {
console.log(TAG + 'remote caller onRelease is called ' + msg)
})
console.log(TAG + 'remote caller register OnRelease succeed')
}
}).catch((error) => {
console.error(TAG + 'get remote caller failed with ' + error)
})
```
从DeviceManager获取指定设备的deviceId,getTrustedDeviceListSync接口仅对系统应用开放。具体示例代码如下:
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass;
function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) {
var list = dmClass.getTrustedDeviceListSync();
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
return;
}
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
return list[0].deviceId;
} else {
console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
}
}
```
在跨设备场景下,需要向用户申请数据同步的权限。具体示例代码如下:
```ts
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
console.log("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => {
console.log("Failed to request permission from user with error: "+ JSON.stringify(error))
})
```
3. 发送约定序列化数据
向被调用端发送Sequenceable数据有两种方式,一种是不带返回值,一种是获取被调用端返回的数据,method以及序列化数据需要与被调用端协商一致。如下示例调用Call接口,向Calee被调用端发送数据。具体示例代码如下:
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'
async onButtonCall() {
try {
let msg = new MySequenceable(1, 'origin_Msg')
await this.caller.call(MSG_SEND_METHOD, msg)
} catch (error) {
Logger.error(TAG, `caller call failed with ${error}`)
}
}
```
如下示例调用CallWithResult接口,向Calee被调用端发送待处理的数据`originMsg`,并将'CallSendMsg'方法处理完毕的数据赋值给`backMsg`。具体示例代码如下:
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = ''
backMsg: string = ''
async onButtonCallWithResult(originMsg, backMsg) {
try {
let msg = new MySequenceable(1, originMsg)
const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg)
Logger.log(TAG, 'caller callWithResult succeed')
let result = new MySequenceable(0, '')
data.readSequenceable(result)
backMsg(result.str)
Logger.log(TAG, `caller result is [${result.num}, ${result.str}]`)
} catch (error) {
Logger.error(TAG, `caller callWithResult failed with ${error}`)
}
}
```
4. 释放Caller通信接口
Caller不再使用后,应用开发者可以通过release接口释放Caller。具体示例代码如下:
```ts
try {
this.caller.release()
this.caller = undefined
Logger.log(TAG, 'caller release succeed')
} catch (error) {
Logger.error(TAG, `caller release failed with ${error}`)
}
```
## 开发实例
针对Stage模型本地Call功能开发,有以下示例工程可供参考:
[eTSStageCallAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/eTSStageCallAbility)
本示例eTSStageCallAbility中,在Application目录的AbilityStage.ts中实现AbilityStage的接口,在MainAbility目录实现Ability的接口并设置"pages/index"为Ability的页面,在CaleeAbility目录实现Ability的接口、Callee被调用端,设置"pages/second"为Ability的页面。MainAbility作为调用端,CalleeAbility作为被调用端。MainAbility拉起CalleeAbility,获取Caller通信接口后,支持用户输入字符串,做序列化处理后传递给CaleeAbility处理,CaleeAbility根据收到的数据做页面刷新并返回结果给MainAbility。
# ServiceExtensionAbility开发指导
## 场景介绍
ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用于处理无界面的任务,生命周期较简单,没有前后台生命周期。ServiceExtensionAbility是ExtensionAbility的扩展类。
开发者可以自定义类继承ServiceExtensionAbility,通过重写基类中相关生命周期方法,来做初始化、连接中、断开连接时相关业务逻辑操作。
## 接口说明
**表1** ServiceExtensionAbility中相关生命周期功能介绍
|接口名|描述|
|:------|:------|
|onCreate|首次调用startAbility、connectAbility时触发,开发者可以进行初始化操作。|
|onRequest|每次调用startAbility都会触发,首次调用时startId为1,重复调用startAbility递增。|
|onConnect|调用connectAbility触发,重复调用不会再次触发,除非调用disconnectAbility解除绑定后再调用;onConnect返回一个进程通信类RemoteObject。|
|onDisconnect|调用disconnectAbility触发,Extension如果是用connectAbility拉起的,并且已经没有其他应用绑定这个Extension,则会触发onDestroy生命周期销毁组件。|
|onDestroy|调用停止当前ability接口terminateSelf会触发。|
## 约束与限制
- OpenHarmony当前不支持三方应用创建ServiceExtensionAbility。
## 开发步骤
1.创建ServiceExtensionAbility
开发者在创建TS文件中自定义类继承ServiceExtensionAbility,重写基类回调函数,示例如下:
```js
import rpc from '@ohos.rpc'
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
}
}
class ServiceExt extends ServiceExtensionAbility {
onCreate(want) {
console.log('onCreate, want:' + want.abilityName);
}
onRequest(want, startId) {
console.log('onRequest, want:' + want.abilityName);
}
onConnect(want) {
console.log('onConnect , want:' + want.abilityName);
return new StubTest("test");
}
onDisconnect(want) {
console.log('onDisconnect, want:' + want.abilityName);
}
onDestroy() {
console.log('onDestroy');
}
}
```
2.注册ServiceExtensionAbility
需要在应用配置文件module.json中进行注册,注册类型type需要设置为service。
**module.json配置样例**
```json
"extensionAbilities":[{
"name": "ServiceExtAbility",
"icon": "$media:icon",
"description": "service",
"type": "service",
"visible": true,
"srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
}]
```
## 开发实例
针对ServiceExtensionAbility开发,有以下示例工程可供参考:
- [ServiceExtensionAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/eTSServiceExtAbility)
本示例ServiceExtensionAbility中:
在ServiceExtensionAbility目录中的ServiceExtAbility.ts文件创建一个ServiceExtensionAbility实例。
......@@ -18,7 +18,7 @@
首先,提供了支撑OpenHarmony应用的两个重要框架:
- 应用程序的框架:[Ability开发](ability/ability-brief.md)
- 应用程序的框架:[Ability开发](ability/fa-brief.md)
- UI的框架:[UI开发](ui/arkui-overview.md)
所有应用都应该在这两个框架的基础之上进行功能的开发。
......
......@@ -14,19 +14,11 @@
- 开发
- [Ability开发](ability/Readme-CN.md)
- [Ability框架概述](ability/ability-brief.md)
- FA模型
- [FA模型综述](ability/fa-brief.md)
- [PageAbility开发指导](ability/fa-pageability.md)
- [ServiceAbility开发指导](ability/fa-serviceability.md)
- [DataAbility开发指导](ability/fa-dataability.md)
- [FormAbility开发指导](ability/fa-formability.md)
- Stage模型
- [Stage模型综述](ability/stage-brief.md)
- [Ability开发指导](ability/stage-ability.md)
- [ServiceExtensionAbility开发指导](ability/stage-serviceextension.md)
- [FormExtensionAbility开发指导](ability/stage-formextension.md)
- [应用迁移开发指导](ability/stage-ability-continuation.md)
- 其他
- [WantAgent使用指导](ability/wantagent.md)
- [Ability助手使用指导](ability/ability-assistant-guidelines.md)
......@@ -429,6 +421,7 @@
- [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md)
- [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md)
- [Marquee](reference/arkui-ts/ts-basic-components-marquee.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [PatternLock](reference/arkui-ts/ts-basic-components-patternlock.md)
- [PluginComponent](reference/arkui-ts/ts-basic-components-pluginComponent.md)
- [Progress](reference/arkui-ts/ts-basic-components-progress.md)
......@@ -436,6 +429,7 @@
- [Radio](reference/arkui-ts/ts-basic-components-radio.md)
- [Rating](reference/arkui-ts/ts-basic-components-rating.md)
- [RichText](reference/arkui-ts/ts-basic-components-richtext.md)
- [ScrollBar](reference/arkui-ts/ts-basic-components-scrollbar.md)
- [Search](reference/arkui-ts/ts-basic-components-search.md)
- [Select](reference/arkui-ts/ts-basic-components-select.md)
- [Slider](reference/arkui-ts/ts-basic-components-slider.md)
......@@ -464,13 +458,11 @@
- [List](reference/arkui-ts/ts-container-list.md)
- [ListItem](reference/arkui-ts/ts-container-listitem.md)
- [Navigator](reference/arkui-ts/ts-container-navigator.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [Panel](reference/arkui-ts/ts-container-panel.md)
- [Refresh](reference/arkui-ts/ts-container-refresh.md)
- [Row](reference/arkui-ts/ts-container-row.md)
- [RowSplit](reference/arkui-ts/ts-container-rowsplit.md)
- [Scroll](reference/arkui-ts/ts-container-scroll.md)
- [ScrollBar](reference/arkui-ts/ts-basic-components-scrollbar.md)
- [SideBarContainer](reference/arkui-ts/ts-container-sidebarcontainer.md)
- [Stack](reference/arkui-ts/ts-container-stack.md)
- [Swiper](reference/arkui-ts/ts-container-swiper.md)
......@@ -641,4 +633,3 @@
- [非线性容器LightWeightSet](reference/apis/js-apis-lightweightset.md)
- 定制管理
- [配置策略](reference/apis/js-apis-config-policy.md)
\ No newline at end of file
- [企业设备管理](reference/apis/js-apis-enterprise-device-manager.md)
\ No newline at end of file
......@@ -8,6 +8,8 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以
在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioCapturer的状态变更。因为针对AudioCapturer的某些操作,仅在音频采集器在固定状态时才能执行。如果应用在音频采集器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。
详细API含义可参考:[音频管理API文档AudioCapturer](../reference/apis/js-apis-audio.md)
## 开发步骤
1. 使用createAudioCapturer()创建一个AudioCapturer实例。
......
......@@ -16,7 +16,7 @@
## 开发步骤
详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
详细API含义可参考:[媒体服务API文档AudioPlayer](../reference/apis/js-apis-media.md)
### 全流程场景
......
......@@ -16,7 +16,7 @@
## 开发步骤
详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
详细API含义可参考:[媒体服务API文档AudioRecorder](../reference/apis/js-apis-media.md)
### 全流程场景
......
......@@ -16,7 +16,7 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可
### 异步操作
为保证UI线程不被阻塞,大部分AudioRenderer调用都是异步的。对于每个API均提供了callback函数和Promise函数,以下示例均采用Promise函数,更多方式可参考[js-apis-audio](../reference/apis/js-apis-audio.md#audiorenderer8)
为保证UI线程不被阻塞,大部分AudioRenderer调用都是异步的。对于每个API均提供了callback函数和Promise函数,以下示例均采用Promise函数,更多方式可参考[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8)
## 开发步骤
......
......@@ -4,12 +4,10 @@
图片开发的主要工作是将获取到的图片进行解码,将解码后的pixelmap编码成支持的格式,本文将对图片的解码、编码等场景开发进行介绍说明。
## 接口说明
详细API含义请参考[js-apis-image.md](../reference/apis/js-apis-image.md)
## 开发步骤
详细API含义请参考:[图片处理API文档](../reference/apis/js-apis-image.md)
### 全流程场景
包含流程:创建实例,读取图片信息,读写pixelmap,更新数据,打包像素,释放资源等流程。
......
......@@ -35,7 +35,7 @@
## 开发步骤
详细API含义可参考:[js-apis-media.md](../reference/apis/js-apis-media.md)
详细API含义可参考:[媒体服务API文档VideoPlayer](../reference/apis/js-apis-media.md)
### 全流程场景
......
......@@ -83,12 +83,9 @@
- 资源调度
- [@ohos.backgroundTaskManager (后台任务管理)](js-apis-backgroundTaskManager.md)
- [@ohos.workScheduler (延迟任务调度)](js-apis-workScheduler.md)
- [@ohos.WorkSchedulerExtensionAbility (延迟任务调度回调)](js-apis-workScheduler.md)
- 定制管理
- [@ohos.configPolicy (配置策略)](js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager (企业设备管理)](js-apis-enterprise-device-manager.md)
- 安全
- [@ohos.abilityAccessCtrl (访问控制管理)](js-apis-abilityAccessCtrl.md)
......
# 延迟任务调度回调
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
```
## WorkSchedulerExtensionAbility.onWorkStart
onWorkStart(work: workScheduler.WorkInfo): void
延迟任务调度开始回调。
**系统能力:** SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ---- | --------------------- | ---- | -------------- |
| work | [workScheduler.WorkInfo](js-apis-workScheduler.md#workinfo) | 是 | 指示要添加到执行队列的工作。 |
**示例:**
```
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
}
}
```
## WorkSchedulerExtensionAbility.onWorkStop
onWorkStop(work: workScheduler.WorkInfo)
延迟任务调度结束回调。
**系统能力:** SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ---- | --------------------- | ---- | -------------- |
| work | [workScheduler.WorkInfo](js-apis-workScheduler.md#workinfo) | 是 | 指示要添加到执行队列的工作。 |
**示例:**
```
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStop(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
}
}
```
\ No newline at end of file
# 延迟任务调度
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```
import workScheduler from '@ohos.workScheduler'
```
## workScheduler.startWork
startWork(work: WorkInfo): boolean
通知WorkSchedulerService将工作添加到执行队列。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ---- | --------------------- | ---- | -------------- |
| work | [WorkInfo](#workinfo) | 是 | 指示要添加到执行队列的工作。 |
**返回值**
| 类型 | 说明 |
| ------- | -------------------------------- |
| boolean | 如果工作成功添加到执行队列,则返回true,否则返回false。 |
**示例**
```
let workInfo = {
workId: 1,
batteryLevel:50,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension"
}
var res = workScheduler.startWork(workInfo);
console.info("workschedulerLog res:" + res);
```
## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): boolean
通知WorkSchedulerService停止指定工作。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | --------------------- | ---- | ---------- |
| work | [WorkInfo](#workinfo) | 是 | 指示要停止的工作。 |
| needCancel | boolean | 是 | 是否需要取消的工作。 |
**返回值**
| 类型 | 说明 |
| ------- | ----------------------- |
| boolean | 如果成功,则返回true,否则返回false。 |
**示例**
```
let workInfo = {
workId: 1,
batteryLevel:50,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension"
}
var res = workScheduler.stopWork(workInfo, false);
console.info("workschedulerLog res:" + res);
```
## workScheduler.getWorkStatus
getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void
获取工作的最新状态,使用Callback形式返回。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId | number | 是 | work的id。 |
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | 是 | 指定的callback回调方法。如果指定的工作Id有效,则返回从WorkSchedulerService获取的有效工作状态;否则返回null。 |
**示例**
```
workScheduler.getWorkStatus(50, (err, res) => {
if (err) {
console.info('workschedulerLog getWorkStatus failed, because:' + err.data);
} else {
for (let item in res) {
console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
}
}
});
```
## workScheduler.getWorkStatus
getWorkStatus(workId: number): Promise\<WorkInfo>
获取工作的最新状态,使用Promise形式返回。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------- |
| workId | number | 是 | work的id。 |
**返回值**
| 类型 | 说明 |
| ------------------------------- | ---------------------------------------- |
| Promise\<[WorkInfo](#workinfo)> | 指定的Promise回调方法。如果指定的工作ID有效,则返回从WorkSchedulerService获取的有效工作状态;否则返回null。 |
**示例**
```
workScheduler.getWorkStatus(50).then((res) => {
for (let item in res) {
console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]);
}
}).catch((err) => {
console.info('workschedulerLog getWorkStatus failed, because:' + err.data);
})
```
## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
获取与当前应用程序关联的所有工作,使用Callback形式返回。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------------------- |
| callback | AsyncCallback\<void> | 是 | 指定的callback回调方法。返回与应用程序关联的所有工作。 |
**返回值**
| 类型 | 说明 |
| ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | 返回与应用程序关联的所有工作。 |
**示例**
```
workScheduler.obtainAllWorks((err, res) =>{
if (err) {
console.info('workschedulerLog obtainAllWorks failed, because:' + err.data);
} else {
console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
}
});
```
## workScheduler.obtainAllWorks
obtainAllWorks(): Promise<Array\<WorkInfo>>
获取与当前应用程序关联的所有工作,使用Promise形式返回。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**返回值**
| 类型 | 说明 |
| -------------------------------------- | ------------------------------ |
| Promise<Array\<[WorkInfo](#workinfo)>> | 指定的Promise回调方法。返回与应用程序关联的所有工作。 |
**示例**
```
workScheduler.obtainAllWorks().then((res) => {
console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res));
}).catch((err) => {
console.info('workschedulerLog obtainAllWorks failed, because:' + err.data);
})
```
## workScheduler.stopAndClearWorks
stopAndClearWorks(): boolean
停止和取消与当前应用程序关联的所有工作。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**示例**
```
let res = workScheduler.stopAndClearWorks();
console.info("workschedulerLog res:" + res);
```
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
检查指定工作的最后一次执行是否为超时操作,使用Callback形式返回。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------------------------------------- |
| workId | number | 是 | work的id。 |
| callback | AsyncCallback\<void> | 是 | 指定的callback回调方法。如果指定工作的最后一次执行是超时操作,则返回true;否则返回false。 |
**返回值**
| 类型 | 说明 |
| ------- | ---------------------------------------- |
| boolean | 指定的callback回调方法。如果指定工作的最后一次执行是超时操作,则返回true;否则返回false。 |
**示例**
```
workScheduler.isLastWorkTimeOut(500, (err, res) =>{
if (err) {
console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.data);
} else {
console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
}
});
```
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean>
检查指定工作的最后一次执行是否为超时操作,使用Promise形式返回。
**系统能力**:SystemCapability.ResourceSchedule.WorkScheduler
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------- |
| workId | number | 是 | work的id。 |
**返回值**
| 类型 | 说明 |
| ----------------- | ---------------------------------------- |
| Promise\<boolean> | 指定的Promise回调方法。如果指定工作的最后一次执行是超时操作,则返回true;否则返回false。 |
**示例**
```
workScheduler.isLastWorkTimeOut(500)
.then(res => {
console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res);
})
.catch(err => {
console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.data);
});
```
## WorkInfo
提供工作的具体信息。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.WorkScheduler
| 参数名 | 类型 | 必填 | 说明 |
| --------------- | --------------------------------- | ---- | ---------------- |
| workId | number | 是 | 当前工作的ID |
| bundleName | string | 是 | 延迟任务包名 |
| abilityName | string | 是 | 延迟任务回调通知的组件名(必填) |
| networkType | [NetworkType](#networktype) | 否 | 网络类型 |
| isCharging | boolean | 否 | 是否充电 |
| chargerType | [ChargingType](#chargingtype) | 否 | 充电类型 |
| batteryLevel | number | 否 | 电量 |
| batteryStatus | [BatteryStatus](#batterystatus) | 否 | 电池状态 |
| storageRequest | [StorageRequest](#storagerequest) | 否 | 存储状态 |
| isRepeat | boolean | 否 | 是否循环任务 |
| repeatCycleTime | number | 否 | 循环间隔 |
| repeatCount | number | 否 | 循环次数 |
## NetworkType
触发工作的网络类型。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.WorkScheduler
| 名称 | 默认值 | 说明 |
| ---------------------- | ---- | ----------------------- |
| NETWORK_TYPE_ANY | 0 | 表示这个触发条件是任何类型的网络连接。 |
| NETWORK_TYPE_MOBILE | 1 | 表示这个触发条件是Mobile网络连接。 |
| NETWORK_TYPE_WIFI | 2 | 表示这个触发条件是Wifi类型的网络连接。 |
| NETWORK_TYPE_BLUETOOTH | 3 | 表示这个触发条件是Bluetooth网络连接。 |
| NETWORK_TYPE_WIFI_P2P | 4 | 表示这个触发条件是Wifi P2P网络连接。 |
| NETWORK_TYPE_ETHERNET | 5 | 表示这个触发条件是有线网络连接。 |
## ChargingType
触发工作的充电类型。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.WorkScheduler
| 名称 | 默认值 | 说明 |
| ------------------------- | ---- | -------------------- |
| CHARGING_PLUGGED_ANY | 0 | 表示这个触发条件是任何类型的充电器连接。 |
| CHARGING_PLUGGED_AC | 1 | 表示这个触发条件是直流充电器连接。 |
| CHARGING_PLUGGED_USB | 2 | 表示这个触发条件是USB充连接。 |
| CHARGING_PLUGGED_WIRELESS | 3 | 表示这个触发条件是无线充电器连接。 |
## BatteryStatus
触发工作的电池状态。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.WorkScheduler
| 名称 | 默认值 | 说明 |
| -------------------------- | ---- | -------------------------- |
| BATTERY_STATUS_LOW | 0 | 表示这个触发条件是低电告警。 |
| BATTERY_STATUS_OKAY | 1 | 表示这个触发条件是从低电恢复到正常电量。 |
| BATTERY_STATUS_LOW_OR_OKAY | 2 | 表示这个触发条件是从低电恢复到正常电量或者低电告警。 |
## StorageRequest
触发工作的存储状态。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.WorkScheduler
|名称 |默认值 |说明|
| -------- | -------- | -------- |
|STORAGE_LEVEL_LOW |0 |表示这个触发条件是存储空间不足。
|STORAGE_LEVEL_OKAY |1 |表示这个触发条件是从存储空间不足恢复到正常。
|STORAGE_LEVEL_LOW_OR_OKAY |2 |表示这个触发条件是从存储空间不足恢复到正常或者存储空间不足。
\ No newline at end of file
......@@ -26,7 +26,7 @@ XmlSerializer的构造函数。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| -------- | --------------------------------- | ---- | ----------------------------------- |
| buffer | ArrayBuffer&nbsp;\|&nbsp;DataView | 是 | 用于接收写入xml信息的ArrayBuffer或DataView内存。 |
| encoding | string | 否 | 编码格式。 |
......@@ -48,7 +48,7 @@ setAttributes(name: string, value: string): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ----- | ------ | ---- | ---------- |
| name | string | 是 | 属性的key值。 |
| value | string | 是 | 属性的value值。 |
......@@ -69,7 +69,7 @@ addEmptyElement(name: string): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ---- | ------ | ---- | --------- |
| name | string | 是 | 该空元素的元素名。 |
**示例:**
......@@ -103,7 +103,7 @@ startElement(name: string): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ---- | ------ | ---- | --------- |
| name | string | 是 | 当前元素的元素名。 |
**示例:**
......@@ -143,7 +143,7 @@ setNamespace(prefix: string, namespace: string): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| --------- | ------ | ---- | --------------- |
| prefix | string | 是 | 当前元素及其子元素的前缀。 |
| namespace | string | 是 | 当前元素及其子元素的命名空间。 |
......@@ -167,7 +167,7 @@ setComment(text: string): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ---- | ------ | ---- | ---------- |
| text | string | 是 | 当前元素的注释内容。 |
**示例:**
......@@ -190,7 +190,7 @@ setCDATA(text: string): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ---- | ------ | ---- | ----------- |
| text | string | 是 | CDATA属性的内容。 |
**示例:**
......@@ -211,7 +211,7 @@ setText(text: string): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ---- | ------ | ---- | ---------- |
| text | string | 是 | text属性的内容。 |
**示例:**
......@@ -235,7 +235,7 @@ setDocType(text: string): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ---- | ------ | ---- | ------------- |
| text | string | 是 | DocType属性的内容。 |
**示例:**
......@@ -259,7 +259,7 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string)
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| -------- | --------------------------------- | ---- | -------------------------------- |
| buffer | ArrayBuffer&nbsp;\|&nbsp;DataView | 是 | 含有xml文本信息的ArrayBuffer或者DataView。 |
| encoding | string | 否 | 编码格式(仅支持utf-8)。 |
......@@ -292,7 +292,7 @@ parse(option: ParseOptions): void
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ------ | ----------------------------- | ---- | ---------------- |
| option | [ParseOptions](#parseoptions) | 是 | 用户控制以及获取解析信息的选项。 |
**示例:**
......@@ -331,7 +331,7 @@ xml解析选项。
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| ------------------------------ | ---------------------------------------- | ---- | -------------------------------- |
| supportDoctype | boolean | 否 | 是否忽略Doctype&nbsp;,&nbsp;默认false。 |
| ignoreNameSpace | boolean | 否 | 是否忽略NameSpace,默认false。 |
| tagValueCallbackFunction | (name:&nbsp;string,&nbsp;value:&nbsp;string)=&gt;&nbsp;boolean | 否 | 获取tagValue回调函数。 |
......@@ -352,7 +352,7 @@ getColumnNumber(): number
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------ | ------- |
| number | 返回当前列号。 |
......@@ -365,7 +365,7 @@ getDepth(): number
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------ | ---------- |
| number | 返回元素的当前深度。 |
......@@ -378,7 +378,7 @@ getLineNumber(): number
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------ | ------- |
| number | 返回当前行号。 |
......@@ -391,7 +391,7 @@ getName(): string
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------ | --------- |
| string | 返回当前元素名称。 |
......@@ -404,7 +404,7 @@ getNamespace(): string
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------ | ------------ |
| string | 返回当前元素的命名空间。 |
......@@ -417,7 +417,7 @@ getPrefix(): string
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------ | --------- |
| string | 返回当前元素前缀。 |
......@@ -430,7 +430,7 @@ getText(): string
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------ | ------------ |
| string | 返回当前事件的文本内容。 |
......@@ -443,7 +443,7 @@ isEmptyElementTag(): boolean
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------- | ---------------- |
| boolean | 返回true,当前元素为空元素。 |
......@@ -456,7 +456,7 @@ isWhitespace(): boolean
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------- | --------------------- |
| boolean | 返回true,当前文本事件仅包含空格字符。 |
......@@ -468,7 +468,7 @@ getAttributeCount(): number
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| ------ | ----------- |
| number | 当前开始标记的属性数。 |
......@@ -477,7 +477,7 @@ getAttributeCount(): number
事件枚举。
| 名称 | 枚举值 | 说明 |
| -------- | -------- | -------- |
| ---------------- | ---- | ------------ |
| START_DOCUMENT | 0 | 启动文件事件。 |
| END_DOCUMENT | 1 | 结束文件事件。 |
| START_TAG | 2 | 启动标签事件。 |
......
......@@ -60,6 +60,7 @@
- [ImageAnimator](ts-basic-components-imageanimator.md)
- [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.md)
- [Navigation](ts-basic-components-navigation.md)
- [PatternLock](ts-basic-components-patternlock.md)
- [PluginComponent](ts-basic-components-plugincomponent.md)
- [Progress](ts-basic-components-progress.md)
......@@ -67,10 +68,13 @@
- [Radio](ts-basic-components-radio.md)
- [Rating](ts-basic-components-rating.md)
- [RichText](ts-basic-components-richtext.md)
- [ScrollBar](ts-basic-components-scrollbar.md)
- [Search](ts-basic-components-search.md)
- [Select](ts-basic-components-select.md)
- [Slider](ts-basic-components-slider.md)
- [Span](ts-basic-components-span.md)
- [Stepper](ts-basic-components-stepper.md)
- [StepperItem](ts-basic-components-stepperitem.md)
- [Text](ts-basic-components-text.md)
- [TextArea](ts-basic-components-textarea.md)
- [TextClock](ts-basic-components-textclock.md)
......@@ -94,17 +98,13 @@
- [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md)
- [Navigator](ts-container-navigator.md)
- [Navigation](ts-basic-components-navigation.md)
- [Panel](ts-container-panel.md)
- [Refresh](ts-container-refresh.md)
- [Row](ts-container-row.md)
- [RowSplit](ts-container-rowsplit.md)
- [Scroll](ts-container-scroll.md)
- [ScrollBar](ts-basic-components-scrollbar.md)
- [SideBarContainer](ts-container-sidebarcontainer.md)
- [Stack](ts-container-stack.md)
- [Stepper](ts-basic-components-stepper.md)
- [StepperItem](ts-basic-components-stepperitem.md)
- [Swiper](ts-container-swiper.md)
- [Tabs](ts-container-tabs.md)
- [TabContent](ts-container-tabcontent.md)
......
......@@ -15,19 +15,11 @@
- 开发
- Ability开发
- [Ability框架概述](ability/ability-brief.md)
- FA模型
- [FA模型综述](ability/fa-brief.md)
- [PageAbility开发指导](ability/fa-pageability.md)
- [ServiceAbility开发指导](ability/fa-serviceability.md)
- [DataAbility开发指导](ability/fa-dataability.md)
- [FormAbility开发指导](ability/fa-formability.md)
- Stage模型
- [Stage模型综述](ability/stage-brief.md)
- [Ability开发指导](ability/stage-ability.md)
- [ServiceExtensionAbility开发指导](ability/stage-serviceextension.md)
- [FormExtensionAbility开发指导](ability/stage-formextension.md)
- [应用迁移开发指导](ability/stage-ability-continuation.md)
- 其他
- [WantAgent使用指导](ability/wantagent.md)
- [Ability助手使用指导](ability/ability-assistant-guidelines.md)
......@@ -440,6 +432,7 @@
- [ImageAnimator](reference/arkui-ts/ts-basic-components-imageanimator.md)
- [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md)
- [Marquee](reference/arkui-ts/ts-basic-components-marquee.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [PatternLock](reference/arkui-ts/ts-basic-components-patternlock.md)
- [PluginComponent](reference/arkui-ts/ts-basic-components-plugincomponent.md)
- [Progress](reference/arkui-ts/ts-basic-components-progress.md)
......@@ -447,6 +440,7 @@
- [Radio](reference/arkui-ts/ts-basic-components-radio.md)
- [Rating](reference/arkui-ts/ts-basic-components-rating.md)
- [RichText](reference/arkui-ts/ts-basic-components-richtext.md)
- [ScrollBar](reference/arkui-ts/ts-basic-components-scrollbar.md)
- [Search](reference/arkui-ts/ts-basic-components-search.md)
- [Select](reference/arkui-ts/ts-basic-components-select.md)
- [Slider](reference/arkui-ts/ts-basic-components-slider.md)
......@@ -476,13 +470,11 @@
- [List](reference/arkui-ts/ts-container-list.md)
- [ListItem](reference/arkui-ts/ts-container-listitem.md)
- [Navigator](reference/arkui-ts/ts-container-navigator.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [Panel](reference/arkui-ts/ts-container-panel.md)
- [Refresh](reference/arkui-ts/ts-container-refresh.md)
- [Row](reference/arkui-ts/ts-container-row.md)
- [RowSplit](reference/arkui-ts/ts-container-rowsplit.md)
- [Scroll](reference/arkui-ts/ts-container-scroll.md)
- [ScrollBar](reference/arkui-ts/ts-basic-components-scrollbar.md)
- [SideBarContainer](reference/arkui-ts/ts-container-sidebarcontainer.md)
- [Stack](reference/arkui-ts/ts-container-stack.md)
- [Swiper](reference/arkui-ts/ts-container-swiper.md)
......@@ -653,4 +645,3 @@
- [非线性容器LightWeightSet](reference/apis/js-apis-lightweightset.md)
- 定制管理
- [配置策略](reference/apis/js-apis-config-policy.md)
\ No newline at end of file
- [企业设备管理](reference/apis/js-apis-enterprise-device-manager.md)
\ No newline at end of file
# Camera<a name="ZH-CN_TOPIC_0000001078436908"></a>
# Camera
- [Camera<a name="ZH-CN_TOPIC_0000001078436908"></a>](#camera)
- [概述<a name="section11660541593"></a>](#概述)
- [开发指导<a name="section161941989596"></a>](#开发指导)
- [HDI接口说明<a name="section1551164914237"></a>](#hdi接口说明)
- [开发步骤<a name="section19806524151819"></a>](#开发步骤)
- [开发实例<a name="section1564411661810"></a>](#开发实例)
## 概述<a name="1"></a>
### 功能简介<a name="2"></a>
OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Device Interface)接口,对下实现相机Pipeline模型,管理相机各个硬件设备。
该驱动框架模型内部分为三层,依次为HDI实现层、框架层和设备适配层,各层基本概念如下:
## 概述<a name="section11660541593"></a>
+ HDI实现层:实现OHOS(OpenHarmony Operation System)相机标准南向接口。
+ 框架层:对接HDI实现层的控制、流的转发,实现数据通路的搭建,管理相机各个硬件设备等功能。
+ 设备适配层:屏蔽底层芯片和OS(Operation System)差异,支持多平台适配。
OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Interface)接口,对下实现相机Pipeline模型,管理相机各个硬件设备。
该驱动框架模型内部分为三层,依次为HDI实现层、框架层和适配层,各层基本概念如下:
+ **HDI实现层**:对上实现OHOS(OpenHarmony Operation System)相机标准南向接口。
### 运作机制<a name="3"></a>
+ **框架层**:对接HDI实现层的控制、流的转发,实现数据通路的搭建,管理相机各个硬件设备等功能。
Camera模块主要包含服务、设备的初始化,数据通路的搭建,流的配置、创建、下发、捕获等,具体运作机制参考以下图文解析:
+ **适配层**:屏蔽底层芯片和OS(Operation System)差异,支持多平台适配。
**图 1** 基于HDF驱动框架的Camera驱动模型 
**<a name="fig3672817152110"></a>**
**图 1** 基于HDF驱动框架的Camera驱动模型
![](figures/logic-view-of-camera-hal-zh.png)
        ![](figures/Camera模块驱动模型.png)
1. 系统启动时创建CameraDeviceHost进程。进程创建后,首先枚举底层设备,创建(也可以通过配置表创建)管理设备树的DeviceManager类及其内部各个底层设备的对象,创建对应的CameraHost类实例并且将其注册到UHDF服务中,方便上层通过UHDF服务获取底层CameraDeviceHost的服务,从而操作底层设备。
1. 系统启动时创建camera_host进程。进程创建后,首先枚举底层设备,创建(也可以通过配置表创建)管理设备树的DeviceManager类及其内部各个底层设备的对象,创建对应的CameraHost类实例并且将其注册到UHDF服务中,方便相机服务层通过UHDF服务获取底层CameraDeviceHost的服务,从而操作硬件设备。
2. Service通过CameraDeviceHost服务获取CameraHost实例,CameraHost可以获取底层的Camera能力,打开手电筒、调用Open接口打开Camera创建连接、创建DeviceManager(负责底层硬件模块上电)、创建CameraDevice(向上提供设备控制接口)。创建CameraDevice时会实例化PipelineCore的各个子模块,其中StreamPiplineCore负责创建Pipeline,MetaQueueManager负责上报meta。
2. Service通过CameraDeviceHost服务获取CameraHost实例,CameraHost可以获取底层的Camera能力,打开手电筒、调用Open接口打开Camera创建连接、创建DeviceManager(负责底层硬件模块上电)、创建CameraDevice(向上提供设备控制接口)。创建CameraDevice时会实例化PipelineCore的各个子模块,其中StreamPipelineCore负责创建Pipeline,MetaQueueManager负责上报metaData。
3. Service通过底层的CameraDevice配置流、创建Stream类。StreamPipelineStrategy模块通过上层下发的模式和查询配置表创建对应流的Node连接方式,StreamPipelineBuilder模块创建Node实例并且连接返回该Pipline给StreamPipelineDispatcher。StreamPipelineDispatcher提供统一的Pipline调用管理。
3. Service通过CameraDevice模块配置流、创建Stream类。StreamPipelineStrategy模块通过上层下发的模式和查询配置表创建对应流的Node连接方式,StreamPipelineBuilder模块创建Node实例并且连接返回该Pipeline给StreamPipelineDispatcher。StreamPipelineDispatcher提供统一的Pipeline调用管理。
4. Service通过Stream控制整个流的操作,AttachBufferQueue接口将从显示模块申请的BufferQueue下发到底层,由CameraDeviceDriverModel自行管理buffer,当Capture接口下发命令后,底层开始向上传递buffer。Pipeline的IspNode依次从BufferQueue获取指定数量buffer,然后下发到底层ISP(Image Signal Processor,图像信号处理器)硬件,ISP填充完之后将buffer传递给CameraDeviceDriverModel,CameraDeviceDriverModel通过循环线程将buffer填充到已经创建好的Pipeline中,各个Node处理后通过回调传递给上层,同时buffer返回BufferQueue等待下一次下发。
......@@ -34,25 +30,98 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
6. Service通过CameraDevice的UpdateSettings接口向下发送CaptureSetting参数,CameraDeviceDriverModel通过StreamPipelineDispatcher模块向各个Node转发,StartStreamingCapture和Capture接口携带的CaptureSetting通过StreamPipelineDispatcher模块向该流所属的Node转发。
7. Service通过EnableResult和DisableResult接口控制底层meta的上报。如果需要底层meta上报,pipeline会创建CameraDeviceDriverModel内部的一个Bufferqueue用来收集和传递meta,根据StreamPipelineStrategy模块查询配置表并通过StreamPipelineBuilder创建和连接Node,MetaQueueManager下发buffer至底层,底层相关Node填充数据,MetaQueueManager模块再调用上层回调传递给上层。
7. Service通过EnableResult和DisableResult接口控制底层metaData的上报。如果需要底层metaData上报,pipeline会创建CameraDeviceDriverModel内部的一个Bufferqueue用来收集和传递metaData,根据StreamPipelineStrategy模块查询配置表并通过StreamPipelineBuilder创建和连接Node,MetaQueueManager下发buffer至底层,底层相关Node填充数据,MetaQueueManager模块再调用上层回调传递给上层。
8. Service调用CameraDevice的Close接口,CameraDevice调用对应的DeviceManager模块对各个硬件下电;如果此时在Ipp的SubPipeline中存在OfflineStream,则需要保留OfflineStream,直到执行完毕。
9. 动态帧率控制。在StreamOperator中起一个CollectBuffer线程,CollectBuffer线程从每一路stream的BufferQueue中获取buffer,如果某一路流的帧率需要控制(为sensor出帧帧率的1/n),可以根据需求控制每一帧的buffer打包,并决定是否collect此路流的buffer(比如sensor出帧帧率为120fps,预览流的帧率为30fps,CollectBuffer线程collect预览流的buffer时,每隔4fps collect一次)。
## 开发指导<a name="section161941989596"></a>
### HDI接口说明<a name="section1551164914237"></a>
旨在了解HDI接口的作用及函数参数的传递规则,详情可见[Camera驱动子系统HDI使用说明](https://gitee.com/openharmony/drivers_peripheral/blob/master/camera/README_zh.md)
## 开发指导<a name="4"></a>
### 开发步骤<a name="section19806524151819"></a>
下面分步骤描述了Camera驱动框架的主要接口,包括注册、检测;创建、捕获和销毁流;打开和关闭设备等接口(为了更清晰的展示和描述主要功能的实现部分,该章节删除了部分判错和LOG源码)。
1. 注册CameraHost
### 场景介绍<a name="5"></a>
定义Camera的HdfDriverEntry结构体,该结构体中定义了CameraHost初始化的方法。
Camera模块主要用以相机预览、拍照、视频流等场景下对相机操作封装,使开发者更易操作相机硬件,提高开发效率。
### 接口说明<a name="6"></a>
- icamera_device.h
| 功能描述 | 接口名称 |
| ---------------------------- | ------------------------------------------------------------ |
| 获取流控制器 | CamRetCode GetStreamOperator(<br/> const OHOS::sptr<IStreamOperatorCallback> &callback,<br/> OHOS::sptr<IStreamOperator> &streamOperator) |
| 更新设备控制参数 | CamRetCode UpdateSettings(const std::shared_ptr<CameraSetting> &settingss) |
| 设置Result回调模式和回调函数 | CamRetCode SetResultMode(const ResultCallbackMode &mode) |
| 获取使能的ResultMeta | CamRetCode GetEnabledResults(std::vector<MetaType> &results) |
| 使能具体的ResultMeta | CamRetCode EnableResult(const std::vector<MetaType> &results) |
| 禁止具体的ResultMeta | CamRetCode DisableResult(const std::vector<MetaType> &results) |
| 关闭Camera设备 | void Close() |
- icamera_device_callback.h
| 功能描述 | 接口名称 |
| ---------------------------------------------------------- | ------------------------------------------------------------ |
| 设备发生错误时调用,由调用者实现,用于返回错误信息给调用者 | void OnError(ErrorType type, int32_t errorCode) |
| 上报camera设备相关的metadata的回调 | void OnResult(uint64_t timestamp, const std::shared_ptr<CameraMetadata> &result) |
- icamera_host.h
| 功能描述 | 接口名称 |
| ------------------------------ | ------------------------------------------------------------ |
| 设置ICameraHost回调接口 | CamRetCode SetCallback(const OHOS::sptr<ICameraHostCallback> &callback) |
| 获取当前可用的Camera设备ID列表 | CamRetCode GetCameraIds(std::vector<std::string> &cameraIds) |
| 获取Camera设备能力集合 | CamRetCode GetCameraAbility(const std::string &cameraId,<br/> std::shared_ptr<CameraAbility> &ability) |
| 打开Camera设备 | CamRetCode OpenCamera(const std::string &cameraId,<br/> const OHOS::sptr<ICameraDeviceCallback> &callback,<br/> OHOS::sptr<ICameraDevice> &device) |
| 打开或关闭闪光灯 | CamRetCode SetFlashlight(const std::string &cameraId, bool &isEnable) |
- icamera_host_callback.h
| 功能描述 | 接口名称 |
| ---------------------- | ------------------------------------------------------------ |
| Camera设备状态变化上报 | void OnCameraStatus(const std::string &cameraId, CameraStatus status) |
| 闪光灯状态变化回调 | void OnFlashlightStatus(const std::string &cameraId, FlashlightStatus status) |
- ioffline_stream_operator.h
| 功能描述 | 接口名称 |
| -------------- | ------------------------------------------------------------ |
| 取消捕获请求 | CamRetCode CancelCapture(int captureId) |
| 释放流 | CamRetCode ReleaseStreams(const std::vector<int> &streamIds) |
| 释放所有离线流 | CamRetCode Release() |
- istream_operator.h
| 功能描述 | 接口名称 |
| -------------------------------- | ------------------------------------------------------------ |
| 查询是否支持添加参数对应的流 | CamRetCode IsStreamsSupported(<br/> OperationMode mode,<br/> const std::shared_ptr<CameraStandard::CameraMetadata> &modeSetting,<br/> const std::vector&ltstd::shared_ptr&ltStreamInfo&gt> &info,<br/> StreamSupportType &type) |
| 创建流 | CamRetCode CreateStreams(const std::vector<std::shared_ptr<StreamInfo>> &streamInfos) |
| 释放流 | CamRetCode ReleaseStreams(const std::vector<int> &streamIds) |
| 配置流 | CamRetCode CommitStreams(OperationMode mode,<br/> const std::shared_ptr<CameraMetadata> &modeSetting) |
| 获取流的属性 | CamRetCode GetStreamAttributes(<br/> std::vector<std::shared_ptr<StreamAttribute>> &attributes) |
| 绑定生产者句柄和指定流 | CamRetCode AttachBufferQueue(int streamId, const OHOS::sptr<OHOS::IBufferProducer> &producer) |
| 解除生产者句柄和指定流的绑定关系 | CamRetCode DetachBufferQueue(int streamId) |
| 捕获图像 | CamRetCode Capture(int captureId,<br/> const std::shared_ptr<CaptureInfo> &info, bool isStreaming) |
| 取消捕获 | CamRetCode CancelCapture(int captureId) |
| 将指定流转换成离线流 | CamRetCode ChangeToOfflineStream(const std::vector<int> &streamIds,<br/> OHOS::sptr<IStreamOperatorCallback> &callback,<br/> OHOS::sptr<IOfflineStreamOperator> &offlineOperator) |
- istream_operator_callback.h
| 功能描述 | 接口名称 |
| ---------------------------------------- | ------------------------------------------------------------ |
| 捕获开始回调,在捕获开始时调用 | void OnCaptureStarted(int32_t captureId, const std::vector<int32_t> &streamIds) |
| 捕获结束回调,在捕获结束时调用 | void OnCaptureEnded(int32_t captureId,<br/> const std::vector<std::shared_ptr<CaptureEndedInfo>> &infos) |
| 捕获错误回调,在捕获过程中发生错误时调用 | void OnCaptureError(int32_t captureId,<br/> const std::vector<std::shared_ptr<CaptureErrorInfo>> &infos) |
| 帧捕获回调 | void OnFrameShutter(int32_t captureId,<br/> const std::vector<int32_t> &streamIds, uint64_t timestamp) |
### 开发步骤<a name="7"></a>
Camera驱动的开发过程主要包含以下步骤:
1. **注册CameraHost**
定义Camera的HdfDriverEntry结构体,该结构体中定义了CameraHost初始化的方法。
```
struct HdfDriverEntry g_cameraHostDriverEntry = {
.moduleVersion = 1,
......@@ -64,7 +133,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
HDF_INIT(g_cameraHostDriverEntry); // 将Camera的HdfDriverEntry结构体注册到HDF上
```
2. CameraHost初始化
2. **初始化Host服务**
步骤1中提到的HdfCameraHostDriverBind接口提供了CameraServiceDispatch和CameraHostStubInstance的注册。这两个接口一个是远端调用CameraHost的方法,如OpenCamera(),SetFlashlight()等,另外一个是Camera设备的初始化,在开机时被调用。
......@@ -123,7 +192,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
CameraHostStubInstance()接口最终调用CameraHostImpl::Init()方法,该方法会获取物理Camera,并对DeviceManager和PipelineCore进行初始化。
3. 获取CamerHost
3. **获取Host服务**
调用Get()接口从远端CameraService中获取CameraHost对象。get()方法如下:
......@@ -149,7 +218,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
}
```
4. OpenCamera()接口
4. **打开设备**
CameraHostProxy对象中有五个方法,分别是SetCallback、GetCameraIds、GetCameraAbility、OpenCamera和SetFlashlight。下面着重描述OpenCamera接口。
CameraHostProxy的OpenCamera()接口通过CMD_CAMERA_HOST_OPEN_CAMERA调用远端CameraHostStubOpenCamera()接口并获取ICameraDevice对象。
......@@ -187,7 +256,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
}
CamRetCode ret = cameraDevice->SetCallback(callback);
if (ret != NO_ERROR) {
CAMERA_LOGW("set camera device callback faild.");
CAMERA_LOGW("set camera device callback failed.");
return ret;
}
CameraHostConfig *config = CameraHostConfig::GetInstance();
......@@ -216,7 +285,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
}
```
5. GetStreamOperator()接口
5. **获取流**
CameraDeviceImpl定义了GetStreamOperator、UpdateSettings、SetResultMode和GetEnabledResult等方法,获取流操作方法如下:
......@@ -228,10 +297,10 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
CAMERA_LOGW("input callback is null.");
return INVALID_ARGUMENT;
}
spCameraDeciceCallback_ = callback;
spCameraDeviceCallback_ = callback;
if (spStreamOperator_ == nullptr) {
// 这里new了一个spStreamOperator对象传递给调用者,以便对stream进行各种操作。
spStreamOperator_ = new(std::nothrow) StreamOperatorImpl(spCameraDeciceCallback_, shared_from_this());
spStreamOperator_ = new(std::nothrow) StreamOperatorImpl(spCameraDeviceCallback_, shared_from_this());
if (spStreamOperator_ == nullptr) {
CAMERA_LOGW("create stream operator failed.");
return DEVICE_ERROR;
......@@ -241,12 +310,12 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
streamOperator = ismOperator_;
spStreamOperator_->SetRequestCallback([this](){
cameraDeciceCallback_->OnError(REQUEST_TIMEOUT, 0);
spCameraDeviceCallback_->OnError(REQUEST_TIMEOUT, 0);
});
}
```
6. 创建流
6. **创建流**
调用CreateStreams创建流前需要填充StreamInfo结构体,具体内容如下:
......@@ -256,7 +325,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
int width_; // 数据流宽
int height_; // 数据流高
int format_; // 数据流格式,如PIXEL_FMT_YCRCB_420_SP
int datasapce_;
int dataSpace_;
StreamIntent intent_; // StreamIntent 如PREVIEW
bool tunneledMode_;
OHOS::sptr<OHOS::IBufferProducer> bufferQueue_; // 数据流bufferQueue可用streamCustomer->CreateProducer()接口创建
......@@ -289,7 +358,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
}
```
7. 配置流
7. **配置流**
CommitStreams()是配置流的接口,必须在创建流之后调用,其主要作用是初始化Pipeline和创建Pipeline。
......@@ -328,7 +397,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
}
```
8. 捕获图像
8. **捕获图像**
在调用Capture()接口前需要先填充CaptureInfo结构体,具体内容如下:
......@@ -370,7 +439,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
}
```
9. 取消捕获和释放离线流
9. **取消捕获和释放离线流**
StreamOperatorImpl类中的CancelCapture()接口的主要作用是根据captureId取消数据流的捕获。
......@@ -397,22 +466,21 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
}
```
10. 关闭Camera设备
10. **关闭Camera设备**
调用CameraDeviceImpl中的Close()来关闭CameraDevice,该接口调用deviceManager中的PowerDown()来给设备下电。
### 开发实例<a name = "8"></a>
## 开发实例<a name="section1564411661810"></a>
在/drivers/peripheral/camera/hal/init目录下有一个关于Camera的demo,开机后会在/system/bin下生成可执行文件ohos_camera_demo,该demo可以完成camera的预览,拍照等基础功能。下面我们就以此demo为例讲述怎样用HDI接口去编写预览PreviewOn()和拍照CaptureON()的用例。
在/drivers/peripheral/camera/hal/init目录下有一个关于Camera的demo,开机后会在/vendor/bin下生成可执行文件ohos_camera_demo,该demo可以完成Camera的预览,拍照等基础功能。下面我们就以此demo为例讲述怎样用HDI接口去编写预览PreviewOn()和拍照CaptureON()的用例,可参考[ohos_camera_demo](https://gitee.com/openharmony/drivers_peripheral/tree/master/camera/hal/init)。
1. 在main函数中构造一个Hos3516Demo对象,该对象中有对camera初始化、启停流、释放等控制的方法。下面mainDemo->InitSensors()函数为初始化CameraHost,mainDemo->InitCameraDevice()函数为初始化CameraDevice。
1. 在main函数中构造一个CameraDemo 对象,该对象中有对Camera初始化、启停流、释放等控制的方法。下面mainDemo->InitSensors()函数为初始化CameraHost,mainDemo->InitCameraDevice()函数为初始化CameraDevice。
```
int main(int argc, char** argv)
{
RetCode rc = RC_OK;
auto mainDemo = std::make_shared<Hos3516Demo>();
auto mainDemo = std::make_shared<CameraDemo>();
rc = mainDemo->InitSensors(); // 初始化CameraHost
if (rc == RC_ERROR) {
CAMERA_LOGE("main test: mainDemo->InitSensors() error\n");
......@@ -440,7 +508,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
初始化CameraHost函数实现如下,这里调用了HDI接口ICameraHost::Get()去获取demoCameraHost,并对其设置回调函数。
```
RetCode Hos3516Demo::InitSensors()
RetCode CameraDemo::InitSensors()
{
demoCameraHost_ = ICameraHost::Get(DEMO_SERVICE_NAME);
if (demoCameraHost_ == nullptr) {
......@@ -457,7 +525,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
初始化CameraDevice函数实现如下,这里调用了GetCameraIds(cameraIds_),GetCameraAbility(cameraId, ability_),OpenCamera(cameraIds_.front(), callback, demoCameraDevice_)等接口实现了demoCameraHost的获取。
```
RetCode Hos3516Demo::InitCameraDevice()
RetCode CameraDemo::InitCameraDevice()
{
(void)demoCameraHost_->GetCameraIds(cameraIds_);
const std::string cameraId = cameraIds_.front();
......@@ -472,7 +540,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
2. PreviewOn()接口包含配置流、开启预览流和启动Capture动作。该接口执行完成后Camera预览通路已经开始运转并开启了两路流,一路流是preview,另外一路流是capture或者video,两路流中仅对preview流进行capture动作。
```
static RetCode PreviewOn(int mode, const std::shared_ptr<Hos3516Demo>& mainDemo)
static RetCode PreviewOn(int mode, const std::shared_ptr<CameraDemo>& mainDemo)
{
rc = mainDemo->StartPreviewStream(); // 配置preview流
if (mode == 0) {
......@@ -489,7 +557,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
StartCaptureStream()、StartVideoStream()和StartPreviewStream()接口都会调用CreateStream()接口,只是传入的参数不同。
```
RetCode Hos3516Demo::StartVideoStream()
RetCode CameraDemo::StartVideoStream()
{
RetCode rc = RC_OK;
if (isVideoOn_ == 0) {
......@@ -503,7 +571,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
CreateStream()方法调用HDI接口去配置和创建流,首先调用HDI接口去获取StreamOperation对象,然后创建一个StreamInfo。调用CreateStreams()和CommitStreams()实际创建流并配置流。
```
RetCode Hos3516Demo::CreateStreams(const int streamIdSecond, StreamIntent intent)
RetCode CameraDemo::CreateStreams(const int streamIdSecond, StreamIntent intent)
{
std::vector<std::shared_ptr<StreamInfo>> streamInfos;
std::vector<std::shared_ptr<StreamInfo>>().swap(streamInfos);
......@@ -546,10 +614,10 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
}
```
CaptureON()接口调用streamOperator的Capture()方法获取camera数据并轮转buffer,拉起一个线程接收相应类型的数据。
CaptureON()接口调用streamOperator的Capture()方法获取Camera数据并轮转buffer,拉起一个线程接收相应类型的数据。
```
RetCode Hos3516Demo::CaptureON(const int streamId, const int captureId, CaptureMode mode)
RetCode CameraDemo::CaptureON(const int streamId, const int captureId, CaptureMode mode)
{
std::shared_ptr<Camera::CaptureInfo> captureInfo = std::make_shared<Camera::CaptureInfo>(); // 创建并填充CaptureInfo
captureInfo->streamIds_ = {streamId};
......@@ -576,7 +644,7 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
3. ManuList()函数从控制台通过fgets()接口获取字符,不同字符所对应demo支持的功能不同,并打印出该demo所支持功能的菜单。
```
static void ManuList(const std::shared_ptr<Hos3516Demo>& mainDemo,
static void ManuList(const std::shared_ptr<CameraDemo>& mainDemo,
const int argc, char** argv)
{
int idx, c;
......@@ -668,5 +736,4 @@ OpenHarmony相机驱动框架模型对上实现相机HDI(Hardware Driver Inter
"-q | --quit stop preview and quit this app\n");
```
demo中其他功能会调用不同的HDI接口去实现,与PreviewOn()接口类似,这里不再赘述,具体详情可以参见[ohos_camera_demo](https://gitee.com/openharmony/drivers_peripheral/tree/master/camera/hal/init)。
......@@ -112,9 +112,9 @@ JS UI开发框架源代码在/foundation/ace下,目录结构如下图所示:
**JS UI框架子系统**
ace\_ace\_engine
[ace\_ace\_engine](https://gitee.com/openharmony/ace_ace_engine)
ace\_ace\_engine\_lite
[ace\_ace\_engine\_lite](https://gitee.com/openharmony/ace_engine_lite)
ace\_napi
[ace\_napi](https://gitee.com/openharmony/ace_napi)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册