提交 58a83ff4 编写于 作者: zyjhandsome's avatar zyjhandsome 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into master

Signed-off-by: zyjhandsome's avatarzyjhandsome <zyjhandsome@126.com>
......@@ -25,7 +25,8 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.
> **NOTE**<br>
> **NOTE**
>
> 1. Third-party applications cannot implement ServiceExtensionAbility, DataShareExtensionAbility, StaticSubscriberExtensionAbility, or WindowExtensionAbility.
>
> 2. To implement transaction processing in the background for a third-party application, use background tasks rather than ServiceExtensionAbility. For details, see [Background Task](../task-management/background-task-overview.md).
......@@ -45,7 +46,7 @@ The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-input
## Implementing ExtensionAbility of the Specified Type
The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You derive this base class to create your own class (such as **MyFormExtensionAbility**), implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget functionalities. For details, see [FormExtensionAbility](Widget-development-stage.md).
The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You derive this base class to create your own class (such as **MyFormExtensionAbility**), implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget functionalities. For details, see [FormExtensionAbility](service-widget-overview.md).
You do not need to care when to add or delete a widget. The lifecycle of the FormExtensionAbility instance and the lifecycle of the ExtensionAbility process where the FormExtensionAbility instance is located are scheduled and managed by FormManagerService.
......@@ -63,3 +64,5 @@ You do not need to care when to add or delete a widget. The lifecycle of the For
> - The two FormExtensionAbility components run in an independent process.
>
> - The two ImeExtensionAbility components run in an independent process.
<!--no_check-->
\ No newline at end of file
......@@ -323,7 +323,7 @@ async function deleteFormInfo(formId: string) {
// ...
```
For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md).
For details about how to implement persistent data storage, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).
The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary.
......
......@@ -332,7 +332,7 @@ export default class EntryFormAbility extends FormExtension {
}
```
For details about how to implement persistent data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md).
For details about how to implement persistent data storage, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).
The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary.
......
......@@ -53,10 +53,10 @@ let want = {
abilityName: 'EntryAbility'
};
abilityDelegator.startAbility(want, (err) => {
if (!err || err.code === 0) {
console.log('Success start ability.');
} else {
if (err) {
console.error('Failed start ability, error: ${JSON.stringify(err)}');
} else {
console.log('Success start ability.');
}
});
```
......
......@@ -40,7 +40,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager';
appManager.isRunningInStabilityTest((err, flag) => {
if (err && err.code !== 0) {
if (err) {
console.error('isRunningInStabilityTest fail, err: ${JSON.stringify(err)}');
} else {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
......@@ -146,7 +146,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager';
appManager.isRamConstrainedDevice((err, data) => {
if (err && err.code !== 0) {
if (err) {
console.error('isRamConstrainedDevice fail, err: ${JSON.stringify(err)}');
} else {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
......@@ -216,7 +216,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager';
appManager.getAppMemorySize((err, data) => {
if (err && err.code !== 0) {
if (err) {
console.error('getAppMemorySize fail, err: ${JSON.stringify(err)}');
} else {
console.log('The size of app memory is: ${JSON.stringify(data)}');
......@@ -290,7 +290,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation((err, data) => {
if (err && err.code !== 0) {
if (err) {
console.error('getRunningProcessInformation fail, err: ${JSON.stringify(err)}');
} else {
console.log('The process running information is: ${JSON.stringify(data)}');
......@@ -489,7 +489,7 @@ try {
// 2. Deregister the application state observer.
function unregisterApplicationStateObserverCallback(err) {
if (err && err.code !== 0) {
if (err) {
console.error('unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('unregisterApplicationStateObserverCallback success.');
......@@ -612,7 +612,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager';
function getForegroundApplicationsCallback(err, data) {
if (err && err.code !== 0) {
if (err) {
console.error('getForegroundApplicationsCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('getForegroundApplicationsCallback success, data: ${JSON.stringify(data)}');
......@@ -745,7 +745,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
let accountId = 0;
function killProcessWithAccountCallback(err, data) {
if (err && err.code !== 0) {
if (err) {
console.error('killProcessWithAccountCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('killProcessWithAccountCallback success.');
......@@ -788,7 +788,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) {
if (err && err.code !== 0) {
if (err) {
console.error('killProcessesByBundleNameCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('killProcessesByBundleNameCallback success.');
......@@ -884,7 +884,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) {
if (err && err.code !== 0) {
if (err) {
console.error('clearUpApplicationDataCallback fail, err: ${JSON.stringify(err)}');
} else {
console.log('clearUpApplicationDataCallback success.');
......
......@@ -29,7 +29,7 @@ Creates a **Filter** instance based on the pixel map.
| Name | Type | Mandatory| Description |
| ------- | ----------------- | ---- | -------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module. |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module. An instance can be obtained by decoding an image or directly created. For details, see [Image Overview](../../media/image-overview.md). |
**Return value**
......@@ -61,7 +61,7 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses a promi
| Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | -------------------------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module.|
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module. An instance can be obtained by decoding an image or directly created. For details, see [Image Overview](../../media/image-overview.md).|
**Return value**
......@@ -95,7 +95,7 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses an asyn
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | -------------------------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes |**PixelMap** instance created by the image module. |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes |**PixelMap** instance created by the image module. An instance can be obtained by decoding an image or directly created. For details, see [Image Overview](../../media/image-overview.md). |
| callback | AsyncCallback\<[ColorPicker](#colorpicker)> | Yes | Callback used to return the **ColorPicker** instance created.|
**Example**
......
# @ohos.enterprise.dateTimeManager (System Time Management)
The **dateTimeManager** module provides APIs for system time management, which can only be called by device administrator applications.
The **dateTimeManager** module provides APIs for system time management. Only the enterprise device administrator applications can call the APIs provided by this module.
> **NOTE**
>
......@@ -30,7 +30,7 @@ Sets the system time. This API uses an asynchronous callback to return the resul
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| time | number | Yes| Timestamp (ms).|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the setting is successful, **err** is **null**. Otherwise, **err** is an error object.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes**
......@@ -101,3 +101,181 @@ dateTimeManager.setDateTime(wantTemp, 1526003846000).then(() => {
console.log("error code:" + error.code + " error message:" + error.message);
})
```
## dateTimeManager.disallowModifyDateTime<sup>10+</sup>
disallowModifyDateTime(admin: Want, disallow: boolean, callback: AsyncCallback\<void>): void
Disables modification of the system time. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| disallow | boolean | Yes| Whether to disable modification of the system time. The value **true** means to disable modification of the system time, and **false** means the opposite.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
dateTimeManager.disallowModifyDateTime(wantTemp, true, (error) => {
if (error) {
console.log("error code:" + error.code + " error message:" + error.message);
}
})
```
## dateTimeManager.disallowModifyDateTime<sup>10+</sup>
disallowModifyDateTime(admin: Want, disallow: boolean): Promise\<void>
Disables modification of the system time. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| disallow | boolean | Yes| Whether to disable modification of the system time. The value **true** means to disable modification of the system time, and **false** means the opposite.|
**Return value**
| Type | Description |
| ----- | ----------------------------------- |
| Promise\<void> | that returns no value. If the operation fails, an error object is thrown.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
dateTimeManager.disallowModifyDateTime(wantTemp, true).then(() => {
}).catch((error) => {
console.log("error code:" + error.code + " error message:" + error.message);
})
```
## dateTimeManager.isModifyDateTimeDisallowed<sup>10+</sup>
isModifyDateTimeDisallowed(admin: Want, callback: AsyncCallback\<boolean>): void
Checks whether modification of the system time is disabled. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| callback | AsyncCallback\<boolean> | Yes| Callback used to return the result. The value **true** means that modification of the system time is disabled, and **false** means the opposite.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
dateTimeManager.isModifyDateTimeDisallowed(wantTemp, (error) => {
if (error) {
console.log("error code:" + error.code + " error message:" + error.message);
}
})
```
## dateTimeManager.isModifyDateTimeDisallowed<sup>10+</sup>
isModifyDateTimeDisallowed(admin: Want): Promise\<boolean>
Checks whether modification of the system time is disabled. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
**Return value**
| Type | Description |
| ----- | ----------------------------------- |
| Promise\<boolean> | Promise Promise used to return the result. The value **true** means that modification of the system time is disabled, and **false** means the opposite.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
dateTimeManager.disallowModifyDateTime(wantTemp).then(() => {
}).catch((error) => {
console.log("error code:" + error.code + " error message:" + error.message);
})
```
# @ohos.file.fileAccess (User File Access and Management)
The **fileAccess** module is a framework for accessing and operating user files based on the ExtensionAbility mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards.
The **fileAccess** module provides a framework for accessing and operating user files based on the ExtensionAbility mechanism. This module interacts with file management services, such as the media library and external storage management service, and provides a set of unified interfaces for system applications to access and manage files. The media library service allows access to user files on local and distributed devices. The external storage management service allows access to the user files stored on devices, such as shared disks, USB flash drives, and SD cards.
>**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.
>- The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **picker** and **fs**.
>- The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
> - 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.
> - The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **FilePicker** and **FileManager**.
## Modules to Import
......@@ -16,9 +15,11 @@ import fileAccess from '@ohos.file.fileAccess';
## fileAccess.getFileAccessAbilityInfo
getFileAccessAbilityInfo( ) : Promise&lt;Array&lt;Want&gt;&gt;
getFileAccessAbilityInfo() : Promise&lt;Array&lt;Want&gt;&gt;
Obtains information about all wants with **extension** set to **fileAccess** in the system. A want is a basic communication component used to start services. This API uses a promise to return the result.
Obtains information about all Wants with **extension** set to **fileAccess** in the system. A Want contains information for starting an ability. This API uses a promise to return the result.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -26,9 +27,13 @@ Obtains information about all wants with **extension** set to **fileAccess** in
**Return value**
| Type| Description|
| --- | -- |
| Promise&lt;Array&lt;Want&gt;&gt; | Promise used to return the **want** information obtained.|
| Type| Description|
| --- | -- |
| Promise&lt;Array&lt;[Want](js-apis-app-ability-want.md)&gt;&gt; | Promise used to return the Want information obtained.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -46,9 +51,11 @@ Obtains information about all wants with **extension** set to **fileAccess** in
## fileAccess.getFileAccessAbilityInfo
getFileAccessAbilityInfo(callback: AsyncCallback&lt;Array&lt;Want&gt;&gt;): void;
getFileAccessAbilityInfo(callback: AsyncCallback&lt;Array&lt;Want&gt;&gt;): void
Obtains information about all Wants with **extension** set to **fileAccess** in the system. A Want contains information for starting an ability. This API uses an asynchronous callback to return the result.
Obtains information about all wants with **extension** set to **fileAccess** in the system. A want is a basic communication component used to start services. This API uses an asynchronous callback to return the result.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -56,9 +63,13 @@ Obtains information about all wants with **extension** set to **fileAccess** in
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;Array&lt;Want&gt;&gt; | Yes| Promise used to return the **want** information obtained.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;Array&lt;[Want](js-apis-app-ability-want.md)&gt;&gt; | Yes| Promise used to return the Want information obtained.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -82,7 +93,9 @@ Obtains information about all wants with **extension** set to **fileAccess** in
createFileAccessHelper(context: Context, wants: Array&lt;Want&gt;) : FileAccessHelper
Synchronously creates a **Helper** object to connect to the specified wants. The **Helper** object provides file access and management capabilities.
Synchronously creates a **Helper** object to connect to the specified Wants. The **Helper** object provides file access and management capabilities.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -90,16 +103,20 @@ Synchronously creates a **Helper** object to connect to the specified wants. The
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| context | Context | Yes| Context of the ability.|
| wants | Array&lt;Want&gt; | Yes| Wants to connect.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| context | [Context](js-apis-inner-application-context.md) | Yes| Context of the ability.|
| wants | Array&lt;[Want](js-apis-app-ability-want.md)&gt; | Yes| Wants to connect.|
**Return value**
| Type| Description|
| --- | -- |
| FileAccessHelper | **Helper** object created.|
| Type| Description|
| --- | -- |
| [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -131,21 +148,27 @@ createFileAccessHelper(context: Context) : FileAccessHelper
Synchronously creates a **Helper** object to connect to all file management services in the system.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| context | Context | Yes| Context of the ability.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| context | [Context](js-apis-inner-application-context.md) | Yes| Context of the ability.|
**Return value**
| Type| Description|
| --- | -- |
| FileAccessHelper | **Helper** object created.|
| Type| Description|
| --- | -- |
| [FileAccessHelper](#fileaccesshelper) | **Helper** object created.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -164,55 +187,91 @@ Synchronously creates a **Helper** object to connect to all file management serv
}
```
## FileAccessHelper.getRoots
## FileInfo
Provides the file or directory attribute information and APIs.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
getRoots( ) : Promise&lt;RootIterator&gt;
### Attributes
Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext).
| Name| Type | Readable| Writable| Description |
| ------ | ------ | -------- | ------ | -------- |
| uri | string | Yes| No| URI of the file or directory.|
| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the file or directory.|
| fileName | string | Yes| No| Name of the file or directory.|
| mode | number | Yes| No| Permissions on the file or directory.|
| size | number | Yes| No| Size of the file or directory.|
| mtime | number | Yes| No| Time when the file or directory was last modified.|
| mimeType | string | Yes| No| Multipurpose Internet Mail Extensions (MIME) type of the file or directory.|
### listFile
listFile(filter?: Filter) : FileIterator
Synchronously obtains a **FileIterator** object that lists the next-level files (directories) matching the conditions of the filter from a directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, only built-in storage devices support the file filter.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
**Return value**
| Type| Description|
| --- | -- |
| Promise&lt;RootIterator&gt; | Promise used to return the **RootIterator** object obtained.|
| Type| Description|
| --- | -- |
| [FileIterator](#fileiterator) | **FileIterator** object obtained.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
async getRoots() {
let rootIterator = null;
let rootinfos = [];
let isDone = false;
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
rootIterator = await fileAccessHelper.getRoots();
if (!rootIterator) {
console.error("getRoots interface returns an undefined object");
return;
}
while (!isDone) {
let result = rootIterator.next();
console.log("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
rootinfos.push(result.value);
}
} catch (error) {
console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
// fileInfoDir indicates information about a directory.
// let filter = { suffix : [".txt", ".jpg", ".xlsx"] };
let fileInfoDir = fileInfos[0];
let subfileInfos = [];
let isDone = false;
try {
let fileIterator = fileInfoDir.listFile();
// listFile() with the filter implementation.
// let fileIterator = rootInfo.listFile(filter);
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
return;
}
while (!isDone) {
let result = fileIterator.next();
console.log("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
subfileInfos.push(result.value);
}
} catch (error) {
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
## FileAccessHelper.getRoots
### scanFile
scanFile(filter?: Filter) : FileIterator;
getRoots(callback:AsyncCallback&lt;RootIterator&gt;) : void;
Synchronously obtains a **FileIterator** object that recursively retrieves the files matching the conditions of the filter from a directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, this API supports only built-in storage devices.
Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses an asynchronous callback to return the result.
The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo) through [next()](#rootiteratornext).
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -220,59 +279,127 @@ The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo)
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;RootIterator&gt; | Yes| Promise used to return the **RootIterator** object obtained.|
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
**Return value**
| Type| Description|
| --- | -- |
| [FileIterator](#fileiterator) | **FileIterator** object obtained.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
async getRoots() {
let rootinfos = [];
let isDone = false;
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.getRoots(function (err, rootIterator) {
if (err) {
console.error("Failed to getRoots in async, errCode:" + err.code + ", errMessage:" + err.message);
return;
}
while (!isDone) {
let result = rootIterator.next();
console.log("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
rootinfos.push(result.value);
}
});
} catch (error) {
console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
// fileInfoDir indicates information about a directory.
// let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
let fileInfoDir = fileInfos[0];
let subfileInfos = [];
let isDone = false;
try {
let fileIterator = fileInfoDir.scanFile();
// scanFile() with the filter implementation.
// let fileIterator = rootInfo.scanFile(filter);
if (!fileIterator) {
console.error("scanFile interface returns an undefined object");
return;
}
while (!isDone) {
let result = fileIterator.next();
console.log("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
subfileInfos.push(result.value);
}
} catch (error) {
console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
## RootInfo.listfile
## FileIterator
listFile(filter?: Filter) : FileIterator
Provides the **FileIterator** object.
Synchronously obtains the **FileIterator** object of the first-level files (directory) matching the conditions of the filter from the device root node. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext).
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Parameters**
### next
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
next() : { value: FileInfo, done: boolean }
Obtains information about the next-level files or directories.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Return value**
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
| {value: [FileInfo](#fileinfo), done: boolean} | File or directory information obtained. This method traverses the specified directory until **true** is returned. The **value** field contains the file or directory information obtained.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## RootInfo
Provides the device's root attribute information and APIs.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
### Attributes
| Name| Type | Readable| Writable| Description |
| ------ | ------ | -------- | ------ | -------- |
| deviceType | number | Yes| No|Type of the device.|
| uri | string | Yes| No| Root directory URI of the device.|
| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the root directory.|
| displayName | string | Yes| No| Device name.|
| deviceFlags | number | Yes| No| Capabilities supported by the device.|
### listFile
listFile(filter?: Filter) : FileIterator
Synchronously obtains a **FileIterator** object that lists the first-level files (directories) matching the conditions of the filter from the device root directory and returns [FileInfo](#fileinfo) using [next()](#next). Currently, only built-in storage devices support the file filter.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
**Return value**
| Type| Description|
| --- | -- |
| [FileIterator](#fileiterator) | **FileIterator** object obtained.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -284,7 +411,7 @@ Synchronously obtains the **FileIterator** object of the first-level files (dire
let isDone = false;
try {
let fileIterator = rootInfo.listFile();
// listFile contains the filter implementation.
// listFile() with the filter implementation.
// let fileIterator = rootInfo.listFile(filter);
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
......@@ -302,11 +429,13 @@ Synchronously obtains the **FileIterator** object of the first-level files (dire
}
```
## RootInfo.scanFile
### scanFile
scanFile(filter?: Filter) : FileIterator
Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the device root node synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext).
Synchronously obtains a **FileIterator** object that recursively retrieves the files matching the conditions of the filter from the device root directory and returns [FileInfo](#fileinfo)using [next()](#next). Currently, this API supports only built-in storage devices.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -314,15 +443,19 @@ Recursively obtains the **FileIterator** object of the files matching the condit
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | [Filter](js-apis-file-fs.md#filter) | No| **Filter** object. |
**Return value**
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
| Type| Description|
| --- | -- |
| [FileIterator](#fileiterator) | **FileIterator** object obtained.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -334,7 +467,7 @@ Recursively obtains the **FileIterator** object of the files matching the condit
let isDone = false;
try {
let fileIterator = rootInfo.scanFile();
// scanFile contains the filter implementation.
// scanFile with the filter implementation.
// let fileIterator = rootInfo.scanFile(filter);
if (!fileIterator) {
console.error("scanFile interface returns undefined object");
......@@ -352,61 +485,100 @@ Recursively obtains the **FileIterator** object of the files matching the condit
}
```
## FileInfo.listfile
## RootIterator
listFile(filter?: Filter) : FileIterator
Provides an iterator object of the device root directory.
Synchronously obtains the **FileIterator** object of the next-level files (directories) matching the conditions of the filter from a directory. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext).
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Parameters**
### next
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
next() : { value: RootInfo, done: boolean }
Obtains the root directory of the next-level device.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Return value**
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
| {value: [RootInfo](#rootinfo), done: boolean} | Root directory information obtained. This method traverses the directory until **true** is returned. The **value** field contains the root directory information.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## FileAccessHelper
Provides a **FileAccessHelper** object.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
### getRoots
getRoots() : Promise&lt;RootIterator&gt;
Obtains information about the device root nodes of the file management service connected to the **Helper** object. This API uses a promise to return a **RootIterator** object,
which returns [RootInfo](#rootinfo) by using [next](#next-1).
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Return value**
| Type| Description|
| --- | -- |
| Promise&lt;[RootIterator](#rootiterator)&gt; | Promise used to return the **RootIterator** object obtained.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
// fileInfoDir specifies the target directory.
// let filter = { suffix : [".txt", ".jpg", ".xlsx"] };
let fileInfoDir = fileInfos[0];
let subfileInfos = [];
let isDone = false;
try {
let fileIterator = fileInfoDir.listFile();
// listFile contains the filter implementation.
// let fileIterator = rootInfo.listFile(filter);
if (!fileIterator) {
console.error("listFile interface returns an undefined object");
return;
}
while (!isDone) {
let result = fileIterator.next();
console.log("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
subfileInfos.push(result.value);
async getRoots() {
let rootIterator = null;
let rootinfos = [];
let isDone = false;
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
rootIterator = await fileAccessHelper.getRoots();
if (!rootIterator) {
console.error("getRoots interface returns an undefined object");
return;
}
while (!isDone) {
let result = rootIterator.next();
console.log("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
rootinfos.push(result.value);
}
} catch (error) {
console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
}
} catch (error) {
console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
## FileInfo.scanfile
### getRoots
scanFile(filter?: Filter) : FileIterator;
getRoots(callback:AsyncCallback&lt;RootIterator&gt;) : void
Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from a directory synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext).
Obtains information about the device root nodes of the file management service connected to the **Helper** object. This API uses an asynchronous callback to return a **RootIterator** object,
which returns [RootInfo](#rootinfo) by using [next](#next-1).
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -415,45 +587,41 @@ Recursively obtains the **FileIterator** object of the files matching the condit
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;[RootIterator](#rootiterator)&gt; | Yes| Callback invoked to return the **RootIterator** object obtained.|
**Return value**
**Error codes**
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
// fileInfoDir specifies the target directory.
// let filter = {suffix : [".txt", ".jpg", ".xlsx"]};
let fileInfoDir = fileInfos[0];
let subfileInfos = [];
let isDone = false;
try {
let fileIterator = fileInfoDir.scanFile();
// scanFile contains the filter implementation.
// let fileIterator = rootInfo.scanFile(filter);
if (!fileIterator) {
console.error("scanFile interface returns an undefined object");
return;
}
while (!isDone) {
let result = fileIterator.next();
console.log("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
subfileInfos.push(result.value);
async getRoots() {
let rootinfos = [];
let isDone = false;
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.getRoots(function (err, rootIterator) {
if (err) {
console.error("Failed to getRoots in async, errCode:" + err.code + ", errMessage:" + err.message);
return;
}
while (!isDone) {
let result = rootIterator.next();
console.log("next result = " + JSON.stringify(result));
isDone = result.done;
if (!isDone)
rootinfos.push(result.value);
}
});
} catch (error) {
console.error("getRoots failed, errCode:" + error.code + ", errMessage:" + error.message);
}
} catch (error) {
console.error("scanFile failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
## FileAccessHelper.createFile
### createFile
createFile(uri: string, displayName: string) : Promise&lt;string&gt;
......@@ -467,7 +635,7 @@ Creates a file in a directory. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the parent directory for the file to create.|
| uri | string | Yes| URI of the destination directory for the file to create.|
| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
**Return value**
......@@ -476,6 +644,10 @@ Creates a file in a directory. This API uses a promise to return the result.
| --- | -- |
| Promise&lt;string&gt; | Promise used to return the URI of the file created.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
......@@ -498,9 +670,9 @@ Creates a file in a directory. This API uses a promise to return the result.
};
```
## FileAccessHelper.createFile
### createFile
createFile(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void;
createFile(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
Creates a file in a directory. This API uses an asynchronous callback to return the result.
......@@ -512,9 +684,13 @@ Creates a file in a directory. This API uses an asynchronous callback to return
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the parent directory for the file to create.|
| uri | string | Yes| URI of the destination directory for the file to create.|
| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the file created.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the file created.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -538,7 +714,7 @@ Creates a file in a directory. This API uses an asynchronous callback to return
};
```
## FileAccessHelper.mkDir
### mkDir
mkDir(parentUri: string, displayName: string) : Promise&lt;string&gt;
......@@ -552,7 +728,7 @@ Creates a directory. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| parentUri | string | Yes| URI of the parent directory for the directory to create.|
| parentUri | string | Yes| URI of the destination directory for the directory to create.|
| displayName | string | Yes| Name of the directory to create.|
**Return value**
......@@ -561,6 +737,10 @@ Creates a directory. This API uses a promise to return the result.
| --- | -- |
| Promise&lt;string&gt; | Promise used to return the URI of the directory created.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
......@@ -583,9 +763,9 @@ Creates a directory. This API uses a promise to return the result.
};
```
## FileAccessHelper.mkDir
### mkDir
mkDir(parentUri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void;
mkDir(parentUri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
Creates a directory. This API uses an asynchronous callback to return the result.
......@@ -597,9 +777,13 @@ Creates a directory. This API uses an asynchronous callback to return the result
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| parentUri | string | Yes| URI of the parent directory for the directory to create.|
| parentUri | string | Yes| URI of the destination directory for the directory to create.|
| displayName | string | Yes| Name of the directory to create.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the directory created.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the directory created.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -623,7 +807,7 @@ Creates a directory. This API uses an asynchronous callback to return the result
};
```
## FileAccessHelper.openFile
### openFile
openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
......@@ -644,13 +828,17 @@ Opens a file. This API uses a promise to return the result.
| Type| Description|
| --- | -- |
| Promise&lt;number&gt; | Promise used to return the file descriptor of the file opened.|
| Promise&lt;number&gt; | Promise used to return the file descriptor (FD) of the file opened.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
// The media library URI is used as an example.
//In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
let targetUri = "datashare:///media/file/100";
try {
......@@ -661,9 +849,9 @@ Opens a file. This API uses a promise to return the result.
};
```
## FileAccessHelper.openFile
### openFile
openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void;
openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void
Opens a file. This API uses an asynchronous callback to return the result.
......@@ -677,13 +865,17 @@ Opens a file. This API uses an asynchronous callback to return the result.
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file to open.|
| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the file descriptor of the file opened.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the FD of the file opened.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
// The media library URI is used as an example.
//In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
let targetUri = "datashare:///media/file/100";
try {
......@@ -700,7 +892,7 @@ Opens a file. This API uses an asynchronous callback to return the result.
};
```
## FileAccessHelper.delete
### delete
delete(uri: string) : Promise&lt;number&gt;
......@@ -722,11 +914,15 @@ Deletes a file or directory. This API uses a promise to return the result.
| --- | -- |
| Promise&lt;number&gt | Promise used to return the result.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
// The media library URI is used as an example.
//In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
let targetUri = "datashare:///media/file/100";
try {
......@@ -739,9 +935,9 @@ Deletes a file or directory. This API uses a promise to return the result.
};
```
## FileAccessHelper.delete
### delete
delete(uri: string, callback: AsyncCallback&lt;number&gt;) : void;
delete(uri: string, callback: AsyncCallback&lt;number&gt;) : void
Deletes a file or directory. This API uses an asynchronous callback to return the result.
......@@ -754,13 +950,17 @@ Deletes a file or directory. This API uses an asynchronous callback to return th
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or directory to delete.|
| callback | AsyncCallback&lt;number&gt; | Yes| Promise used to return the result.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
// The media library URI is used as an example.
//In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
let targetUri = "datashare:///media/file/100";
try {
......@@ -777,11 +977,11 @@ Deletes a file or directory. This API uses an asynchronous callback to return th
};
```
## FileAccessHelper.move
### move
move(sourceFile: string, destFile: string) : Promise&lt;string&gt;
Moves a file or directory. This API uses a promise to return the result.
Moves a file or directory. This API uses a promise to return the result. Currently, this API does not support move of files or directories across devices.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -792,7 +992,7 @@ Moves a file or directory. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFile | string | Yes| URI of the file or directory to move.|
| destFile | string | Yes| URI of the directory, to which the file or directory will be moved.|
| destFile | string | Yes| URI of the destination directory, to which the file or directory will be moved.|
**Return value**
......@@ -800,11 +1000,15 @@ Moves a file or directory. This API uses a promise to return the result.
| ----- | ------ |
| Promise&lt;string&gt; | Promise used to return the URI of the file or directory in the destination directory.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
// The media library URI is used as an example.
//In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
// In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
......@@ -817,11 +1021,11 @@ Moves a file or directory. This API uses a promise to return the result.
};
```
## FileAccessHelper.move
### move
move(sourceFile: string, destFile: string, callback: AsyncCallback&lt;string&gt;) : void;
move(sourceFile: string, destFile: string, callback: AsyncCallback&lt;string&gt;) : void
Moves a file or directory. This API uses an asynchronous callback to return the result.
Moves a file or directory. This API uses an asynchronous callback to return the result. Currently, this API does not support move of files or directories across devices.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -832,14 +1036,18 @@ Moves a file or directory. This API uses an asynchronous callback to return the
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFile | string | Yes| URI of the file or directory to move.|
| destFile | string | Yes| URI of the directory, to which the file or directory will be moved.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the file or directory in the destination directory.|
| destFile | string | Yes| URI of the destination directory, to which the file or directory will be moved.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the file or directory in the destination directory.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
// The media library URI is used as an example.
//In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
// In the sample code, sourceFile destFile indicates the file or directory in the Download directory. The URI is the URI in fileInfo.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
......@@ -857,7 +1065,7 @@ Moves a file or directory. This API uses an asynchronous callback to return the
};
```
## FileAccessHelper.rename
### rename
rename(uri: string, displayName: string) : Promise&lt;string&gt;
......@@ -880,6 +1088,10 @@ Renames a file or directory. This API uses a promise to return the result.
| --- | -- |
| Promise&lt;string&gt; | Promise used to return the URI of the renamed file or directory.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
......@@ -896,9 +1108,9 @@ Renames a file or directory. This API uses a promise to return the result.
};
```
## FileAccessHelper.rename
### rename
rename(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void;
rename(uri: string, displayName: string, callback: AsyncCallback&lt;string&gt;) : void
Renames a file or directory. This API uses an asynchronous callback to return the result.
......@@ -912,7 +1124,11 @@ Renames a file or directory. This API uses an asynchronous callback to return th
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or directory to rename.|
| displayName | string | Yes| New name of the file or directory, which can contain the file name extension.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the renamed file or directory.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the URI of the renamed file or directory.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -935,7 +1151,7 @@ Renames a file or directory. This API uses an asynchronous callback to return th
};
```
## FileAccessHelper.access
### access
access(sourceFileUri: string) : Promise&lt;boolean&gt;
......@@ -949,7 +1165,7 @@ Checks whether a file or directory exists. This API uses a promise to return the
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFileUri | string | Yes| URI of the file or directory.|
| sourceFileUri | string | Yes| URI of the file or directory to check.|
**Return value**
......@@ -957,6 +1173,10 @@ Checks whether a file or directory exists. This API uses a promise to return the
| --- | -- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
```js
......@@ -976,9 +1196,9 @@ Checks whether a file or directory exists. This API uses a promise to return the
};
```
## FileAccessHelper.access
### access
access(sourceFileUri: string, callback: AsyncCallback&lt;boolean&gt;) : void;
access(sourceFileUri: string, callback: AsyncCallback&lt;boolean&gt;) : void
Checks whether a file or directory exists. This API uses an asynchronous callback to return the result.
......@@ -990,8 +1210,12 @@ Checks whether a file or directory exists. This API uses an asynchronous callbac
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFileUri | string | Yes| URI of the file or directory.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Promise used to return the result.|
| sourceFileUri | string | Yes| URI of the file or directory to check.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result.|
**Error codes**
For details about error codes, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
**Example**
......@@ -1017,11 +1241,11 @@ Checks whether a file or directory exists. This API uses an asynchronous callbac
};
```
## FileAccessHelper.getFileInfoFromUri<sup>10+</sup>
### getFileInfoFromUri<sup>10+</sup>
getFileInfoFromUri(uri: string) : Promise<FileInfo>;
getFileInfoFromUri(uri: string) : Promise\<FileInfo>
Obtains a [FileInfo](#fileinfo) object based on the specified URI. This API uses a promise to return the result.
Obtains a **FileInfo** object based on the specified URI. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -1037,7 +1261,7 @@ Obtains a [FileInfo](#fileinfo) object based on the specified URI. This API uses
| Type| Description|
| --- | -- |
| [FileInfo](#fileinfo) | Promise used to return the **FileInfo** object obtained.|
| Promise\<[FileInfo](#fileinfo)> | Promise used to return the **FileInfo** object obtained.|
**Example**
......@@ -1054,11 +1278,11 @@ Obtains a [FileInfo](#fileinfo) object based on the specified URI. This API uses
};
```
## FileAccessHelper.getFileInfoFromUri<sup>10+</sup>
### getFileInfoFromUri<sup>10+</sup>
getFileInfoFromUri(uri: string, callback: AsyncCallback<FileInfo>) : void;
getFileInfoFromUri(uri: string, callback: AsyncCallback\<FileInfo>) : void
Obtains a [FileInfo](#fileinfo) object based on the specified URI. This API uses an asynchronous callback to return the result.
Obtains a **FileInfo** object based on the specified URI. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -1066,10 +1290,10 @@ Obtains a [FileInfo](#fileinfo) object based on the specified URI. This API uses
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of a file or directory.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the **FileInfo** object obtained.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or directory.|
| callback | AsyncCallback&lt;[FileInfo](#fileinfo)&gt; | Yes| Callback invoked to return the **FileInfo** object obtained.|
**Example**
......@@ -1093,11 +1317,11 @@ Obtains a [FileInfo](#fileinfo) object based on the specified URI. This API uses
```
## FileAccessHelper.getFileInfoFromRelativePath<sup>10+</sup>
### getFileInfoFromRelativePath<sup>10+</sup>
getFileInfoFromRelativePath(relativePath: string) : Promise<FileInfo>;
getFileInfoFromRelativePath(relativePath: string) : Promise\<FileInfo>
Obtains a [FileInfo](#fileinfo) object based on the specified relative path. This API uses a promise to return the result.
Obtains a **FileInfo** object based on the **relativePath**. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -1107,19 +1331,19 @@ Obtains a [FileInfo](#fileinfo) object based on the specified relative path. Thi
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| relativePath | string | Yes| Relative path of a file or directory.|
| relativePath | string | Yes| Relative path of the file or directory.|
**Return value**
| Type| Description|
| --- | -- |
| [FileInfo](#fileinfo) | Promise used to return the **FileInfo** object obtained.|
| Promise\<[FileInfo](#fileinfo)> | Promise used to return the **FileInfo** object obtained.|
**Example**
```js
// The relative path of the media library is used as an example.
// In the sample code, relativePath indicates the download directory, which is the relativePath in fileInfo.
// The relative path of the Media Library is used as an example.
// In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
// You can use the relativePath obtained.
let relativePath = "Download/";
try {
......@@ -1130,11 +1354,11 @@ Obtains a [FileInfo](#fileinfo) object based on the specified relative path. Thi
};
```
## FileAccessHelper.getFileInfoFromRelativePath<sup>10+</sup>
### getFileInfoFromRelativePath<sup>10+</sup>
getFileInfoFromRelativePath(relativePath: string, callback: AsyncCallback<FileInfo>) : void;
getFileInfoFromRelativePath(relativePath: string, callback: AsyncCallback\<FileInfo>) : void
Obtains a [FileInfo](#fileinfo) object based on the specified relative path. This API uses an asynchronous callback to return the result.
Obtains a **FileInfo** object based on the **relativePath**. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -1144,14 +1368,14 @@ Obtains a [FileInfo](#fileinfo) object based on the specified relative path. Thi
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| relativePath | string | Yes| Relative path of a file or directory.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the **FileInfo** object obtained.|
| relativePath | string | Yes| Relative path of the file or directory.|
| callback | AsyncCallback&lt;[FileInfo](#fileinfo)&gt; | Yes| Callback invoked to return the **FileInfo** object obtained.|
**Example**
```js
// The relative path of the media library is used as an example.
// In the sample code, relativePath indicates the download directory, which is the relativePath in fileInfo.
// The relative path of the Media Library is used as an example.
// In the sample code, relativePath indicates the Download directory, which is the relativePath in fileInfo.
// You can use the relativePath obtained.
let relativePath = "Download/";
try {
......@@ -1168,7 +1392,7 @@ Obtains a [FileInfo](#fileinfo) object based on the specified relative path. Thi
};
```
## FileAccessHelper.getThumbnail<sup>10+</sup>
### getThumbnail<sup>10+</sup>
getThumbnail(uri: string, size: image.Size) : Promise&lt;image.PixelMap&gt;
......@@ -1189,7 +1413,7 @@ Obtains the **Pixelmap** object of a media file based on the specified URI and s
| Type | Description |
| :---------------------------- | :----------------- |
| Promise&lt;image.PixelMap&gt; | Promise used to return the **Pixelmap** object obtained.|
| Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the **Pixelmap** object obtained.|
**Example**
......@@ -1210,7 +1434,7 @@ try {
};
```
## FileAccessHelper.getThumbnail<sup>10+</sup>
### getThumbnail<sup>10+</sup>
getThumbnail(uri: string, size: image.Size, callback: AsyncCallback&lt;image.PixelMap&gt;) : void
......@@ -1226,7 +1450,7 @@ Obtains the **Pixelmap** object of a media file based on the specified URI and s
| -------- | ----------------------------------- | ---- | ------------------ |
| uri | string | Yes | URI of the media file. |
| size | [image.Size](js-apis-image.md#size) | Yes | Size of the thumbnail. |
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes | Callback invoked to return the **Pixelmap** object obtained.|
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the **Pixelmap** object obtained.|
**Example**
......@@ -1252,79 +1476,277 @@ try {
};
```
## RootIterator.next
### query<sup>10+</sup>
next( ) : { value: RootInfo, done: boolean }
query(uri:string, metaJson: string) : Promise&lt;string&gt;
Obtains the next-level device root directory. **RootIterator** is an iterator object of the device root directory.
Queries the attribute information about a file or directory based on the URI. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ---------------------------------------------------- |
| uri | string | Yes | URI of the file or directory (obtained from [FileInfo](#fileinfo)).|
| metaJson | string | Yes | Attribute [FILEKEY](#filekey10) to query. |
**Return value**
| Type| Description|
| --- | -- |
| {value: RootInfo, done: boolean} | Root directory information obtained. This API traverses the directory until **done** returns **true**. The **value** field contains the root directory information.|
| Type | Description |
| :-------------------- | :------------------------------- |
| Promise&lt;string&gt; | Promised used to return the attribute queried and the value obtained.|
**Example**
## FileIterator.next
```js
var imageFileRelativePath = "Download/queryTest/image/01.jpg";
var jsonStrSingleRelativepath = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
var fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath);
let queryResult = await fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath);
console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path);
} catch (error) {
console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message);
};
```
next( ) : { value: FileInfo, done: boolean }
### query<sup>10+</sup>
Obtains the information about the next-level file or directory. **FileIterator** is an iterator object of a directory.
query(uri:string, metaJson: string, callback: AsyncCallback&lt;string&gt;) : void
Queries the attribute information about a file or directory based on the URI. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------------------------------- |
| uri | string | Yes | URI of the file or directory (obtained from [FileInfo](#fileinfo)).|
| metaJson | string | Yes | Attribute [FILEKEY](#filekey10) to query. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the attribute queried and the value obtained. |
**Example**
```js
var imageFileRelativePath = "Download/queryTest/image/01.jpg";
var jsonStrSingleRelativepath = JSON.stringify({ [fileAccess.FileKey.RELATIVE_PATH]: "" });
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
var fileInfo = await fileAccessHelper.getFileInfoFromRelativePath(imageFileRelativePath);
fileAccessHelper.query(fileInfo.uri, jsonStrSingleRelativepath, (err, queryResult)=>{
if (err) {
console.log("query_file_single faf query Failed, errCode:" + err.code + ", errMessage:" + err.message);
return;
}
console.log("query_file_single faf query, queryResult.relative_path: " + JSON.parse(queryResult).relative_path);
})
} catch (error) {
console.error("query_file_single faf query failed, error.code :" + error.code + ", errorMessage :" + error.message);
};
```
### copy<sup>10+</sup>
copy(sourceUri: string, destUri: string, force?: boolean) : Promise&lt;Array&lt;CopyResult&gt;&gt;
Copies a file or directory. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------- | ---- | ------------------------------------------------------------ |
| sourceUri | string | Yes | URI of the file or directory to copy, for example, **datashare:///media/file/102**. |
| destUri | string | Yes | URI of the destination directory, for example, **datashare:///media/file/101**. |
| force | boolean | No | Whether to forcibly overwrite the file with the same name. <br>If **force** is **true**, the file with the same name will be overwritten. If **force** is **false** or not specified, the file with the same name will not be overwritten.|
**Return value**
| Type| Description|
| --- | -- |
| {value: FileInfo, done: boolean} | File or directory information obtained. This API traverses the specified directory until **done** returns **true**. The **value** field contains the file or directory information obtained.|
| Type | Description |
| :------------------------------------------------------ | :----------------------------------------------------------- |
| Promise&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Promise used to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
## RootInfo
Example 1: Copy a file with **force** unspecified.
Represents the root attribute information and interface capabilities of a device.
```js
// The media library URI is used as an example.
// In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let copyResult = await fileAccessHelper.copy(sourceFile, destFile);
if (copyResult.length === 0) {
console.log("copy success");
} else {
for (let i = 0; i < copyResult.length; i++) {
console.error("errCode" + copyResult[i].errCode);
console.error("errMsg" + copyResult[i].errMsg);
console.error("sourceUri" + copyResult[i].sourceUri);
console.error("destUri" + copyResult[i].destUri);
}
}
} catch (error) {
console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
Example 2: Copy a file or directory when **force** set to **true**.
```js
// The media library URI is used as an example.
// In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
let copyResult = await fileAccessHelper.copy(sourceFile, destFile, true);
if (copyResult.length === 0) {
console.log("copy success");
} else {
for (let i = 0; i < copyResult.length; i++) {
console.error("errCode" + copyResult[i].errCode);
console.error("errMsg" + copyResult[i].errMsg);
console.error("sourceUri" + copyResult[i].sourceUri);
console.error("destUri" + copyResult[i].destUri);
}
}
} catch (error) {
console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
### copy<sup>10+</sup>
copy(sourceUri: string, destUri: string, callback: AsyncCallback&lt;Array&lt;CopyResult&gt;&gt;) : void
Copies a file or directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
### Attributes
**Parameters**
| Name| Type | Readable| Writable| Description |
| ------ | ------ | -------- | ------ | -------- |
| deviceType | number | Yes| No|Device type.|
| uri | string | Yes| No| Root directory URI of the device.|
| relativePath<sup>10+</sup> | string | Yes| No| Relative path of the root directory.|
| displayName | string | Yes| No| Device name.|
| deviceFlags | number | Yes| No| Capabilities supported by the device.|
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| sourceUri | string | Yes | URI of the file or directory to copy, for example, **datashare:///media/file/102**. |
| destUri | string | Yes | URI of the destination directory, for example, **datashare:///media/file/101**. |
| callback | AsyncCallback&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Yes | Callback invoked to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
## FileInfo
**Example**
Represents the file or directory attribute information and interface capabilities.
```js
// The media library URI is used as an example.
// In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.copy(sourceFile, destFile, async (err, copyResult) => {
if (err) {
console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message);
return;
}
if (copyResult.length === 0) {
console.log("copy success");
} else {
for (let i = 0; i < copyResult.length; i++) {
console.error("errCode" + copyResult[i].errCode);
console.error("errMsg" + copyResult[i].errMsg);
console.error("sourceUri" + copyResult[i].sourceUri);
console.error("destUri" + copyResult[i].destUri);
}
}
});
} catch (error) {
console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
### copy<sup>10+</sup>
copy(sourceUri: string, destUri: string, force: boolean, callback: AsyncCallback&lt;Array&lt;CopyResult&gt;&gt;) : void
Copies a file or directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
### Attributes
**Parameters**
| Name| Type | Readable| Writable| Description |
| ------ | ------ | -------- | ------ | -------- |
| uri | string | Yes| No| URI of the file or directory.|
| relativePath<sup>10+</sup> | string | Yes| No| Relative path of a file or directory.|
| fileName | string | Yes| No| Name of a file or directory.|
| mode | number | Yes| No| Permissions on the file or directory.|
| size | number | Yes| No| Size of the file or directory.|
| mtime | number | Yes| No| Time when the file or directory was last modified.|
| mimeType | string | Yes| No| MIME type of the file or directory.|
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| sourceUri | string | Yes | URI of the file or directory to copy, for example, **datashare:///media/file/102**. |
| destUri | string | Yes | URI of the destination directory, for example, **datashare:///media/file/101**. |
| force | boolean | Yes | Whether to forcibly overwrite the file with the same name. <br>If **force** is **true**, the file with the same name will be overwritten. If **force** is **false** or not specified, the file with the same name will not be overwritten.|
| callback | AsyncCallback&lt;Array&lt;[CopyResult](#copyresult10)&gt;&gt; | Yes | Callback invoked to return the result. If the file or directory is copied successfully, no information is returned. If the file copy fails, **copyResult** is returned.|
**Example**
```js
// The media library URI is used as an example.
// In the sample code, sourceFile indicates the file (directory) in the Download directory to copy, destFile indicates the destination directory in the Download directory, and uri is to URI in fileInfo.
// You can use the URI obtained.
let sourceFile = "datashare:///media/file/102";
let destFile = "datashare:///media/file/101";
try {
// Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper.
fileAccessHelper.copy(sourceFile, destFile, true, async (err, copyResult) => {
if (err) {
console.error("copy failed, errCode:" + err.code + ", errMessage:" + err.message);
return;
}
if (copyResult.length === 0) {
console.log("copy success");
} else {
for (let i = 0; i < copyResult.length; i++) {
console.error("errCode" + copyResult[i].errCode);
console.error("errMsg" + copyResult[i].errMsg);
console.error("sourceUri" + copyResult[i].sourceUri);
console.error("destUri" + copyResult[i].destUri);
}
}
});
} catch (error) {
console.error("copy failed, errCode:" + error.code + ", errMessage:" + error.message);
}
```
## CopyResult<sup>10+</sup>
Defines the information returned when the file copy operation fails. If the copy operation is successful, no information is returned.
**System capability**: SystemCapability.FileManagement.UserFileService
**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER
| Name | Type | Readable| Writable| Description |
| --------- | ------ | ---- | ---- | ----------------- |
| sourceUri | string | Yes | No | URI of the source file or directory. |
| destUri | string | Yes | No | URI of the conflict file. If the error is not caused by a conflict, **destUri** is empty.|
| errCode | number | Yes | No | Error code. |
| errMsg | string | Yes | No | Error information. |
## OPENFLAGS
Enumerates the modes for opening a file.
Enumerates the file open modes.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -1333,3 +1755,22 @@ Enumerates the modes for opening a file.
| READ | 0o0 | Read mode.|
| WRITE | 0o1 | Write mode.|
| WRITE_READ | 0o2 | Read/Write mode.|
## FILEKEY<sup>10+</sup>
Enumerates the keys of the file attributes to query.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileService
| Name | Value | Description |
| ------------- | ------------- | ----------------------------------- |
| DISPLAY_NAME | 'display_name' | Name of the file. |
| DATE_ADDED | 'date_added' | Date when the file was created, for example, **1501925454**. |
| DATE_MODIFIED | 'date_modified' | Date when a file was modified, for example, **1665310670**. |
| RELATIVE_PATH | 'relative_path' | Relative path of the file, for example, **Pictures/Screenshots/**.|
| FILE_SIZE | 'size' | Size of a file, in bytes. |
| WIDTH | 'width' | Width of the image file, in pixels. |
| HEIGHT | 'height' | Height of the image file, in pixels. |
| DURATION | 'duration' | Duration of the audio or video file, in milliseconds. |
......@@ -6,6 +6,12 @@ The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** in
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
## Usage
An **AbilityDelegator** object is obtained by calling [getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator) in **AbilityDelegatorRegistry**.
......@@ -30,10 +36,18 @@ Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to r
| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | AddAbilityMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback, data: ${JSON.stringify(data)}');
......@@ -70,10 +84,18 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | AddAbilityMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback');
......@@ -105,10 +127,18 @@ Removes an **AbilityMonitor** instance. This API uses an asynchronous callback t
| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | RemoveAbilityMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback');
......@@ -145,10 +175,18 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | RemoveAbilityMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
- Example
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback');
......@@ -180,10 +218,18 @@ Waits for the **Ability** instance that matches the **AbilityMonitor** instance
| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.|
| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | WaitAbilityMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback');
......@@ -196,7 +242,7 @@ let monitor = {
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityMonitor(monitor, (error : any, data : any) => {
if (error && error.code !== 0) {
if (error) {
console.error('waitAbilityMonitor fail, error: ${JSON.stringify(error)}');
} else {
console.log('waitAbilityMonitor success, data: ${JSON.stringify(data)}');
......@@ -220,10 +266,18 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo
| timeout | number | No | Maximum waiting time, in milliseconds. |
| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | WaitAbilityMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let timeout = 100;
function onAbilityCreateCallback(data) {
......@@ -268,10 +322,18 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo
| ----------------------------------------------------------- | -------------------------- |
| Promise\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Promise used to return the **Ability** instance.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | WaitAbilityMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback');
......@@ -305,7 +367,7 @@ Obtains the application context.
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let context = abilityDelegator.getAppContext();
......@@ -334,7 +396,7 @@ Obtains the lifecycle state of an ability.
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -360,10 +422,18 @@ Obtains the top ability of this application. This API uses an asynchronous callb
| -------- | ------------------------------------------------------------ | ---- | ------------------ |
| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | GetCurrentTopAbility failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -387,10 +457,18 @@ Obtains the top ability of this application. This API uses a promise to return t
| ----------------------------------------------------------- | -------------------------------------- |
| Promise\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Promise used to return the top ability.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | GetCurrentTopAbility failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -415,10 +493,30 @@ Starts an ability. This API uses an asynchronous callback to return the result.
| want | [Want](js-apis-application-want.md) | Yes | **Want** parameter for starting the ability. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Can not start invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16200001 | The caller has been released. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let want = {
bundleName: 'bundleName',
abilityName: 'abilityName'
......@@ -450,10 +548,30 @@ Starts an ability. This API uses a promise to return the result.
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Can not start invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation flag is forbidden. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16200001 | The caller has been released. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let want = {
bundleName: 'bundleName',
abilityName: 'abilityName'
......@@ -480,10 +598,18 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses an
| ability | UIAbility | Yes | Target ability. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.<br>\- **true**: The operation is successful.<br>\- **false**: The operation failed.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | DoAbilityForeground failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -516,10 +642,18 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p
| ----------------- | ------------------------------------------------------------ |
| Promise\<boolean> | Promise used to return the result.<br>\- **true**: The operation is successful.<br>\- **false**: The operation failed.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | DoAbilityForeground failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -547,10 +681,18 @@ Schedules the lifecycle state of an ability to **Background**. This API uses an
| ability | UIAbility | Yes | Target ability. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.<br>\- **true**: The operation is successful.<br>\- **false**: The operation failed.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | DoAbilityBackground failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -583,10 +725,18 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p
| ----------------- | ------------------------------------------------------------ |
| Promise\<boolean> | Promise used to return the result.<br>\- **true**: The operation is successful.<br>\- **false**: The operation failed.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | DoAbilityBackground failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let ability;
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -616,7 +766,7 @@ Prints log information to the unit test console.
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -641,7 +791,7 @@ Prints log information to the unit test console. This API uses an asynchronous c
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -673,7 +823,7 @@ Prints log information to the unit test console. This API uses a promise to retu
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -700,7 +850,7 @@ Executes a shell command. This API uses an asynchronous callback to return the r
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -728,7 +878,7 @@ Executes a shell command with the timeout period specified. This API uses an asy
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd';
let timeout = 100;
......@@ -762,7 +912,7 @@ Executes a shell command with the timeout period specified. This API uses a prom
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd';
let timeout = 100;
......@@ -788,10 +938,18 @@ Finishes the test and prints log information to the unit test console. This API
| code | number | Yes | Log code. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | FinishTest failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -821,10 +979,18 @@ Finishes the test and prints log information to the unit test console. This API
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | FinishTest failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let msg = 'msg';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
......@@ -848,10 +1014,18 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes
| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | AddAbilityStageMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let monitor = {
moduleName: 'moduleName',
......@@ -884,10 +1058,18 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | AddAbilityStageMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let monitor = {
moduleName: 'moduleName',
......@@ -915,10 +1097,18 @@ Removes an **AbilityStageMonitor** instance from the application memory. This AP
| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | RemoveAbilityStageMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let monitor = {
moduleName: 'moduleName',
......@@ -951,10 +1141,18 @@ Removes an **AbilityStageMonitor** object from the application memory. This API
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | RemoveAbilityStageMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let monitor = {
moduleName: 'moduleName',
......@@ -982,10 +1180,18 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A
| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.|
| callback | AsyncCallback\<AbilityStage> | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | WaitAbilityStageMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback');
......@@ -1023,10 +1229,18 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A
| -------------- | ------------------- |
| Promise\<AbilityStage> | Promise used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | WaitAbilityStageMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
function onAbilityCreateCallback(data) {
console.info('onAbilityCreateCallback');
......@@ -1059,10 +1273,18 @@ Waits a period of time for an **AbilityStage** instance that matches the conditi
| timeout | number | No | Maximum waiting time, in milliseconds.|
| callback | AsyncCallback\<AbilityStage> | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. |
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000100 | WaitAbilityStageMonitor failed. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let timeout = 100;
function onAbilityCreateCallback(data) {
......
......@@ -6,6 +6,12 @@ The **AbilityMonitor** module provides monitors for abilities that meet specifie
>
> 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
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
## Usage
**AbilityMonitor** can be used as an input parameter of [addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9) in **abilityDelegator** to listen for lifecycle changes of an ability.
......@@ -43,9 +49,9 @@ let monitor = {
onAbilityCreate: onAbilityCreateCallback
};
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor, (error : any) => {
if (error && error.code !== 0) {
if (error) {
console.error('addAbilityMonitor fail, error: ${JSON.stringify(error)}');
}
});
......
......@@ -6,6 +6,12 @@ The **AbilityRunningInfo** module defines the running information and state of a
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
```
## Usage
The ability running information is obtained by calling [getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos) in **abilityManager**.
......@@ -31,7 +37,7 @@ The ability running information is obtained by calling [getAbilityRunningInfos](
import abilitymanager from '@ohos.app.ability.abilityManager';
abilitymanager.getAbilityRunningInfos((error, data) => {
if (error && error.code !== 0) {
if (error) {
console.error('getAbilityRunningInfos fail, error: ${JSON.stringify(error)}');
} else {
console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}');
......
# AbilityStageMonitor
The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance.
The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -20,7 +21,7 @@ let monitor = {
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => {
if (error && error.code !== 0) {
if (error) {
console.error('waitAbilityStageMonitor fail, error: ${JSON.stringify(error)}');
} else {
console.log('waitAbilityStageMonitor success, data: ${JSON.stringify(data)}');
......
......@@ -6,6 +6,12 @@ The **ProcessInformation** module defines the running information of a process.
>
> 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
```ts
import appManager from '@ohos.app.ability.appManager';
```
## How to Use
The process information is obtained by calling [getRunningProcessInformation](js-apis-app-ability-appManager.md#appmanagergetrunningprocessinformation9) of the **appManager** module.
......@@ -14,7 +20,7 @@ The process information is obtained by calling [getRunningProcessInformation](js
import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation((error, data) => {
if (error && error.code !== 0) {
if (error) {
console.error('getRunningProcessInformation fail, error: ${JSON.stringify(error)}');
} else {
console.log('getRunningProcessInformation success, data: ${JSON.stringify(data)}');
......
......@@ -6,6 +6,12 @@ The **ShellCmdResult** module provides the shell command execution result.
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Readable| Writable| Description |
......@@ -20,12 +26,12 @@ The result is obtained by calling [executeShellCommand](js-apis-inner-applicatio
**Example**
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let abilityDelegator;
let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (error: any, data: any) => {
if (error && error.code !== 0) {
if (error) {
console.error('executeShellCommand fail, error: ${JSON.stringify(error)}');
} else {
console.log('executeShellCommand success, data: ${JSON.stringify(data)}');
......
......@@ -41,7 +41,6 @@ The APIs of this module return exceptions since API version 9. The following tab
## MessageSequence<sup>9+</sup>
Provides APIs for reading and writing data in specific format.
During RPC or IPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects.
### create
......@@ -99,9 +98,9 @@ Serializes a remote object and writes it to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900008 | proxy or remote object is invalid |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -140,9 +139,9 @@ Reads the remote object from **MessageSequence**. You can use this API to deseri
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -182,8 +181,8 @@ Writes an interface token to this **MessageSequence** object. The remote object
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -216,8 +215,8 @@ Reads the interface token from this **MessageSequence** object. The interface to
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ----- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -268,7 +267,7 @@ Obtains the capacity of this **MessageSequence** object.
**Return value**
| Type | Description|
| Type | Description |
| ------ | ----- |
| number | **MessageSequence** capacity obtained, in bytes.|
......@@ -290,7 +289,7 @@ Sets the size of the data contained in this **MessageSequence** object.
**Parameters**
| Name| Type | Mandatory| Description|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------ |
| size | number | Yes | Data size to set, in bytes.|
......@@ -326,8 +325,8 @@ Sets the storage capacity of this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------ |
| 1900011 | parcel memory alloc failed |
| -------- | -------- |
| 1900011 | parcel memory alloc failed |
**Example**
......@@ -352,7 +351,7 @@ Obtains the writable capacity (in bytes) of this **MessageSequence** object.
**Return value**
| Type| Description|
| Type | Description |
| ------ | ------ |
| number | Writable capacity of the **MessageSequence** instance, in bytes.|
......@@ -378,7 +377,7 @@ Obtains the readable capacity of this **MessageSequence** object.
**Return value**
| Type| Description|
| Type | Description |
| ------ | ------- |
| number | Readable capacity of the **MessageSequence** instance, in bytes.|
......@@ -404,7 +403,7 @@ Obtains the read position of this **MessageSequence** object.
**Return value**
| Type| Description|
| Type | Description |
| ------ | ------ |
| number | Read position obtained.|
......@@ -426,7 +425,7 @@ Obtains the write position of this **MessageSequence** object.
**Return value**
| Type| Description|
| Type | Description |
| ------ | ----- |
| number | Write position obtained.|
......@@ -449,7 +448,7 @@ Moves the read pointer to the specified position.
**Parameters**
| Name| Type| Mandatory| Description|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- |
| pos | number | Yes | Position from which data is to read.|
......@@ -481,7 +480,7 @@ Moves the write pointer to the specified position.
**Parameters**
| Name| Type| Mandatory| Description|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ----- |
| pos | number | Yes | Position from which data is to write.|
......@@ -511,17 +510,17 @@ Writes a byte value to this **MessageSequence** object.
**Parameters**
| Name| Type | Mandatory| Description|
| ----- | ------ | ---- | ----- |
| val | number | Yes| Byte value to write.|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ----- |
| val | number | Yes | Byte value to write.|
**Error codes**
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900009 | write data to message sequence failed |
| -------- | ------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -545,7 +544,7 @@ Reads the byte value from this **MessageSequence** object.
**Return value**
| Type | Description|
| Type | Description |
| ------ | ----- |
| number | Byte value read.|
......@@ -587,16 +586,16 @@ Writes a short integer to this **MessageSequence** object.
**Parameters**
| Name| Type | Mandatory| Description|
| ------ | ------ | --- | --- |
| val | number | Yes| Short integer to write.|
| ------ | ------ | --- | --- |
| val | number | Yes | Short integer to write.|
**Error codes**
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------ |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -629,8 +628,8 @@ Reads the short integer from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -670,8 +669,8 @@ Writes an integer to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -704,8 +703,8 @@ Reads the integer from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -745,8 +744,8 @@ Writes a long integer to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -779,8 +778,8 @@ Reads the long integer from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -811,17 +810,17 @@ Writes a floating-point number to this **MessageSequence** object.
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ---- | ---- | ----- |
| val | number | Yes| Floating-point number to write.|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ----- |
| val | number | Yes | Floating-point number to write.|
**Error codes**
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -854,8 +853,8 @@ Reads the floating-pointer number from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -895,8 +894,8 @@ Writes a double-precision floating-point number to this **MessageSequence** obje
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -929,8 +928,8 @@ Reads the double-precision floating-point number from this **MessageSequence** o
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -970,8 +969,8 @@ Writes a Boolean value to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1004,8 +1003,8 @@ Reads the Boolean value from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1045,8 +1044,8 @@ Writes a character to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1079,8 +1078,8 @@ Reads the character from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------ | --------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1120,8 +1119,8 @@ Writes a string to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1154,8 +1153,8 @@ Reads the string from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1195,8 +1194,8 @@ Writes a **Parcelable** object to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1241,16 +1240,16 @@ Reads a **Parcelable** object from this **MessageSequence** object to the specif
| Name| Type | Mandatory| Description |
| ------ | ------------------------- | ---- | ----------------------------------------- |
| dataIn | Parcelable | Yes | **Parcelable** object to read.|
| dataIn | Parcelable | Yes | **Parcelable** object to read.|
**Error codes**
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900010 | read data from message sequence failed |
| 1900012 | call js callback function failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
| 1900012 | call js callback function failed |
**Example**
......@@ -1304,8 +1303,8 @@ Writes a byte array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1339,8 +1338,8 @@ Reads a byte array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1381,8 +1380,8 @@ Reads the byte array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1423,8 +1422,8 @@ Writes a short array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ----- | ----- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1457,8 +1456,8 @@ Reads a short array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------ | ------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1498,8 +1497,8 @@ Reads the short array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1539,8 +1538,8 @@ Writes an integer array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ----- | --------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1573,8 +1572,8 @@ Reads an integer array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1614,8 +1613,8 @@ Reads the integer array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ----- | ------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1655,8 +1654,8 @@ Writes a long array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ----- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1689,8 +1688,8 @@ Reads a long array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------ |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1730,8 +1729,8 @@ Reads the long array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1771,8 +1770,8 @@ Writes a floating-point array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1805,8 +1804,8 @@ Reads a floating-point array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1846,8 +1845,8 @@ Reads the floating-point array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1887,8 +1886,8 @@ Writes a double-precision floating-point array to this **MessageSequence** objec
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -1921,8 +1920,8 @@ Reads a double-precision floating-point array from this **MessageSequence** obje
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -1962,8 +1961,8 @@ Reads the double-precision floating-point array from this **MessageSequence** ob
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2003,8 +2002,8 @@ Writes a Boolean array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -2037,8 +2036,8 @@ Reads a Boolean array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2078,8 +2077,8 @@ Reads the Boolean array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2119,8 +2118,8 @@ Writes a character array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------ |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -2153,8 +2152,8 @@ Reads a character array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2194,8 +2193,8 @@ Reads the character array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2236,8 +2235,8 @@ Writes a string array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -2270,8 +2269,8 @@ Reads a string array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2311,8 +2310,8 @@ Reads the string array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2346,8 +2345,8 @@ Writes information to this **MessageSequence** object indicating that no excepti
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -2388,15 +2387,17 @@ Reads the exception information from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -2414,7 +2415,11 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message.
......@@ -2468,8 +2473,8 @@ Writes a **Parcelable** array to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -2524,9 +2529,9 @@ Reads a **Parcelable** array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| 1900012 | call js callback function failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
| 1900012 | call js callback function failed |
**Example**
......@@ -2585,8 +2590,8 @@ Writes an array of **IRemoteObject** objects to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------- |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -2632,8 +2637,8 @@ Reads an array of **IRemoteObject** objects from this **MessageSequence** object
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2685,8 +2690,8 @@ Reads the **IRemoteObject** object array from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -2731,11 +2736,11 @@ Closes a file descriptor. This API is a static method.
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
try {
rpc.MessageSequence.closeFileDescriptor(fd);
rpc.MessageSequence.closeFileDescriptor(file.fd);
} catch(error) {
console.info("rpc close file descriptor fail, errorCode " + error.code);
console.info("rpc close file descriptor fail, errorMessage" + error.message);
......@@ -2767,17 +2772,17 @@ Duplicates a file descriptor. This API is a static method.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------- |
| 1900013 | call os dup function failed |
| -------- | -------- |
| 1900013 | call os dup function failed |
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
try {
let newFd = rpc.MessageSequence.dupFileDescriptor(fd);
let newFd = rpc.MessageSequence.dupFileDescriptor(file.fd);
} catch(error) {
console.info("rpc dup file descriptor fail, errorCode " + error.code);
console.info("rpc dup file descriptor fail, errorMessage" + error.message);
......@@ -2802,13 +2807,13 @@ Checks whether this **MessageSequence** object contains file descriptors.
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let sequence = new rpc.MessageSequence();
let filePath = "path/to/file";
let r1 = sequence.containFileDescriptors();
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
try {
sequence.writeFileDescriptor(fd);
sequence.writeFileDescriptor(file.fd);
} catch(error) {
console.info("rpc write file descriptor fail, errorCode " + error.code);
console.info("rpc write file descriptor fail, errorMessage" + error.message);
......@@ -2841,18 +2846,18 @@ Writes a file descriptor to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------ |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let sequence = new rpc.MessageSequence();
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
try {
sequence.writeFileDescriptor(fd);
sequence.writeFileDescriptor(file.fd);
} catch(error) {
console.info("rpc write file descriptor fail, errorCode " + error.code);
console.info("rpc write file descriptor fail, errorMessage" + error.message);
......@@ -2878,18 +2883,18 @@ Reads the file descriptor from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let sequence = new rpc.MessageSequence();
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
try {
sequence.writeFileDescriptor(fd);
sequence.writeFileDescriptor(file.fd);
} catch(error) {
console.info("rpc write file descriptor fail, errorCode " + error.code);
console.info("rpc write file descriptor fail, errorMessage" + error.message);
......@@ -2921,8 +2926,8 @@ Writes an anonymous shared object to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------- |
| 1900003 | write to ashmem failed |
| -------- | ------- |
| 1900003 | write to ashmem failed |
**Example**
......@@ -2963,8 +2968,8 @@ Reads the anonymous shared object from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900004 | read from ashmem failed |
| -------- | -------- |
| 1900004 | read from ashmem failed |
**Example**
......@@ -3034,8 +3039,8 @@ Writes raw data to this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------ |
| 1900009 | write data to message sequence failed |
| -------- | -------- |
| 1900009 | write data to message sequence failed |
**Example**
......@@ -3075,8 +3080,8 @@ Reads raw data from this **MessageSequence** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900010 | read data from message sequence failed |
| -------- | -------- |
| 1900010 | read data from message sequence failed |
**Example**
......@@ -3103,7 +3108,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
>This class is no longer maintained since API version 9. You are advised to use [MessageSequence](#messagesequence9).
Provides APIs for reading and writing data in specific format.
During RPC, the sender can use the **write()** method provided by **MessageParcel** to write data in specific format to a **MessageParcel** object. The receiver can use the **read()** method provided by **MessageParcel** to read data in specific format from a **MessageParcel** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects.
### create
......@@ -4031,8 +4035,8 @@ Writes a sequenceable object to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | --------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4072,14 +4076,14 @@ Reads member variables from this **MessageParcel** object.
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | --------------------------------------- |
| Name| Type | Mandatory | Description |
| ------ | ----------------------------- | ------- | ---------------------------------------------- |
| dataIn | [Sequenceable](#sequenceabledeprecated) | Yes | Object that reads member variables from the **MessageParcel** object.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------- |
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -4128,8 +4132,8 @@ Writes a byte array to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | --------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4207,8 +4211,8 @@ Writes a short array to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | ----------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4283,8 +4287,8 @@ Writes an integer array to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | ----------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4429,14 +4433,14 @@ Writes a FloatArray to this **MessageParcel** object.
**Parameters**
| Name| Type| Mandatory| Description|
| Name| Type| Mandatory| Description |
| ---------- | -------- | ---- | --- |
| floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.|
**Return value**
| Type | Description |
| ------- | ----------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4457,7 +4461,7 @@ Reads a FloatArray from this **MessageParcel** object.
**Parameters**
| Name| Type| Mandatory| Description|
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ------ |
| dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.|
......@@ -4511,8 +4515,8 @@ Writes a DoubleArray to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | ----------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4587,8 +4591,8 @@ Writes a Boolean array to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | --------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4663,8 +4667,8 @@ Writes a character array to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | --------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4733,14 +4737,14 @@ Writes a string array to this **MessageParcel** object.
**Parameters**
| Name | Type | Mandatory| Description|
| Name | Type | Mandatory| Description |
| ----------- | -------- | ---- | ---------------- |
| stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.|
**Return value**
| Type | Description|
| ------- | --------------------------------- |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -4850,11 +4854,13 @@ Reads the exception information from this **MessageParcel** object.
**System capability**: SystemCapability.Communication.IPC.Core
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -4872,7 +4878,11 @@ Reads the exception information from this **MessageParcel** object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message.
......@@ -4918,8 +4928,8 @@ Writes a sequenceable array to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | --------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -5008,14 +5018,14 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object.
**Parameters**
| Name | Type | Mandatory| Description|
| Name | Type | Mandatory| Description |
| ----------- | --------------- | ---- | ----- |
| objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.|
**Return value**
| Type | Description |
| ------- | -------------------------------------------------------------------------------------------------------------------- |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -5060,7 +5070,7 @@ Reads an **IRemoteObject** array from this **MessageParcel** object.
**Parameters**
| Name | Type | Mandatory| Description|
| Name | Type | Mandatory| Description |
| ------- | --------------- | ---- | --------- |
| objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.|
......@@ -5107,8 +5117,8 @@ Reads the **IRemoteObject** array from this **MessageParcel** object.
**Return value**
| Type| Description|
| --------------- | -------- |
| Type | Description |
| --------------- | --------------------------- |
| IRemoteObject[] | **IRemoteObject** object array obtained.|
**Example**
......@@ -5162,10 +5172,10 @@ Closes a file descriptor. This API is a static method.
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
rpc.MessageParcel.closeFileDescriptor(fd);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
rpc.MessageParcel.closeFileDescriptor(file.fd);
```
### dupFileDescriptor<sup>8+</sup>
......@@ -5191,10 +5201,10 @@ Duplicates a file descriptor. This API is a static method.
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let newFd = rpc.MessageParcel.dupFileDescriptor(fd);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let newFd = rpc.MessageParcel.dupFileDescriptor(file.fd);
```
### containFileDescriptors<sup>8+</sup>
......@@ -5207,19 +5217,19 @@ Checks whether this **MessageParcel** object contains file descriptors.
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------------ |
| Type | Description |
| ------- | --------------------------------------------- |
| boolean |Returns **true** if the **MessageParcel** object contains file descriptors; returns **false** otherwise.|
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let r1 = parcel.containFileDescriptors();
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let writeResult = parcel.writeFileDescriptor(file.fd);
console.log("RpcTest: parcel writeFd result is : " + writeResult);
let containFD = parcel.containFileDescriptors();
console.log("RpcTest: parcel after write fd containFd result is : " + containFD);
......@@ -5241,18 +5251,18 @@ Writes a file descriptor to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let writeResult = parcel.writeFileDescriptor(file.fd);
console.log("RpcTest: parcel writeFd result is : " + writeResult);
```
......@@ -5273,11 +5283,11 @@ Reads the file descriptor from this **MessageParcel** object.
**Example**
```ts
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
let parcel = new rpc.MessageParcel();
let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let writeResult = parcel.writeFileDescriptor(fd);
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let writeResult = parcel.writeFileDescriptor(file.fd);
let readFD = parcel.readFileDescriptor();
console.log("RpcTest: parcel read fd is : " + readFD);
```
......@@ -5298,8 +5308,8 @@ Writes an anonymous shared object to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | -------------------------------------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -5375,8 +5385,8 @@ Writes raw data to this **MessageParcel** object.
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -5439,8 +5449,8 @@ Marshals this **Parcelable** object into a **MessageSequence** object.
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -5488,8 +5498,8 @@ Unmarshals this **Parcelable** object from a **MessageSequence** object.
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -5538,14 +5548,14 @@ Marshals the sequenceable object into a **MessageParcel** object.
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | ----------------------------------------- |
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | ----------------------------------------- |
| dataOut | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object to which the sequenceable object is to be marshaled.|
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -5587,14 +5597,14 @@ Unmarshals this sequenceable object from a **MessageParcel** object.
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------- | ---- | --------------------------------------------- |
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------------- | ---- | --------------------------------------------- |
| dataIn | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object in which the sequenceable object is to be unmarshaled.|
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -5641,8 +5651,8 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
**Return value**
| Type | Description|
| ---- | ----- |
| Type | Description |
| ----- | ----- |
| [IRemoteObject](#iremoteobject) | Returns the **RemoteObject** if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.|
**Example**
......@@ -5658,20 +5668,22 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function (elementName, remoteProxy) {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function (elementName) {
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function () {
onFailed: function() {
console.log("RpcClient: onFailed");
}
};
......@@ -5679,11 +5691,15 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **asObject()** of the proxy object is called to obtain the proxy or remote object.
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **asObject()** of the proxy object is called to obtain the proxy or remote object.
```ts
class TestProxy {
remote: rpc.RemoteObject;
......@@ -5695,7 +5711,6 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
}
}
let iRemoteObject = new TestProxy(proxy).asObject();
```
## DeathRecipient
......@@ -5806,17 +5821,17 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type| Mandatory| Description |
| ------- | ------------------------------- | ---- | ---- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.|
......@@ -5832,12 +5847,12 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ---------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
......@@ -5856,12 +5871,12 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. |
| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
......@@ -5880,13 +5895,13 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. |
| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. |
### sendRequest<sup>8+(deprecated)</sup>
......@@ -5900,13 +5915,13 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback for receiving the sending result. |
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback for receiving the sending result. |
### registerDeathRecipient<sup>9+</sup>
......@@ -5928,8 +5943,8 @@ Registers a callback for receiving death notifications of the remote object. The
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
### addDeathrecipient<sup>(deprecated)</sup>
......@@ -5950,8 +5965,8 @@ Adds a callback for receiving death notifications of the remote object. This met
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.|
......@@ -5975,8 +5990,8 @@ Unregisters the callback used to receive death notifications of the remote objec
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
### removeDeathRecipient<sup>(deprecated)</sup>
......@@ -5997,8 +6012,8 @@ Removes the callback used to receive death notifications of the remote object.
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | -----------------------------------------|
| boolean | Returns **true** if the callback is removed; returns **false** otherwise.|
### getDescriptor<sup>9+</sup>
......@@ -6020,8 +6035,8 @@ Obtains the interface descriptor (which is a string) of this object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
### getInterfaceDescriptor<sup>(deprecated)</sup>
......@@ -6051,8 +6066,8 @@ Checks whether this object is dead.
**Return value**
| Type | Description |
| ------- | ------------------------------------------- |
| Type | Description |
| ------- | ---------------------------------- |
| boolean | Returns **true** if the object is dead; returns **false** otherwise.|
......@@ -6082,25 +6097,27 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | ---------------------------------|
| boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.|
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6118,11 +6135,15 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message.
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message.
```ts
let option = new rpc.MessageOption();
let data = rpc.MessageParcel.create();
......@@ -6152,12 +6173,12 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. |
| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
......@@ -6167,10 +6188,12 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6188,9 +6211,13 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
```
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message.
```ts
......@@ -6230,12 +6257,12 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
......@@ -6245,10 +6272,12 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6266,7 +6295,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message.
......@@ -6306,20 +6339,22 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. |
| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. |
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6350,7 +6385,11 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
result.data.reclaim();
result.reply.reclaim();
}
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message.
......@@ -6362,7 +6401,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
data.writeInt(1);
data.writeString("hello");
try {
proxy.sendRequest(1, data, reply, option, sendRequestCallback);
proxy.sendMessageRequest(1, data, reply, option, sendRequestCallback);
} catch(error) {
console.info("rpc send sequence request fail, errorCode " + error.code);
console.info("rpc send sequence request fail, errorMessage " + error.message);
......@@ -6381,20 +6420,22 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback for receiving the sending result. |
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback for receiving the sending result. |
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6412,7 +6453,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
function sendRequestCallback(result) {
function sendRequestCallback(result) {
if (result.errCode === 0) {
console.log("sendRequest got result");
result.reply.readException();
......@@ -6425,7 +6466,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
result.data.reclaim();
result.reply.reclaim();
}
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **sendMessageRequest()** of the proxy object is called to send a message.
......@@ -6464,22 +6509,24 @@ Obtains the **LocalInterface** object of an interface token.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900006 | only remote object permitted |
| -------- | -------- |
| 1900006 | only remote object permitted |
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function (elementName) {
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
......@@ -6487,10 +6534,14 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
}
};
let want = {
"bundleName":"com.ohos.server",
"abilityName":"com.ohos.server.EntryAbility",
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **getLocalInterface()** of the proxy object is called to obtain the interface descriptor.
......@@ -6529,17 +6580,19 @@ Obtains the **LocalInterface** object of an interface token.
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function (elementName) {
onDisconnect: function(elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function() {
......@@ -6547,12 +6600,16 @@ Obtains the **LocalInterface** object of an interface token.
}
};
let want = {
"bundleName":"com.ohos.server",
"abilityName":"com.ohos.server.EntryAbility",
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
```
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **queryLocalInterface()** of the proxy object is called to obtain the interface descriptor.
```ts
......@@ -6580,15 +6637,17 @@ Registers a callback for receiving death notifications of the remote object. The
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6606,11 +6665,15 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **registerDeathRecipient()** of the proxy object is called to register a callback for receiving the death notification of the remote object.
```ts
class MyDeathRecipient {
onRemoteDied() {
......@@ -6645,16 +6708,18 @@ Adds a callback for receiving the death notifications of the remote object, incl
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.|
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6672,9 +6737,13 @@ Adds a callback for receiving the death notifications of the remote object, incl
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
```
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **addDeathRecippient()** of the proxy object is called to add a callback for receiving the death notification of the remove object.
```ts
......@@ -6707,15 +6776,17 @@ Unregisters the callback used to receive death notifications of the remote objec
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6733,9 +6804,13 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
```
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **unregisterDeathRecipient()** of the proxy object is called to unregister the callback for receiving the death notification of the remote object.
```ts
......@@ -6773,16 +6848,18 @@ Removes the callback used to receive death notifications of the remote object.
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the callback is removed; returns **false** otherwise.|
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6800,9 +6877,13 @@ Removes the callback used to receive death notifications of the remote object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
```
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **removeDeathRecipient()** of the proxy object is called to remove the callback used to receive the death notification of the remote object.
```ts
......@@ -6835,16 +6916,18 @@ Obtains the interface descriptor (which is a string) of this proxy object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900008 | proxy or remote object is invalid |
| 1900007 | communication failed |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
| 1900007 | communication failed |
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6862,7 +6945,11 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **getDescriptor()** of the proxy object is called to obtain the interface descriptor of the object.
......@@ -6894,10 +6981,12 @@ Obtains the interface descriptor of this proxy object.
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6915,9 +7004,13 @@ Obtains the interface descriptor of this proxy object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
```
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **getInterfaceDescriptor()** of the proxy object is called to obtain the interface descriptor of the current proxy object.
```ts
......@@ -6935,16 +7028,18 @@ Checks whether the **RemoteObject** is dead.
**Return value**
| Type | Description |
| ------- | --------------------------------------------------------- |
| Type | Description |
| ------- | ------------------------------------------------- |
| boolean | Returns **true** if the **RemoteObject** is dead; returns **false** otherwise.|
**Example**
Obtain the service.
Before obtaining the ability for the application developed based on the stage model, obtain the context. For details, see [Obtaining the Context](#obtaining-the-context).
```ts
import FA from "@ohos.ability.featureAbility";
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6962,7 +7057,11 @@ Checks whether the **RemoteObject** is dead.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **isObjectDead()** of the proxy object is called to check whether this object is dead.
......@@ -6980,10 +7079,10 @@ Provides common message options (flag and wait time). Use the specified flag to
| Name | Value | Description |
| ------------- | ---- | ----------------------------------------------------------- |
| TF_SYNC | 0 | Synchronous call. |
| TF_ASYNC | 1 | Asynchronous call. |
| TF_SYNC | 0 | Synchronous call. |
| TF_ASYNC | 1 | Asynchronous call. |
| TF_ACCEPT_FDS | 0x10 | Indication to **sendMessageRequest<sup>9+</sup>** for returning the file descriptor.|
| TF_WAIT_TIME | 8 | Default waiting time, in seconds. |
| TF_WAIT_TIME | 8 | Default waiting time, in seconds. |
### constructor<sup>9+</sup>
......@@ -7045,8 +7144,8 @@ Checks whether **SendMessageRequest** is called synchronously or asynchronously.
**Return value**
| Type | Description |
| ------- | ------------------------------------ |
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if **SendMessageRequest** is called synchronously; returns **false** if **SendMessageRequest** is called asynchronously.|
**Example**
......@@ -7353,8 +7452,8 @@ Checks whether the remote process is a process of the local device. This API is
**Return value**
| Type | Description |
| ------- | --------------------------------------------------------- |
| Type | Description |
| ------- | -------------------------------------------------- |
| boolean | Returns **true** if the local and remote processes are on the same device; returns **false** otherwise.|
**Example**
......@@ -7526,8 +7625,8 @@ Sets the UID and PID of the remote user. This API is a static method. It is usua
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | ---------------------------------|
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -7579,17 +7678,17 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.|
**Example**
......@@ -7645,12 +7744,12 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
......@@ -7715,12 +7814,12 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. |
| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
**Return value**
......@@ -7771,13 +7870,13 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| Name | Type | Mandatory| Description |
| ------------- | ------------------------------------ | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. |
| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| AsyncCallback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| AsyncCallback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. |
**Example**
......@@ -7821,13 +7920,13 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| AsyncCallback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback for receiving the sending result. |
| Name | Type | Mandatory| Description |
| ------------- | ----------------------------------------- | ---- | -------------------------------------------------------------------------------------- |
| code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.|
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. |
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. |
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| AsyncCallback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback for receiving the sending result. |
**Example**
......@@ -7885,17 +7984,17 @@ Provides a response to **sendMessageRequest()**. The server processes the reques
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------- | ---- | --------------------------------------- |
| code | number | Yes | Service request code sent by the remote end. |
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------------- | ---- | --------------------------------------- |
| code | number | Yes | Service request code sent by the remote end. |
| data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that holds the parameters called by the client.|
| reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object carrying the result. |
| option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. |
| option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. |
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -7946,17 +8045,17 @@ Provides a response to **sendMessageRequest()**. The server processes the reques
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------- | ---- | ----------------------------------------- |
| code | number | Yes | Service request code sent by the remote end. |
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------ | ---- | ----------------------------------------- |
| code | number | Yes | Service request code sent by the remote end. |
| data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that holds the parameters called by the client.|
| reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object to which the result is written. |
| option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. |
| option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. |
**Return value**
| Type | Description |
| ----------------- | ---------------------------------------------------------------------------------------------- |
| Type | Description |
| ----------------- | ----------------------------------------------------------------------------------------------- |
| boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. The value **true** means the operation is successful; the value **false** means the opposite.|
| Promise\<boolean> | Returns a promise object if the request is processed asynchronously in **onRemoteMessageRequest**. |
......@@ -8237,8 +8336,8 @@ Obtains the interface descriptor of this object. The interface descriptor is a s
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900008 | proxy or remote object is invalid |
| -------- | -------- |
| 1900008 | proxy or remote object is invalid |
**Example**
......@@ -8629,8 +8728,8 @@ Creates the shared file mapping on the virtual address space of this process. Th
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | ------ |
| 1900001 | call mmap function failed |
| -------- | -------- |
| 1900001 | call mmap function failed |
**Example**
......@@ -8662,8 +8761,8 @@ Creates the shared file mapping on the virtual address space of this process. Th
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the mapping is created; returns **false** otherwise.|
**Example**
......@@ -8687,8 +8786,8 @@ Maps the shared file to the readable and writable virtual address space of the p
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900001 | call mmap function failed |
| -------- | -------- |
| 1900001 | call mmap function failed |
**Example**
......@@ -8714,8 +8813,8 @@ Maps the shared file to the readable and writable virtual address space of the p
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the mapping is created; returns **false** otherwise.|
**Example**
......@@ -8739,8 +8838,8 @@ Maps the shared file to the read-only virtual address space of the process.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900001 | call mmap function failed |
| -------- | -------- |
| 1900001 | call mmap function failed |
**Example**
......@@ -8766,8 +8865,8 @@ Maps the shared file to the read-only virtual address space of the process.
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the mapping is created; returns **false** otherwise.|
**Example**
......@@ -8797,8 +8896,8 @@ Sets the protection level of the memory region to which the shared file is mappe
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| -------- | ------- |
| 1900002 | call os ioctl function failed |
| -------- | -------- |
| 1900002 | call os ioctl function failed |
**Example**
......@@ -8830,8 +8929,8 @@ Sets the protection level of the memory region to which the shared file is mappe
**Return value**
| Type | Description |
| ------- | ----------------------------------------- |
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -8863,8 +8962,8 @@ Writes data to the shared file associated with this **Ashmem** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID| Error Message|
| ------- | -------- |
| 1900003 | write to ashmem failed |
| -------- | -------- |
| 1900003 | write to ashmem failed |
**Example**
......@@ -8900,8 +8999,8 @@ Writes data to the shared file associated with this **Ashmem** object.
**Return value**
| Type | Description |
| ------- | ----------------------------------------------------------------------------------------- |
| Type | Description |
| ------- | ----------------------------------------------------------------------------- |
| boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example**
......@@ -8940,9 +9039,9 @@ Reads data from the shared file associated with this **Ashmem** object.
For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md).
| ID | Error Message|
| ID| Error Message|
| -------- | -------- |
| 1900004 | read from ashmem failed |
| 1900004 | read from ashmem failed |
**Example**
......@@ -8985,7 +9084,7 @@ Reads data from the shared file associated with this **Ashmem** object.
**Example**
```ts
``` ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem();
console.info("RpcTest map ashmem result is " + mapResult);
......@@ -8995,3 +9094,36 @@ Reads data from the shared file associated with this **Ashmem** object.
let readResult = ashmem.readFromAshmem(5, 0);
console.log("RpcTest: read to Ashmem result is : " + readResult);
```
## Obtaining the Context
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate");
globalThis.context = this.context;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy");
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate");
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy");
}
onForeground() {
// Ability has brought to foreground
console.log("[Demo] MainAbility onForeground");
}
onBackground() {
// Ability has back to background
console.log("[Demo] MainAbility onBackground");
}
};
```
......@@ -12,6 +12,8 @@ Use **RenderingContext** to draw rectangles, text, images, and other objects on
CanvasRenderingContext2D(setting: RenderingContextSetting)
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Description |
......@@ -25,34 +27,36 @@ RenderingContextSettings(antialias?: boolean)
Configures the settings of a **CanvasRenderingContext2D** object, including whether to enable antialiasing.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ----------------------------- |
| antialias | boolean | No | Whether to enable antialiasing.<br>Default value: **false** |
| antialias | boolean | No | Whether to enable antialiasing.<br>Default value: **false**|
## Attributes
| Name | Type | Description |
| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is string, this attribute indicates the color of the fill area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [fillStyle](#fillstyle) | string \|number<sup>10+</sup> \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is string, this attribute indicates the color of the fill area.<br>- When the type is number, this attribute indicates the color of the fill area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is string, this attribute indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **'butt'**: The endpoints of the line are squared off.<br>- **'round'**: The endpoints of the line are rounded.<br>- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.<br>Default value: **'butt'**|
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.<br>- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.<br>- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>Default value: **'miter'**|
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>Default value: **10**|
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**.<br>Default value: **'normal normal 14px sans-serif'**|
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **'left'**: The text is left-aligned.<br>- **'right'**: The text is right-aligned.<br>- **'center'**: The text is center-aligned.<br>- **'start'**: The text is aligned with the start bound.<br>- **'end'**: The text is aligned with the end bound.<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>Default value: **'left'**|
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **'alphabetic'**: The text baseline is the normal alphabetic baseline.<br>- **'top'**: The text baseline is on the top of the text bounding box.<br>- **'hanging'**: The text baseline is a hanging baseline over the text.<br>- **'middle'**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>Default value: **'alphabetic'**|
| [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>Default value: **0.0** |
| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>Default value: **'source-over'**|
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>Default value: **0.0**|
| [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>Default value: **true**|
| [strokeStyle](#strokestyle) | string \|number<sup>10+</sup> \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is string, this attribute indicates the stroke color.<br>- When the type is number, this attribute indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **'butt'**: The endpoints of the line are squared off.<br>- **'round'**: The endpoints of the line are rounded.<br>- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.<br>Default value: **'butt'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.<br>- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.<br>- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>Default value: **'miter'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>Default value: **10**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**.<br>Default value: **'normal normal 14px sans-serif'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **'left'**: The text is left-aligned.<br>- **'right'**: The text is right-aligned.<br>- **'center'**: The text is center-aligned.<br>- **'start'**: The text is aligned with the start bound.<br>- **'end'**: The text is aligned with the end bound.<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>Default value: **'left'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **'alphabetic'**: The text baseline is the normal alphabetic baseline.<br>- **'top'**: The text baseline is on the top of the text bounding box.<br>- **'hanging'**: The text baseline is a hanging baseline over the text.<br>- **'middle'**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>Default value: **'alphabetic'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>Default value: **0.0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>Default value: **'source-over'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>Default value: **0.0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [shadowColor](#shadowcolor) | string | Shadow color.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets.|
> **NOTE**
>
......@@ -77,7 +81,7 @@ struct FillStyleExample {
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.fillStyle = '#0000ff'
this.context.fillRect(20, 160, 150, 100)
this.context.fillRect(20, 20, 150, 100)
})
}
.width('100%')
......@@ -657,6 +661,8 @@ fillRect(x: number, y: number, w: number, h: number): void
Fills a rectangle on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -701,6 +707,8 @@ strokeRect(x: number, y: number, w: number, h: number): void
Draws an outlined rectangle on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -745,6 +753,8 @@ clearRect(x: number, y: number, w: number, h: number): void
Clears the content in a rectangle on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -791,6 +801,8 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void
Draws filled text on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
......@@ -836,6 +848,8 @@ strokeText(text: string, x: number, y: number, maxWidth?:number): void
Draws a text stroke on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
......@@ -881,6 +895,8 @@ measureText(text: string): TextMetrics
Measures the specified text to obtain its width. This API returns a **TextMetrics** object.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type | Mandatory| Default Value| Description |
......@@ -889,9 +905,9 @@ Measures the specified text to obtain its width. This API returns a **TextMetric
**Return value**
| Type | Description |
| ----------- | ---------------- |
| TextMetrics | **TextMetrics** object.|
| Type | Description |
| ----------- | ------------------------------------------------------------ |
| TextMetrics | **TextMetrics** object.<br>Since API version 9, this API is supported in ArkTS widgets.|
**TextMetrics**
......@@ -951,6 +967,8 @@ stroke(path?: Path2D): void
Strokes a path.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -997,6 +1015,8 @@ beginPath(): void
Creates a drawing path.
Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
......@@ -1037,6 +1057,8 @@ moveTo(x: number, y: number): void
Moves a drawing path to a target position on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1082,6 +1104,8 @@ lineTo(x: number, y: number): void
Connects the current point to a target position using a straight line.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1127,6 +1151,8 @@ closePath(): void
Draws a closed path.
Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
......@@ -1167,12 +1193,14 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu
Creates a pattern for image filling based on a specified source image and repetition mode.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | Source image. For details, see **ImageBitmap**. |
| repetition | string | Yes | Repetition mode. The value can be **'repeat'**, **'repeat-x'**, **'repeat-y'**, or **'no-repeat'**.<br>Default value: **''**|
| repetition | string | Yes | Repetition mode. The value can be **'repeat'**, **'repeat-x'**, **'repeat-y'**, **'no-repeat'**, **'clamp'**, or **'mirror'**.<br>Default value: **''**|
**Return value**
......@@ -1218,6 +1246,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1267,6 +1297,8 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
Draws a quadratic curve on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1314,6 +1346,8 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number,
Draws an arc on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1362,6 +1396,8 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1409,6 +1445,8 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
Draws an ellipse in the specified rectangular region on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1459,6 +1497,8 @@ rect(x: number, y: number, w: number, h: number): void
Creates a rectangle on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1504,6 +1544,8 @@ fill(fillRule?: CanvasFillRule): void
Fills the area inside a closed path on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1545,6 +1587,8 @@ fill(path: Path2D, fillRule?: CanvasFillRule): void
Fills the area inside a closed path on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1598,6 +1642,8 @@ clip(fillRule?: CanvasFillRule): void
Sets the current path to a clipping area.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1641,6 +1687,8 @@ clip(path: Path2D, fillRule?: CanvasFillRule): void
Sets the current path to a clipping path.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1653,35 +1701,35 @@ Sets the current path to a clipping path.
```ts
// xxx.ets
@Entry
@Component
struct Clip {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
let region = new Path2D()
region.moveTo(30, 90)
region.lineTo(110, 20)
region.lineTo(240, 130)
region.lineTo(60, 130)
region.lineTo(190, 20)
region.lineTo(270, 90)
region.closePath()
this.context.clip(region,"evenodd")
this.context.fillStyle = "rgb(0,255,0)"
this.context.fillRect(0, 0, this.context.width, this.context.height)
})
@Entry
@Component
struct Clip {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
let region = new Path2D()
region.moveTo(30, 90)
region.lineTo(110, 20)
region.lineTo(240, 130)
region.lineTo(60, 130)
region.lineTo(190, 20)
region.lineTo(270, 90)
region.closePath()
this.context.clip(region,"evenodd")
this.context.fillStyle = "rgb(0,255,0)"
this.context.fillRect(0, 0, this.context.width, this.context.height)
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777779](figures/en-us_image_000000127777779.png)
......@@ -1693,6 +1741,8 @@ filter(filter: string): void
Provides filter effects. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1706,6 +1756,8 @@ getTransform(): Matrix2D
Obtains the current transformation matrix being applied to the context. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
### resetTransform
......@@ -1713,6 +1765,8 @@ resetTransform(): void
Resets the current transform to the identity matrix. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
### direction
......@@ -1720,6 +1774,8 @@ direction(direction: CanvasDirection): void
Sets the current text direction used to draw text. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
### rotate
......@@ -1727,6 +1783,8 @@ rotate(angle: number): void
Rotates a canvas clockwise around its coordinate axes.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1769,6 +1827,8 @@ scale(x: number, y: number): void
Scales the canvas based on the given scale factors.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1814,6 +1874,8 @@ transform(a: number, b: number, c: number, d: number, e: number, f: number): voi
Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects.
Since API version 9, this API is supported in ArkTS widgets.
> **NOTE**
>
> The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation.
......@@ -1875,6 +1937,8 @@ setTransform(a: number, b: number, c: number, d: number, e: number, f: number):
Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1932,6 +1996,8 @@ translate(x: number, y: number): void
Moves the origin of the coordinate system.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1980,7 +2046,7 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh:
Draws an image on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
Since API version 9, this API is supported in ArkTS widgets, except that **PixelMap** objects are not supported.
**Parameters**
......@@ -2033,6 +2099,8 @@ createImageData(sw: number, sh: number): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2045,6 +2113,8 @@ createImageData(imageData: ImageData): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2085,6 +2155,8 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2105,29 +2177,29 @@ Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created wi
```ts
// xxx.ets
@Entry
@Component
struct GetImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
@Entry
@Component
struct GetImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.drawImage(this.img,0,0,130,130)
var imagedata = this.context.getImageData(50,50,130,130)
this.context.putImageData(imagedata,150,150)
})
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.drawImage(this.img,0,0,130,130)
var imagedata = this.context.getImageData(50,50,130,130)
this.context.putImageData(imagedata,150,150)
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777780](figures/en-us_image_000000127777780.png)
......@@ -2141,6 +2213,8 @@ putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirty
Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2195,6 +2269,8 @@ setLineDash(segments: number[]): void
Sets the dash line style.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Description |
......@@ -2238,6 +2314,8 @@ getLineDash(): number[]
Obtains the dash line style.
Since API version 9, this API is supported in ArkTS widgets.
**Return value**
| Type | Description |
......@@ -2249,40 +2327,40 @@ Obtains the dash line style.
```ts
// xxx.ets
@Entry
@Component
struct CanvasGetLineDash {
@State message: string = 'Hello World'
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
@Entry
@Component
struct CanvasGetLineDash {
@State message: string = 'Hello World'
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
console.error('before getlinedash clicked')
let res = this.context.getLineDash()
console.error(JSON.stringify(res))
})
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() => {
this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20])
this.context.stroke()
let res = this.context.getLineDash()
})
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
console.error('before getlinedash clicked')
let res = this.context.getLineDash()
console.error(JSON.stringify(res))
})
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() => {
this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20])
this.context.stroke()
let res = this.context.getLineDash()
})
}
.width('100%')
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
```
![en-us_image_000000127777778](figures/en-us_image_000000127777778.png)
......@@ -2294,6 +2372,8 @@ imageSmoothingQuality(quality: imageSmoothingQuality)
Sets the quality of image smoothing. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Description |
......@@ -2308,6 +2388,8 @@ transferFromImageBitmap(bitmap: ImageBitmap): void
Displays the specified **ImageBitmap** object.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Description |
......@@ -2377,26 +2459,26 @@ Since API version 9, this API is supported in ArkTS widgets.
```ts
// xxx.ets
@Entry
@Component
struct ToDataURL {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
@Entry
@Component
struct ToDataURL {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var dataURL = this.context.toDataURL()
})
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var dataURL = this.context.toDataURL()
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
......@@ -2406,6 +2488,8 @@ restore(): void
Restores the saved drawing context.
Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
......@@ -2444,6 +2528,8 @@ save(): void
Saves all states of the canvas in the stack. This API is usually called when the drawing state needs to be saved.
Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
......@@ -2482,6 +2568,8 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
Creates a linear gradient.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2513,7 +2601,7 @@ Creates a linear gradient.
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500)
this.context.fillRect(0, 0, 400, 400)
})
}
.width('100%')
......@@ -2531,6 +2619,8 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
Creates a linear gradient.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2564,7 +2654,7 @@ Creates a linear gradient.
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500)
this.context.fillRect(0, 0, 440, 440)
})
}
.width('100%')
......@@ -2575,7 +2665,55 @@ Creates a linear gradient.
![en-us_image_0000001257058405](figures/en-us_image_0000001257058405.png)
### createConicGradient<sup>10+</sup>
createConicGradient(startAngle: number, x: number, y: number): CanvasGradient
Creates a conic gradient.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| ---------- | ------ | ---- | ------ | ------------------------------------------------------------ |
| startAngle | number | Yes | 0 | Angle at which the gradient starts, in radians. The angle measurement starts horizontally from the right side of the center and moves clockwise.|
| x | number | Yes | 0 | X-coordinate of the center of the conic gradient, in vp. |
| y | number | Yes | 0 | Y-coordinate of the center of the conic gradient, in vp. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffffff')
.onReady(() => {
var grad = this.context.createConicGradient(0, 50, 80)
grad.addColorStop(0.0, '#ff0000')
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.context.fillStyle = grad
this.context.fillRect(0, 30, 100, 100)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001239032419](figures/en-us_image_0000001239032420.png)
## CanvasPattern
Defines an object created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.
......@@ -47,7 +47,7 @@ struct Page45 {
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500)
this.context.fillRect(0, 0, 400, 400)
})
}
.width('100%')
......
......@@ -24,29 +24,29 @@ An **ImageData** object stores pixel data rendered on a canvas.
```ts
// xxx.ets
@Entry
@Component
struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.drawImage(this.img,0,0,130,130)
var imagedata = this.context.getImageData(50,50,130,130)
this.context.putImageData(imagedata,150,150)
})
@Entry
@Component
struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/1234.png")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.drawImage(this.img,0,0,130,130)
var imagedata = this.context.getImageData(50,50,130,130)
this.context.putImageData(imagedata,150,150)
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777780](figures/en-us_image_000000127777780.png)
# Path2D
**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**.
**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** or **fill** API of **Canvas**.
> **NOTE**
> **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -18,11 +18,11 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| path | path2D | Yes| - | Path to be added to this path.|
| transform | Matrix2D | No| null | Transformation matrix of the new path.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| path | path2D | Yes| - | Path to be added to this path.|
| transform | Matrix2D | No| null | Transformation matrix of the new path.|
**Example**
......@@ -109,10 +109,10 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the target point.|
| y | number | Yes| 0 | Y-coordinate of the target point.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the target point.|
| y | number | Yes| 0 | Y-coordinate of the target point.|
**Example**
......@@ -158,10 +158,10 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the target point.|
| y | number | Yes| 0 | Y-coordinate of the target point.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the target point.|
| y | number | Yes| 0 | Y-coordinate of the target point.|
**Example**
......@@ -208,14 +208,14 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.|
| cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.|
| cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.|
| cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.|
| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.|
| cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.|
| cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.|
| cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.|
| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.|
**Example**
......@@ -259,12 +259,12 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.|
| cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.|
| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.|
| cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.|
| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.|
**Example**
......@@ -308,14 +308,14 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the center point of the arc.|
| y | number | Yes| 0 | Y-coordinate of the center point of the arc.|
| radius | number | Yes| 0 | Radius of the arc.|
| startAngle | number | Yes| 0 | Start radian of the arc.|
| endAngle | number | Yes| 0 | End radian of the arc.|
| counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the center point of the arc.|
| y | number | Yes| 0 | Y-coordinate of the center point of the arc.|
| radius | number | Yes| 0 | Radius of the arc.|
| startAngle | number | Yes| 0 | Start radian of the arc.|
| endAngle | number | Yes| 0 | End radian of the arc.|
| counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.|
**Example**
......@@ -358,13 +358,13 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x1 | number | Yes| 0 | X-coordinate of the first point on the arc.|
| y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.|
| x2 | number | Yes| 0 | X-coordinate of the second point on the arc.|
| y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.|
| radius | number | Yes| 0 | Radius of the arc.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x1 | number | Yes| 0 | X-coordinate of the first point on the arc.|
| y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.|
| x2 | number | Yes| 0 | X-coordinate of the second point on the arc.|
| y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.|
| radius | number | Yes| 0 | Radius of the arc.|
**Example**
......@@ -407,16 +407,16 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the ellipse center.|
| y | number | Yes| 0 | Y-coordinate of the ellipse center.|
| radiusX | number | Yes| 0 | Ellipse radius on the x-axis.|
| radiusY | number | Yes| 0 | Ellipse radius on the y-axis.|
| rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.|
| startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.|
| endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | boolean | No| false | Whether to draw the ellipse counterclockwise.<br>**true**: Draw the ellipse counterclockwise.<br>**false**: Draw the ellipse clockwise.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the ellipse center.|
| y | number | Yes| 0 | Y-coordinate of the ellipse center.|
| radiusX | number | Yes| 0 | Ellipse radius on the x-axis.|
| radiusY | number | Yes| 0 | Ellipse radius on the y-axis.|
| rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.|
| startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.|
| endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | boolean | No| false | Whether to draw the ellipse counterclockwise.<br>**true**: Draw the ellipse counterclockwise.<br>**false**: Draw the ellipse clockwise.|
**Example**
......@@ -459,12 +459,12 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.|
| w | number | Yes| 0 | Width of the rectangle.|
| h | number | Yes| 0 | Height of the rectangle.|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.|
| w | number | Yes| 0 | Width of the rectangle.|
| h | number | Yes| 0 | Height of the rectangle.|
**Example**
......
......@@ -9,7 +9,23 @@ The **\<Grid>** component consists of cells formed by rows and columns. You can
## Child Components
This component contains the child component **[\<GridItem>](ts-container-griditem.md)**.
The **\<Grid>** component accepts only **\<[GridItem](ts-container-griditem.md)>** as its child components.
> **NOTE**
>
> Below are the rules for calculating the indexes of the child components of **\<Grid>**:
>
> The index increases in ascending order of child components.
>
> In the **if/else** statement, only the child components in the branch where the condition is met participate in the index calculation.
>
> In the **ForEach** or **LazyForEach** statement, the indexes of all expanded subnodes are calculated.
>
> If the values of [if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated.
>
> Child components of **\<Grid>** whose **visibility** attribute is set to **Hidden** or **None** are included in the index calculation.
>
> Child components of **\<Grid>** whose **visibility** attribute is set to **None** are not displayed, but still take up the corresponding cells.
## APIs
......@@ -18,9 +34,9 @@ Grid(scroller?: Scroller)
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | ----------------------- |
| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Controller, which can be bound to scrollable components.<br>**NOTE**<br>The scroller cannot be bound to other [scrollable components](ts-container-list.md).|
## Attributes
......@@ -28,41 +44,57 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column is used by default.<br>For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.|
| rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row is used by default.<br>For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.|
| columnsGap | Length | Gap between columns.<br>Default value: **0**|
| rowsGap | Length | Gap between rows.<br>Default value: **0**|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| scrollBarColor | string \| number \| Color | Color of the scrollbar.|
| scrollBarWidth | string \| number | Width of the scrollbar.|
| cachedCount | number | Number of grid items to be preloaded. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**|
| editMode <sup>8+</sup> | boolean | Whether to enter editing mode. In editing mode, the user can drag the **[\<GridItem>](ts-container-griditem.md)** in the **\<Grid>** component.<br>Default value: **false** |
| columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column is used by default.<br>For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4.<br>**NOTE**<br>If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column.|
| rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row is used by default.<br>For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4.<br>**NOTE**<br>If this attribute is set to **'0fr'**, the row width is 0, and grid item in the row is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one row.|
| columnsGap | [Length](ts-types.md#length) | Gap between columns.<br>Default value: **0**<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
| rowsGap | [Length](ts-types.md#length) | Gap between rows.<br>Default value: **0**<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off** |
| scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.|
| scrollBarWidth | string \| number | Width of the scrollbar. After the width is set, the scrollbar is displayed with the set width in normal state and pressed state.<br>Default value: **4**<br>Unit: vp|
| cachedCount | number | Number of grid items to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**<br>**NOTE**<br>The number of the grid items to be cached before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns.<br>Grid items that exceed the display and cache range are released.<br>A value less than 0 evaluates to the default value.|
| editMode <sup>8+</sup> | boolean | Whether to enter editing mode. In editing mode, the user can drag the **\<[GridItem](ts-container-griditem.md)>** in the **\<Grid>** component.<br>Default value: **false**|
| layoutDirection<sup>8+</sup> | [GridDirection](#griddirection8) | Main axis direction of the grid.<br>Default value: **GridDirection.Row**|
| maxCount<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.<br>Default value: **Infinity**|
| minCount<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.<br>Default value: **1**|
| maxCount<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.<br>Default value: **Infinity**<br>**NOTE**<br>If the value of **maxCount** is smaller than that of **minCount**, the default values of **maxCount** and **minCount** are used.<br>A value less than 0 evaluates to the default value.|
| minCount<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: minimum number of rows that can be displayed.<br>Default value: **1**<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
| cellLength<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: fixed height per row.<br>When **layoutDirection** is **Column** or **ColumnReverse**: fixed width per column.<br>Default value: size of the first element|
| multiSelectable<sup>8+</sup> | boolean | Whether to enable mouse frame selection.<br>Default value: **false**<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.|
| supportAnimation<sup>8+</sup> | boolean | Whether to enable animation.<br>Default value: **false**|
| supportAnimation<sup>8+</sup> | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.<br>Default value: **false**|
Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\<Grid>** component supports the following layout modes:
1. **rowsTemplate** and **columnsTemplate** are both set
The **\<Grid>** displays only elements in a fixed number of rows and columns and cannot be scrolled. For example, if both **rowsTemplate** and **columnsTemplate** are set to **"1fr 1fr"**, only four elements (two rows and two columns) are displayed.
In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
- The **\<Grid>** component displays only elements in a fixed number of rows and columns and cannot be scrolled.
- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
- If the width and height of a grid are not set, the grid adapts to the size of its parent component by default.
- The size of the grid rows and columns is the size of the grid content area minus the gap between rows and columns. It is allocated based on the proportion of each row and column.
- By default, the grid items fill the entire grid.
- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs.
- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings. If no idle position meets the requirements, the grid item is not laid out.
- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position. If no idle position is available, the grid item is not laid out.
- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**.
2. Either **rowsTemplate** or **columnsTemplate** is set
The **\<Grid>** arranges elements in the specified direction and allows for scrolling to display excess elements. For example, if the **\<Grid>** has 10 elements and **columnsTemplate** is set to **"1fr 1fr 1fr"**, it contains three columns. The elements are arranged in the same direction as the main axis runs down the columns. Elements outside the **\<Grid>** area can be viewed through scrolling.
In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
- The **\<Grid>** component arranges elements in the specified direction and allows for scrolling to display excess elements.
- If **columnsTemplate** is set, the component scrolls vertically, the main axis runs vertically, and the cross axis runs horizontally.
- If **rowsTemplate** is set, the component scrolls horizontally, the main axis runs horizontally, and the cross axis runs vertically.
- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
- The cross axis size of the grid is the cross axis size of the grid content area minus the gaps along the cross axis. It is allocated based on the proportion of each row and column.
- The main axis size of the grid is the maximum height of all grid items in the cross axis direction of the current grid.
- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs.
- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings.
- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position.
- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**.
3. Neither **rowsTemplate** nor **columnsTemplate** is set
The **\<Grid>** arranges elements in the direction specified by **layoutDirection **. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**. The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling.
In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
- The **\<Grid>** component arranges elements in the direction specified by **layoutDirection**. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**.
- The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling.
- In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
- When **layoutDirection** is set to **Row**, elements are arranged from left to right. When a row is full, a new row will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered.
- When **layoutDirection** is set to **Column**, elements are arranged from top to bottom. When a column is full, a new column will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered.
- In this mode, **rowStart** and **columnStart** of the grid item do not take effect.
## GridDirection<sup>8+</sup>
......@@ -73,14 +105,18 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib
| RowReverse | Reverse horizontal layout, where the child components are arranged from right to left as the main axis runs along the rows.|
| ColumnReverse | Reverse vertical layout, where the child components are arranged from bottom up as the main axis runs down the columns.|
> **NOTE**
>
> The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **\<Grid>** component.
## Events
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name| Description|
| -------- | -------- |
| onScrollIndex(event: (first: number) => void) | Triggered when the start item of the grid changes.<br>- **first**: index of the start item of the grid.|
| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged element.|
| onScrollIndex(event: (first: number) => void) | Triggered when the start item of the grid changes. It is triggered once when the grid is initialized.<br>- **first**: index of the start item of the grid.<br>If it changes, this event will be triggered.|
| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged element.<br>**NOTE**<br>If **void** is returned, the drag operation cannot be performed.<br>This event is triggered when the user long presses a grid item.|
| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).|
| onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.|
| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item exits the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged item.|
......@@ -90,8 +126,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name | Type | Description |
| ---------- | ---------- | ---------- |
| x | number | X-coordinate of the dragged item. |
| y | number | Y-coordinate of the dragged item. |
| x | number | X coordinate of the dragged item. |
| y | number | Y coordinate of the dragged item. |
## Example
......
......@@ -12,6 +12,24 @@ The **\<List>** component provides a list container that presents a series of li
This component supports the **[\<ListItem>](ts-container-listitem.md)** and **[\<ListItemGroup>](ts-container-listitemgroup.md)** child components.
> **NOTE**
>
> Below are the rules for calculating the indexes of the child components of **\<List>**:
>
> The index increases in ascending order of child components.
>
> In the **if/else** statement, only the child components in the branch where the condition is met participate in the index calculation.
>
> In the **ForEach** or **LazyForEach** statement, the indexes of all expanded subnodes are calculated.
>
> If the values of [if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated.
>
> Each **\<ListItemGroup>** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the index calculation.
>
> Child components of **\<List>** whose **visibility** attribute is set to **Hidden** or **None** are included in the index calculation.
>
> Child components of **\<List>** whose **visibility** attribute is set to **None** are not displayed, but the spacing above and below them still takes effect.
## APIs
......@@ -23,9 +41,9 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| space | number \| string | No| Spacing between list items.<br>Default value: **0**|
| initialIndex | number | No| Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed. If the value set is greater than the sequence number of the last item, the setting does not take effect.<br>Default value: **0**|
| scroller | [Scroller](ts-container-scroll.md#scroller) | No| Scroller, which can be bound to scrollable components.|
| space | number \| string | No| Spacing between list items along the main axis.<br>Default value: **0**<br>**NOTE**<br>If this parameter is set to a percentage or a negative number other than -1, the default value is used.<br>If the value of **space** is less than the width of the list divider, the latter is used as the spacing.|
| initialIndex | number | No| Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.<br>Default value: **0**<br>**NOTE**<br>If this parameter is set to a negative value other than -1 or is greater than the index value of the last item in the current list, the value is invalid. In this case, the default value is used.|
| scroller | [Scroller](ts-container-scroll.md#scroller) | No| Scroller, which can be bound to scrollable components.<br>**NOTE**<br>The scroller cannot be bound to other scrollable components. |
## Attributes
......@@ -34,16 +52,16 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.<br>Default value: **Axis.Vertical**<br>Since API version 9, this API is supported in ArkTS widgets.|
| divider | {<br>strokeWidth: [Length](ts-types.md#length),<br>color?:[ResourceColor](ts-types.md#resourcecolor),<br>startMargin?: Length,<br>endMargin?: Length<br>} \| null | Style of the divider for the list items. By default, there is no divider.<br>- **strokeWidth**: stroke width of the divider.<br>- **color**: color of the divider.<br>- **startMargin**: distance between the divider and the start edge of the list.<br>- **endMargin**: distance between the divider and the end edge of the list.<br>Since API version 9, this API is supported in ArkTS widgets.|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**<br>Since API version 9, this API is supported in ArkTS widgets.|
| cachedCount | number | Number of list items or list item groups to be preloaded. A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.|
| divider | {<br>strokeWidth: [Length](ts-types.md#length),<br>color?:[ResourceColor](ts-types.md#resourcecolor),<br>startMargin?: Length,<br>endMargin?: Length<br>} \| null | Style of the divider for the list items. By default, there is no divider. This attribute cannot be set in percentage.<br>- **strokeWidth**: stroke width of the divider.<br>- **color**: color of the divider.<br>- **startMargin**: distance between the divider and the start edge of the list.<br>- **endMargin**: distance between the divider and the end edge of the list.<br>Since API version 9, this API is supported in ArkTS widgets.<br>The sum of **endMargin** and **startMargin** cannot exceed the column width.<br>**startMargin** and **endMargin** cannot be set in percentage.<br>The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.<br>In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.|
| cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.<br>In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.|
| editMode<sup>(deprecated)</sup> | boolean | Whether to enter editing mode.<br>This API is deprecated since API version 9.<br>Default value: **false**|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect.<br>Default value: **EdgeEffect.Spring**<br>Since API version 9, this API is supported in ArkTS widgets.|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.<br>Default value: **EdgeEffect.Spring**<br>Since API version 9, this API is supported in ArkTS widgets.|
| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.<br>Default value: **false**<br>- **false**: No chained animations are displayed.<br>- **true**: Chained animations are displayed.<br>Since API version 9, this API is supported in ArkTS widgets.|
| multiSelectable<sup>8+</sup> | boolean | Whether to enable mouse frame selection.<br>Default value: **false**<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.|
| lanes<sup>9+</sup> | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:<br>Number of columns in which the list items are arranged along the cross axis.<br>Default value: **1**<br>The rules are as follows:<br>- If the value is set to a number, the column width is determined based on the specified number and the cross-axis width of the **\<List>** component.<br>- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\<List>** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized. For example, if **lanes** is set to **{minLength: 40vp, maxLength: 60vp}** and the width of the **\<List>** component is 70 vp, the list items are arranged in one column with their alignment compliant with the **alignListItem** settings. If the width of the **\<List>** component is changed to 80 vp, which is twice the value of **minLength**, the list items are arranged in two columns.<br>This API is supported in ArkTS widgets.|
| alignListItem<sup>9+</sup> | ListItemAlign | Alignment mode of list items along the cross axis when: Cross-axis width of the **\<List>** component > Cross-axis width of list items x Value of **lanes**.<br>Default value: **ListItemAlign.Start**<br>This API is supported in ArkTS widgets.|
| sticky<sup>9+</sup> | StickyStyle | Whether to pin the header to the top or the footer to the bottom in the **\<ListItemGroup>** component. This attribute is used together with the **[\<ListItemGroup>](ts-container-listitemgroup.md)** component.<br>Default value: **StickyStyle.None**<br>This API is supported in ArkTS widgets.<br>**NOTE**<br>The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.|
| lanes<sup>9+</sup> | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:<br>Number of columns in which the list items are arranged along the cross axis.<br>Default value: **1**<br>The rules are as follows:<br>- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\<List>** component by the specified number.<br>- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\<List>** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.<br>- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the maximum width of list items in the display area.<br>- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.<br>- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.<br>This API is supported in ArkTS widgets. |
| alignListItem<sup>9+</sup> | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\<List>** component > Cross-axis width of list items x Value of **lanes**.<br>Default value: **ListItemAlign.Start**<br>This API is supported in ArkTS widgets.|
| sticky<sup>9+</sup> | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\<ListItemGroup>** component. This attribute is used together with the **[\<ListItemGroup>](ts-container-listitemgroup.md)** component.<br>Default value: **StickyStyle.None**<br>This API is supported in ArkTS widgets.<br>**NOTE**<br>The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.|
## ListItemAlign<sup>9+</sup>
......@@ -62,21 +80,23 @@ This API is supported in ArkTS widgets.
| Name | Description |
| ------ | -------------------------------------- |
| None | In the **\<ListItemGroup>** component, the header is not pinned to the top, and the footer is not pinned to the bottom.|
| Header | In the **\<ListItemGroup>** component, the header is pinned to the top.|
| Footer | In the **\<ListItemGroup>** component, the footer is pinned to the bottom.|
| Header | In the **\<ListItemGroup>** component, the header is pinned to the top, and the footer is not pinned to the bottom.|
| Footer | In the **\<ListItemGroup>** component, the footer is pinned to the bottom, and the header is not pinned to the top.|
> **NOTE**
>
> The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **\<List>** component.
## Events
| Name| Description|
| -------- | -------- |
| onItemDelete<sup>(deprecated)</sup>(event: (index: number) => boolean) | Triggered when a list item is deleted.<br>This API is deprecated since API version 9.<br>- **index**: index of the deleted list item.|
| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.<br>- **scrollOffset**: scroll offset.<br>- **[scrollState](#scrollstate)**: current scroll state.<br>Since API version 9, this API is supported in ArkTS widgets.|
| onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.<br>When calculating the index value, the **\<ListItemGroup>** accounts for one index value as a whole, and the index values of the list items within are not calculated.<br>- **start**: index of the scroll start position.<br>- **end**: index of the scroll end position.<br>Since API version 9, this API is supported in ArkTS widgets.|
| onReachStart(event: () => void) | Triggered when the list reaches the start position.<br>Since API version 9, this API is supported in ArkTS widgets.|
| onReachEnd(event: () => void) | Triggered when the list reaches the end position.<br>Since API version 9, this API is supported in ArkTS widgets.|
| onScrollFrameBegin<sup>9+</sup>(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.<br>\- **offset**: amount to scroll by.<br>\- **state**: current sliding status.<br>- **offsetRemain**: actual amount by which the list scrolls.<br>This API is supported in ArkTS widgets.<br>**NOTE**<br>If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.|
| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.<br>- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.<br>- **[scrollState](#scrollstate)**: current scroll state.<br>This event is not triggered when **ScrollEdge** and **ScrollToIndex** are called by using the controller. In other cases, this event is triggered when scrolling occurs.<br>Since API version 9, this API is supported in ArkTS widgets.|
| onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or exits from the list display area.<br>During index calculation, each **\<ListItemGroup>** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.<br>- **start**: index of the scroll start position.<br>- **end**: index of the scroll end position.<br>This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.<br>When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.<br>Since API version 9, this API is supported in ArkTS widgets.|
| onReachStart(event: () => void) | Triggered when the list reaches the start position.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.|
| onReachEnd(event: () => void) | Triggered when the list reaches the end position.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.|
| onScrollFrameBegin<sup>9+</sup>(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.<br>\- **offset**: amount to scroll by, in vp.<br>\- **state**: current sliding status.<br>- **offsetRemain**: actual amount by which the list scrolls, in vp.<br>This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.<br>This API is supported in ArkTS widgets.<br>**NOTE**<br>If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.|
| onScrollStart<sup>9+</sup>(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\<Scroll>** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.<br>This API is supported in ArkTS widgets.|
| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.<br>Since API version 9, this API is supported in ArkTS widgets.|
| onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.<br>- **from**: index of the item before moving.<br>- **to**: index of the item after moving.|
......@@ -84,7 +104,7 @@ This API is supported in ArkTS widgets.
| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).|
| onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.|
| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item exits the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: index of the list item.|
| onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.<br>- **isSuccess**: whether the dragged item is successfully dropped.|
| onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.<br>- **isSuccess**: whether the dragged item is successfully dropped.<br>**NOTE**<br>During dragging across lists, **true** is returned if the drop target is bound to **onItemDrop**. Otherwise, **false** is returned. During dragging within a list, **isSuccess** is the return value of the **onItemMove** event.|
## ScrollState
......@@ -92,13 +112,13 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Description |
| ------ | ------------------------- |
| Idle | Not scrolling. |
| Scroll | Finger dragging. |
| Fling | Inertial scrolling. |
| Idle | Not scrolling. Triggered when the API provided by the controller is used to scroll the list or when the scrollbar is dragged.|
| Scroll | Finger dragging. Triggered when the user drags the list to scroll.|
| Fling | Inertial scrolling. Triggered when inertial scrolling occurs or when the list bounces back after being released from a quick swipe.|
> **NOTE**
>
> To enable the editable mode for a list, the following conditions must be met: (This feature is deprecated since API version 9.)
> To enable the editable mode for a list, the following conditions must be met:
>
> - **editMode** is set to **true**.
>
......@@ -108,7 +128,7 @@ Since API version 9, this API is supported in ArkTS widgets.
>
> To enable dragging for a list item, the following conditions must be met:
>
> - **editMode** is set to **true**. (This is not required since API version 9.)
> - **editMode** is set to **true**.
>
> - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback.
......@@ -183,7 +203,7 @@ struct ListLanesExample {
.lanes({ minLength: 40, maxLength: 40 })
.alignListItem(this.alignListItem)
Button("Click to modify alignListItem: "+ this.alignListItem).onClick(() => {
Button("Change alignListItem: "+ this.alignListItem).onClick(() => {
if (this.alignListItem == ListItemAlign.Start) {
this.alignListItem = ListItemAlign.Center
} else if (this.alignListItem == ListItemAlign.Center) {
......
......@@ -39,7 +39,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<Line>** component, which does not have corners. |
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<Line>** component, which does not have corners.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a shape with a sharp angle.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.|
......
......@@ -21,7 +21,7 @@ The following child components are supported: **[\<Rect>](ts-drawing-components-
Shape(value?: PixelMap)
Since API version 9, this API is supported in ArkTS widgets.
Since API version 9, this API is supported in ArkTS widgets, except that **PixelMap** objects are not supported.
**Parameters**
......@@ -52,8 +52,6 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
## Example
### Example 1
```ts
// xxx.ets
@Entry
......
......@@ -12,6 +12,8 @@ Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text o
OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings)
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory| Description |
......@@ -23,25 +25,25 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render
## Attributes
| Name | Type | Description |
| Name | Type | Description |
| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **string**, this attribute indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **\<color>**, this parameter indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.<br>- Default value: **'butt'** |
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>- Default value: **'miter'** |
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10** |
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'** |
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>**NOTE**<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'** |
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>- Default value: **'alphabetic'** |
| [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0** |
| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>- Default value: **'source-over'** |
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0** |
| [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true** |
| [fillStyle](#fillstyle) | string \|number<sup>10+</sup> \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **string**, this attribute indicates the color of the filling area.<br>- When the type is **number**, this attribute indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [lineWidth](#linewidth) | number | Line width.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [strokeStyle](#strokestyle) | string \|number<sup>10+</sup> \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **string**, this attribute indicates the stroke color.<br>- When the type is **number**, this attribute indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.<br>- Default value: **'butt'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>- Default value: **'miter'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>**NOTE**<br><br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>- Default value: **'alphabetic'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>- Default value: **'source-over'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| [shadowColor](#shadowcolor) | string | Shadow color.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object.<br>Since API version 9, this API is supported in ArkTS widgets.|
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets.|
> **NOTE**
> For **fillStyle**, **shadowColor**, and **strokeStyle**, the value format of the string type is 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', '\#FFFFFF'.
......@@ -66,7 +68,7 @@ struct FillStyleExample {
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.fillStyle = '#0000ff'
this.offContext.fillRect(20, 160, 150, 100)
this.offContext.fillRect(20, 20, 150, 100)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
......@@ -700,6 +702,8 @@ fillRect(x: number, y: number, w: number, h: number): void
Fills a rectangle on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -747,6 +751,8 @@ strokeRect(x: number, y: number, w: number, h: number): void
Draws an outlined rectangle on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -794,6 +800,8 @@ clearRect(x: number, y: number, w: number, h: number): void
Clears the content in a rectangle on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -843,6 +851,8 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void
Draws filled text on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -891,6 +901,8 @@ strokeText(text: string, x: number, y: number): void
Draws a text stroke on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -939,6 +951,8 @@ measureText(text: string): TextMetrics
Returns a **TextMetrics** object used to obtain the width of specified text.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -947,9 +961,9 @@ Returns a **TextMetrics** object used to obtain the width of specified text.
**Return value**
| Type | Description |
| ----------- | ------- |
| TextMetrics | **TextMetrics** object.|
| Type | Description |
| ----------- | ------------------------------------------------------------ |
| TextMetrics | **TextMetrics** object.<br>Since API version 9, this API is supported in ArkTS widgets.|
**TextMetrics** attributes
......@@ -1009,6 +1023,8 @@ stroke(path?: Path2D): void
Strokes a path.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1058,6 +1074,8 @@ beginPath(): void
Creates a drawing path.
Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
......@@ -1101,6 +1119,8 @@ moveTo(x: number, y: number): void
Moves a drawing path to a target position on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1149,6 +1169,8 @@ lineTo(x: number, y: number): void
Connects the current point to a target position using a straight line.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1197,6 +1219,8 @@ closePath(): void
Draws a closed path.
Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
......@@ -1240,12 +1264,14 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu
Creates a pattern for image filling based on a specified source image and repetition mode.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | null | Source image. For details, see **ImageBitmap**. |
| repetition | string | Yes | "" | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.|
| repetition | string | Yes | "" | Repetition mode. The value can be **'repeat'**, **'repeat-x'**, **'repeat-y'**, **'no-repeat'**, **'clamp'**, or **'mirror'**.|
**Return value**
......@@ -1294,6 +1320,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1346,6 +1374,8 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
Draws a quadratic curve on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1396,6 +1426,8 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number,
Draws an arc on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1447,6 +1479,8 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1497,6 +1531,8 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
Draws an ellipse in the specified rectangular region on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1549,6 +1585,8 @@ rect(x: number, y: number, w: number, h: number): void
Creates a rectangle on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1597,6 +1635,8 @@ fill(fillRule?: CanvasFillRule): void
Fills the area inside a closed path on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1638,6 +1678,8 @@ fill(path: Path2D, fillRule?: CanvasFillRule): void
Fills the area inside a closed path on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1695,6 +1737,8 @@ clip(fillRule?: CanvasFillRule): void
Sets the current path to a clipping path.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1741,6 +1785,8 @@ clip(path:Path2D, fillRule?: CanvasFillRule): void
Sets a closed path to a clipping path.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1752,39 +1798,39 @@ Sets a closed path to a clipping path.
```ts
// xxx.ets
@Entry
@Component
struct Clip {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
@Entry
@Component
struct Clip {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
let region = new Path2D()
region.moveTo(30, 90)
region.lineTo(110, 20)
region.lineTo(240, 130)
region.lineTo(60, 130)
region.lineTo(190, 20)
region.lineTo(270, 90)
region.closePath()
this.offContext.clip(region,"evenodd")
this.offContext.fillStyle = "rgb(0,255,0)"
this.offContext.fillRect(0, 0, 600, 600)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
let region = new Path2D()
region.moveTo(30, 90)
region.lineTo(110, 20)
region.lineTo(240, 130)
region.lineTo(60, 130)
region.lineTo(190, 20)
region.lineTo(270, 90)
region.closePath()
this.offContext.clip(region,"evenodd")
this.offContext.fillStyle = "rgb(0,255,0)"
this.offContext.fillRect(0, 0, 600, 600)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777779](figures/en-us_image_000000127777779.png)
......@@ -1797,6 +1843,8 @@ filter(filter: string): void
Sets a filter for the image on the canvas. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1810,6 +1858,8 @@ getTransform(): Matrix2D
Obtains the current transformation matrix being applied to the context. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
### resetTransform
......@@ -1817,6 +1867,8 @@ resetTransform(): void
Resets the current transform to the identity matrix. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
### direction
......@@ -1824,6 +1876,8 @@ direction(direction: CanvasDirection): void
Sets the text direction for drawing text. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
### rotate
......@@ -1831,6 +1885,8 @@ rotate(angle: number): void
Rotates a canvas clockwise around its coordinate axes.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1876,6 +1932,8 @@ scale(x: number, y: number): void
Scales the canvas based on scale factors.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -1924,6 +1982,8 @@ transform(a: number, b: number, c: number, d: number, e: number, f: number): voi
Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects.
Since API version 9, this API is supported in ArkTS widgets.
> **NOTE**
>
> The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation.
......@@ -1988,6 +2048,8 @@ setTransform(a: number, b: number, c: number, d: number, e: number, f: number):
Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2041,6 +2103,8 @@ translate(x: number, y: number): void
Moves the origin of the coordinate system.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2092,6 +2156,8 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh:
Draws an image on the canvas.
Since API version 9, this API is supported in ArkTS widgets, except that **PixelMap** objects are not supported.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2145,9 +2211,11 @@ createImageData(sw: number, sh: number): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Parameters | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- |
| sw | number | Yes | 0 | Width of the **ImageData** object.|
| sh | number | Yes | 0 | Height of the **ImageData** object.|
......@@ -2157,6 +2225,8 @@ createImageData(imageData: ImageData): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object by copying an existing **ImageData** object.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2190,6 +2260,27 @@ Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created wi
| ---------------------------------------- | ------------ |
| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.|
### setPixelMap
setPixelMap(value?: PixelMap): void
Draws the input [PixelMap](../apis/js-apis-image.md#pixelmap7) object on the canvas.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------- |
| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.|
| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.|
| sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------ |
| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.|
### getImageData
......@@ -2197,6 +2288,8 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2217,32 +2310,32 @@ Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created wi
```ts
// xxx.ets
@Entry
@Component
struct GetImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
@Entry
@Component
struct GetImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.drawImage(this.img,0,0,130,130)
var imagedata = this.offContext.getImageData(50,50,130,130)
this.offContext.putImageData(imagedata,150,150)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.drawImage(this.img,0,0,130,130)
var imagedata = this.offContext.getImageData(50,50,130,130)
this.offContext.putImageData(imagedata,150,150)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777780](figures/en-us_image_000000127777780.png)
......@@ -2256,6 +2349,8 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY:
Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2311,6 +2406,8 @@ setLineDash(segments: number[]): void
Sets the dash line style.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Description |
......@@ -2320,31 +2417,31 @@ Sets the dash line style.
**Example**
```ts
@Entry
@Component
struct SetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.stroke()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
@Entry
@Component
struct SetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.stroke()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777772](figures/en-us_image_000000127777772.png)
......@@ -2355,6 +2452,8 @@ getLineDash(): number[]
Obtains the dash line style.
Since API version 9, this API is supported in ArkTS widgets.
**Return value**
| Type | Description |
......@@ -2365,42 +2464,42 @@ Obtains the dash line style.
```ts
// xxx.ets
@Entry
@Component
struct OffscreenCanvasGetLineDash {
@State message: string = 'Hello World'
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
console.error('before getlinedash clicked')
let res = this.offContext.getLineDash()
console.error(JSON.stringify(res))
})
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() => {
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.stroke()
let res = this.offContext.getLineDash()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
@Entry
@Component
struct OffscreenCanvasGetLineDash {
@State message: string = 'Hello World'
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
console.error('before getlinedash clicked')
let res = this.offContext.getLineDash()
console.error(JSON.stringify(res))
})
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() => {
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.stroke()
let res = this.offContext.getLineDash()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
```
![en-us_image_000000127777778](figures/en-us_image_000000127777778.png)
......@@ -2430,28 +2529,28 @@ Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct ToDataURL {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
// xxx.ets
@Entry
@Component
struct ToDataURL {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var dataURL = this.offContext.toDataURL()
})
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var dataURL = this.offContext.toDataURL()
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
......@@ -2461,6 +2560,8 @@ imageSmoothingQuality(quality: imageSmoothingQuality)
Sets the quality of image smoothing. This API is a void API.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Description |
......@@ -2524,37 +2625,39 @@ restore(): void
Restores the saved drawing context.
Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.save() // save the default state
this.offContext.fillStyle = "#00ff00"
this.offContext.fillRect(20, 20, 100, 100)
this.offContext.restore() // restore to the default state
this.offContext.fillRect(150, 75, 100, 100)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.save() // save the default state
this.offContext.fillStyle = "#00ff00"
this.offContext.fillRect(20, 20, 100, 100)
this.offContext.restore() // restore to the default state
this.offContext.fillRect(150, 75, 100, 100)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777781](figures/en-us_image_000000127777781.png)
......@@ -2565,37 +2668,39 @@ save(): void
Saves the current drawing context.
Since API version 9, this API is supported in ArkTS widgets.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.save() // save the default state
this.offContext.fillStyle = "#00ff00"
this.offContext.fillRect(20, 20, 100, 100)
this.offContext.restore() // restore to the default state
this.offContext.fillRect(150, 75, 100, 100)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.save() // save the default state
this.offContext.fillStyle = "#00ff00"
this.offContext.fillRect(20, 20, 100, 100)
this.offContext.restore() // restore to the default state
this.offContext.fillRect(150, 75, 100, 100)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777781](figures/en-us_image_000000127777781.png)
......@@ -2606,6 +2711,8 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
Creates a linear gradient.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
......@@ -2638,7 +2745,7 @@ Creates a linear gradient.
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.offContext.fillStyle = grad
this.offContext.fillRect(0, 0, 500, 500)
this.offContext.fillRect(0, 0, 400, 400)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
......@@ -2658,7 +2765,9 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
Creates a linear gradient.
**Parameters**
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------------- |
......@@ -2669,7 +2778,7 @@ Creates a linear gradient.
| y1 | number | Yes | 0 | Y-coordinate of the center of the end circle. |
| r1 | number | Yes | 0 | Radius of the end circle, which must be a non-negative finite number.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2692,7 +2801,7 @@ Creates a linear gradient.
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.offContext.fillStyle = grad
this.offContext.fillRect(0, 0, 500, 500)
this.offContext.fillRect(0, 0, 440, 440)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
......@@ -2705,7 +2814,59 @@ Creates a linear gradient.
![en-us_image_0000001238952407](figures/en-us_image_0000001238952407.png)
### createConicGradient<sup>10+</sup>
createConicGradient(startAngle: number, x: number, y: number): CanvasGradient
Creates a conic gradient.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| ---------- | ------ | ---- | ------ | ------------------------------------------------------------ |
| startAngle | number | Yes | 0 | Angle at which the gradient starts, in radians. The angle measurement starts horizontally from the right side of the center and moves clockwise.|
| x | number | Yes | 0 | X-coordinate of the center of the conic gradient, in vp. |
| y | number | Yes | 0 | Y-coordinate of the center of the conic gradient, in vp. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct OffscreenCanvasConicGradientPage {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffffff')
.onReady(() =>{
var grad = this.offContext.createConicGradient(0, 50, 80)
grad.addColorStop(0.0, '#ff0000')
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.offContext.fillStyle = grad
this.offContext.fillRect(0, 30, 100, 100)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001239032419](figures/en-us_image_0000001239032420.png)
## CanvasPattern
Defines an object created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.
......@@ -12,12 +12,12 @@ The size attributes set the width, height, and margin of a component.
| Name | Type | Description |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| width | [Length](ts-types.md#length) | Width of the component. By default, the width required to fully hold the component content is used. If the width of the component is greater than that of the parent container, the range of the parent container is drawn.<br>Since API version 9, this API is supported in ArkTS widgets.|
| height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn.<br>Since API version 9, this API is supported in ArkTS widgets.|
| size | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} | Size of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.<br>When the parameter is of the **Length** type, the four paddings take effect.<br>Default value: **0**<br>When **padding** is set to a percentage, the width of the parent container is used as the basic value.<br>Since API version 9, this API is supported in ArkTS widgets.|
| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.<br>Default value: **0**<br>When **margin** is set to a percentage, the width of the parent container is used as the basic value.<br>Since API version 9, this API is supported in ArkTS widgets.|
| constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. If the value of **minWidth** is greater than that of **maxWidth**, only the value of **minWidth** takes effect. The same rule applies to **minHeight** and **maxHeight**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>}<br>Since API version 9, this API is supported in ArkTS widgets.|
| width | [Length](ts-types.md#length) | Width of the component. By default, the width required to fully hold the component content is used. If the width of the component is greater than that of the parent container, the range of the parent container is drawn.<br>Since API version 9, this API is supported in ArkTS widgets.<br>Since API version 10, this API supports the calc calculation feature.|
| height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn.<br>Since API version 9, this API is supported in ArkTS widgets.<br>Since API version 10, this API supports the calc calculation feature.|
| size | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} | Size of the component.<br>Since API version 9, this API is supported in ArkTS widgets.<br>Since API version 10, this API supports the calc calculation feature.|
| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.<br>When the parameter is of the **Length** type, the four paddings take effect.<br>Default value: **0**<br>When **padding** is set to a percentage, the width of the parent container is used as the basic value.<br>Since API version 9, this API is supported in ArkTS widgets.<br>Since API version 10, this API supports the calc calculation feature.|
| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.<br>Default value: **0**<br>When **margin** is set to a percentage, the width of the parent container is used as the basic value.<br>Since API version 9, this API is supported in ArkTS widgets.<br>Since API version 10, this API supports the calc calculation feature.|
| constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. If the value of **minWidth** is greater than that of **maxWidth**, only the value of **minWidth** takes effect. The same rule applies to **minHeight** and **maxHeight**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>}<br>Since API version 9, this API is supported in ArkTS widgets.<br>Since API version 10, this API supports the calc calculation feature.|
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>The value can be a number greater than or equal to 0 or a string that can be converted to a number.|
......
# Recommendations for Improving Performance
Poor-performing code may work, but will take away from your application performance. This topic presents a line-up of recommendations that you can take to improve your implementation, thereby avoiding possible performance drop.
## Lazy Loading
When developing a long list, use of loop rendering, as in the code snippet below, can greatly slow down page loading and increase server load.
```ts
@Entry
@Component
struct MyComponent {
@State arr: number[] = Array.from(Array(100), (v,k) =>k); // Construct an array of 0 to 99.
build() {
List() {
ForEach(this.arr, (item: number) => {
ListItem() {
Text(`item value: ${item}`)
}
}, (item: number) => item.toString())
}
}
}
```
The preceding code snippet loads all of the 100 list elements at a time during page loading. This is generally not desirable. Instead, what we need is to load data from the data source and create corresponding components on demand. This can be achieved through lazy loading. The sample code is as follows:
```ts
class BasicDataSource implements IDataSource {
private listeners: DataChangeListener[] = []
public totalCount(): number {
return 0
}
public getData(index: number): any {
return undefined
}
registerDataChangeListener(listener: DataChangeListener): void {
if (this.listeners.indexOf(listener) < 0) {
console.info('add listener')
this.listeners.push(listener)
}
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const pos = this.listeners.indexOf(listener);
if (pos >= 0) {
console.info('remove listener')
this.listeners.splice(pos, 1)
}
}
notifyDataReload(): void {
this.listeners.forEach(listener => {
listener.onDataReloaded()
})
}
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdd(index)
})
}
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChange(index)
})
}
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDelete(index)
})
}
notifyDataMove(from: number, to: number): void {
this.listeners.forEach(listener => {
listener.onDataMove(from, to)
})
}
}
class MyDataSource extends BasicDataSource {
private dataArray: string[] = ['item value: 0', 'item value: 1', 'item value: 2']
public totalCount(): number {
return this.dataArray.length
}
public getData(index: number): any {
return this.dataArray[index]
}
public addData(index: number, data: string): void {
this.dataArray.splice(index, 0, data)
this.notifyDataAdd(index)
}
public pushData(data: string): void {
this.dataArray.push(data)
this.notifyDataAdd(this.dataArray.length - 1)
}
}
@Entry
@Component
struct MyComponent {
private data: MyDataSource = new MyDataSource()
build() {
List() {
LazyForEach(this.data, (item: string) => {
ListItem() {
Row() {
Text(item).fontSize(20).margin({ left: 10 })
}
}
.onClick(() => {
this.data.pushData('item value: ' + this.data.totalCount())
})
}, item => item)
}
}
}
```
![LazyForEach1](figures/LazyForEach1.gif)
The preceding code initializes only three list elements during page loading and loads a new list item each time a list element is clicked.
## Prioritizing Conditional Rendering over Visibility Control
Use of the visibility attribute to hide or show a component, as in the code snippet below, results in re-creation of the component, leading to performance drop.
```ts
@Entry
@Component
struct MyComponent {
@State isVisible: Visibility = Visibility.Visible;
build() {
Column() {
Button ("Show/Hide")
.onClick(() => {
if (this.isVisible == Visibility.Visible) {
this.isVisible = Visibility.None
} else {
this.isVisible = Visibility.Visible
}
})
Row().visibility(this.isVisible)
.width(300).height(300).backgroundColor(Color.Pink)
}.width('100%')
}
}
```
To avoid the preceding issue, use the **if** statement instead. The sample code is as follows:
```ts
@Entry
@Component
struct MyComponent {
@State isVisible: boolean = true;
build() {
Column() {
Button ("Show/Hide")
.onClick(() => {
this.isVisible = !this.isVisible
})
if (this.isVisible) {
Row()
.width(300).height(300).backgroundColor(Color.Pink)
}
}.width('100%')
}
}
```
![isVisible](figures/isVisible.gif)
## Prioritizing Flex over Column/Row
By default, the flex container needs to re-lay out flex items to comply with the **flexShrink** and **flexGrow** settings. This may result in drop in rendering performance.
```ts
@Entry
@Component
struct MyComponent {
build() {
Flex({ direction: FlexDirection.Column }) {
Flex().width(300).height(200).backgroundColor(Color.Pink)
Flex().width(300).height(200).backgroundColor(Color.Yellow)
Flex().width(300).height(200).backgroundColor(Color.Grey)
}
}
}
```
To avoid the preceding issue, replace **Flex** with **Column** and **Row**, which can create the same page layout as **Flex** does.
```ts
@Entry
@Component
struct MyComponent {
build() {
Column() {
Row().width(300).height(200).backgroundColor(Color.Pink)
Row().width(300).height(200).backgroundColor(Color.Yellow)
Row().width(300).height(200).backgroundColor(Color.Grey)
}
}
}
```
![flex1](figures/flex1.PNG)
## Setting Width and Height for \<List> Components
When a **\<List>** component is nested within a **\<Scroll>** component, all of its content will be loaded if its width and height is not specified, which may result in performance drop.
```ts
@Entry
@Component
struct MyComponent {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
build() {
Scroll() {
List() {
ForEach(this.arr, (item) => {
ListItem() {
Text(`item value: ${item}`).fontSize(30).margin({ left: 10 })
}.height(100)
}, (item) => item.toString())
}
}.backgroundColor(Color.Pink)
}
}
```
Therefore, in the above scenario, you are advised to set the width and height for the **\<List>** component as follows:
```ts
@Entry
@Component
struct MyComponent {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
build() {
Scroll() {
List() {
ForEach(this.arr, (item) => {
ListItem() {
Text(`item value: ${item}`).fontSize(30).margin({ left: 10 })
}.height(100)
}, (item) => item.toString())
}.width('100%').height(500)
}.backgroundColor(Color.Pink)
}
}
```
![list1](figures/list1.gif)
## Minimizing White Blocks During Swiping
To minimize white blocks during swiping, expand the UI loading range by increasing the value of **cachedCount** for the **\<List>** and **\<Grid>** components. **cachedCount** indicates the number of list or grid items preloaded outside of the screen.
If an item needs to request an online image, set **cachedCount** as appropriate so that the image is downloaded in advance before the item comes into view on the screen, thereby reducing the number of white blocks.
The following is an example of using **cachedCount**:
```ts
@Entry
@Component
struct MyComponent {
private source: MyDataSource = new MyDataSource();
build() {
List() {
LazyForEach(this.source, item => {
ListItem() {
Text("Hello" + item)
.fontSize(50)
.onAppear(() => {
console.log("appear:" + item)
})
}
})
}.cachedCount(3) // Increase the number of list or grid items preloaded outside of the screen.
}
}
class MyDataSource implements IDataSource {
data: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
public totalCount(): number {
return this.data.length
}
public getData(index: number): any {
return this.data[index]
}
registerDataChangeListener(listener: DataChangeListener): void {
}
unregisterDataChangeListener(listener: DataChangeListener): void {
}
}
```
![list2](figures/list2.gif)
**Instructions**
A greater **cachedCount** value may result in higher CPU and memory overhead of the UI. Adjust the value by taking into account both the comprehensive performance and user experience.
# Mini-System Devices with Screens – Bestechnic SoC Porting Case
This document exemplifies the porting procedure for a development board on a mini-system device with a screen – an intelligent switch panel. It uses the BES multi-modal V200Z-R development board powered by the Bestechnic BES2600W SoC as an example. Components such as `ace_engine_lite`, `graphic_ui`, `aafwk_lite`, `appexecfwk_lite`, and `HDF` are adapted based on the OpenHarmony LiteOS-M kernel. This example uses the board-SoC separation solution as the porting architecture, the Newlib C or Musl C library as the toolchain, and GN and Kconfig graphical configuration for LiteOS-M kernel compilation.
This document exemplifies the porting procedure for a development board on a mini-system device with a screen – an intelligent switch panel. It uses the BES multi-modal V200Z-R development board powered by the Bestechnic BES2600W SoC as an example. Components such as `ace_engine_lite`, `arkui_ui_lite`, `aafwk_lite`, `appexecfwk_lite`, and `HDF` are adapted based on the OpenHarmony LiteOS-M kernel. This example uses the board-SoC separation solution as the porting architecture, the Newlib C or Musl C library as the toolchain, and GN and Kconfig graphical configuration for LiteOS-M kernel compilation.
## Compilation and Building
......@@ -1311,7 +1311,7 @@ aafwk_lite + appexecfwk_lite (AAFWK + APPEXECFWK)
|
ace_engine_lite + jerryscript + i18n_lite + resmgr_lite + utils/native/lite/... (ACE and JS engines and their dependencies)
|
graphic_ui + graphic_utils (Graphic framework)
arkui_lite + graphic_graphic_utils_lite (Graphic framework)
|
giflib + libjpeg + libpng + qrcodegen + freetype... (Third-party graphics library)
```
......
# Small System STM32MP1 SoC Porting Case
This document describes how to port small development boards with screens based on the [BearPi-HM Micro development board](https://gitee.com/openharmony/device_board_bearpi) of the `STM32MP157` SoC from STMicroelectronics, so as to adapt components such as `ace_engine_lite`, `graphic_ui`, `aafwk_lite`, `appexecfwk_lite`, and `HDF` to the `OpenHarmony LiteOS-A` kernel. The porting architecture uses the solution where `Board` and `SoC` are separated.
This document describes how to port small development boards with screens based on the [BearPi-HM Micro development board](https://gitee.com/openharmony/device_board_bearpi) of the `STM32MP157` SoC from STMicroelectronics, so as to adapt components such as `ace_engine_lite`, `arkui_ui_lite`, `aafwk_lite`, `appexecfwk_lite`, and `HDF` to the `OpenHarmony LiteOS-A` kernel. The porting architecture uses the solution where `Board` and `SoC` are separated.
## Compilation and Building
......
......@@ -2,7 +2,7 @@
## Introduction
ArkUI is a UI development framework that provides what you'll need to develop application UIs in OpenHarmony, including UI components, animations, drawing, interaction events, and JavaScript API extension mechanisms. ArkUI comes with two development paradigms: eTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short).
ArkUI is a UI development framework that provides what you'll need to develop application UIs in OpenHarmony, including UI components, animations, drawing, interaction events, and JavaScript API extension mechanisms. ArkUI comes with two development paradigms: ArkTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short).
**Framework Structure**
......
......@@ -28,11 +28,15 @@ The related modules are described as follows:
### Directory Structure
```
/foundation/arkui
├── ui_lite # UI module, including UI components, animations, and fonts
/foundation/graphic
├── surface # Shared memory
├── ui # UI module, including UI components, animations, and fonts
├── utils # Basic graphics library and hardware adaptation layer
└── wms # Window and input event management
├── surface_lite # Shared memory
├── graphic_utils_lite # Basic graphics library and hardware adaptation layer
/foundation/window
└── window_manager_lite # Window and input event management
```
### Constraints
......@@ -48,13 +52,13 @@ For details, see the README and **test** directory of each repository.
**Graphics subsystem**
[graphic\_surface](https://gitee.com/openharmony/graphic_surface)
[graphic\_surface_lite](https://gitee.com/openharmony/graphic_surface_lite)
[graphic\_ui](https://gitee.com/openharmony/graphic_ui)
[arkui\_ui_lite](https://gitee.com/openharmony/arkui_ui_lite)
[graphic\_wms](https://gitee.com/openharmony/graphic_wms)
[window\_window_manager_lite](https://gitee.com/openharmony/window_window_manager_lite)
[graphic\_utils](https://gitee.com/openharmony/graphic_utils)
[graphic\_graphic_utils_lite](https://gitee.com/openharmony/graphic_graphic_utils_lite)
## Standard System
......
......@@ -139,10 +139,10 @@ The following table describes the optimization of repositories.
| startup_frameworks_syspara_lite | startup_syspara_lite | Repository renamed |
| startup_hals_syspara_lite | N/A | Read-only archiving |
| startup_interfaces_kits_syspara_lite | N/A | Read-only archiving |
| graphic_lite | graphic_surface | Repository renamed |
| N/A | graphic_ui | New module |
| N/A | graphic_utils | New module |
| N/A | graphic_wms | New module |
| graphic_lite | graphic_surface_lite | Repository renamed |
| N/A | arkui_ui_lite | Repository renamed module |
| N/A | graphic_graphic_utils_lite | Repository renamed module |
| N/A | window_manager_lite | Repository renamed module |
| N/A | third_party_giflib | New module |
| N/A | third_party_qrcodegen | New module |
| N/A | drivers_adapter_khdf_linux | New module |
......
......@@ -66,7 +66,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -69,7 +69,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -132,7 +132,7 @@ For details, see [JS API Differences](api-diff/v3.0-LTS/js-apidiff-v3.0-lts.md).
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -71,7 +71,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -72,7 +72,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -72,7 +72,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -100,7 +100,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -91,7 +91,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Fixed Security Vulnerabilities
......
......@@ -91,7 +91,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Fixed Security Vulnerabilities
......
......@@ -91,7 +91,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Fixed Security Vulnerabilities
......
......@@ -100,28 +100,28 @@ This version has the following updates to OpenHarmony 3.0 LTS.
| Subsystem| Standard System| Mini and Small Systems|
| -------- | -------- | -------- |
| Bundle management framework| -&nbsp;I4MBSE: Provides the home screen bundle management client.<br>-&nbsp;I4MBSF: Supports cache clearing.<br>-&nbsp;I4MBSG: Supports installation package information query.<br>-&nbsp;I4MBSD: Supports multi-HAP installation.<br>-&nbsp;I4MBSH: Supports signature verification during multi-HAP installation.<br>-&nbsp;I4MBSC: Supports the **srcPath** field for modules and abilities.| NA |
| Distributed Scheduler subsystem| -I4MBRW: Samgr supports intra-process system ability list control.<br>-I4MBRV: Samgr supports maintenance of the system service status list.<br>-I4MBRZ: Samgr supports initialization of the full service list.<br>-I4MBRY: Samgr supports maintenance of the system process status list.<br>-I4MBRX: Samgr supports loading a specific system service.| NA |
| DeviceProfile subsystem| -I4NY23: Insertion, deletion, and query of local device profiles.<br>-I4NY1X: Query of remote device profiles.<br>-I4NY1T: Subscription to remote profile changes.<br>-I4NY1W: Cross-device profile synchronization.| NA |
| Account subsystem| -I4MBQW: Application account addition and deletion.<br>-I4MBQV: Restrictions on the basic information about application accounts.<br>-I4MBQU: Application account subscription and unsubscription.<br>-I4MBQT: Application account function setting and content modification.<br>-I4MBQS: Application account information query.<br>-I4IT3U: Basic information management for application accounts.| NA |
| Pan-sensor subsystem| -I3NJ96: Acceleration sensor data reporting.<br>-I3NJ8H: Gyroscope sensor data reporting.<br>-I3NJ7J: Ambient light sensor data reporting.<br>-I3NJ76: Magnetic field sensor data reporting.<br>-I4MBRP: Magnetic declination and dip.<br>-I4MBRQ: Horizontal intensity and total intensity of the magnetic field.| NA |
| Distributed Scheduler subsystem| - I4MBRW: Samgr supports intra-process system ability list control.<br>- I4MBRV: Samgr supports maintenance of the system service status list.<br>- I4MBRZ: Samgr supports initialization of the full service list.<br>- I4MBRY: Samgr supports maintenance of the system process status list.<br>- I4MBRX: Samgr supports loading a specific system service. | NA |
| DeviceProfile subsystem| - I4NY23: Insertion, deletion, and query of local device profiles.<br>- I4NY1X: Query of remote device profiles.<br>- I4NY1T: Subscription to remote profile changes.<br>- I4NY1W: Cross-device profile synchronization. | NA |
| Account subsystem| - I4MBQW: Application account addition and deletion.<br>- I4MBQV: Restrictions on the basic information about application accounts.<br>- I4MBQU: Application account subscription and unsubscription.<br>- I4MBQT: Application account function setting and content modification.<br>- I4MBQS: Application account information query.<br>- I4IT3U: Basic information management for application accounts. | NA |
| Pan-sensor subsystem| - I3NJ96: Acceleration sensor data reporting.<br>- I3NJ8H: Gyroscope sensor data reporting.<br>- I3NJ7J: Ambient light sensor data reporting.<br>- I3NJ76: Magnetic field sensor data reporting.<br>- I4MBRP: Magnetic declination and dip.<br>- I4MBRQ: Horizontal intensity and total intensity of the magnetic field. | NA |
| USB subsystem| I410OZ:<br>-&nbsp;Querying the list of connected USB devices.<br>-&nbsp;Obtaining the temporary permission to access USB devices.<br>-&nbsp;Setting USB device configurations and interfaces.<br>-&nbsp;Data transfer using USB devices.| NA |
| Multi-language Runtime subsystem| -&nbsp;I4MBUK: The default runtime of JS/TS is changed from quickjs to ARK. <br>-&nbsp;I4MBUJ: The memory reclaim capability of ARK runtime is enhanced. The concurrent marking and concurrent compression algorithms are supported. Some regions can be selected for compression GC, reducing the GC pause time by 30%.| NA |
| Globalization subsystem| -&nbsp;Added globalization features: singular and plural rules, string sorting, phone number processing, calendar and local calendar, weights and measures and formatting, locale representations and attributes, time segment formatting, alphabet retrieval, Unicode character attributes, wrapping and line feed.<br>-&nbsp;Supports system resources and rawfile resources.| NA |
| DSoftBus subsystem| -I4FZ29: DSoftBus provides the Ext API for transmission. <br> -I4FZ25: DSoftBus supports network switching.| -I4FZ29: DSoftBus provides the Ext API for transmission. <br> -I4FZ25: DSoftBus supports network switching.|
| Startup subsystem| NA | -I3XGJH: init basic environment building.<br>-I3XGKV: System parameter management.<br>-I3XGLN: init script management.<br>-I3XGMQ: Basic permission management.<br>-I3XGN8: Boot image building and loading.<br>-I3XGKV: uevent management.<br>-I3XGNM: Burning mode.|
| Media subsystem| NA | -I4BX5Z: HiStreamer supports audio playback and control.<br>-I4BX8A: HiStreamer supports playback of MP3 and WAV audio files.<br>-I4BX9E: HiStreamer playback engine framework requirements are met.<br>-I4DK89: HiStreamer plugin framework requirements are met.<br>-I4DK8D: HiStreamer performance and DFX requirements are met.|
| DSoftBus subsystem| - I4FZ29: DSoftBus provides the Ext API for transmission. <br> - I4FZ25: DSoftBus supports network switching. | - I4FZ29: DSoftBus provides the Ext API for transmission. <br> - I4FZ25: DSoftBus supports network switching. |
| Startup subsystem| NA | - I3XGJH: init basic environment building.<br>- I3XGKV: System parameter management.<br>- I3XGLN: init script management.<br>- I3XGMQ: Basic permission management.<br>- I3XGN8: Boot image building and loading.<br>- I3XGKV: uevent management.<br>- I3XGNM: Burning mode. |
| Media subsystem| NA | - I4BX5Z: HiStreamer supports audio playback and control.<br>- I4BX8A: HiStreamer supports playback of MP3 and WAV audio files.<br>- I4BX9E: HiStreamer playback engine framework requirements are met.<br>- I4DK89: HiStreamer plugin framework requirements are met.<br>- I4DK8D: HiStreamer performance and DFX requirements are met. |
| Graphics subsystem| New design of the OpenHarmony graphics stack:<br>Added the background rendering feature to the UI framework.<br>Supports the access to the background rendering module of RenderService from ArkUI components.| NA |
| Kernel subsystem| Kernel (Linux 5.10): <br>-I4LUG4: Supports Contiguous Memory Area (CMA) reuse. (Currently, only Hi3516D V300 is supported.)<br>-I4LX4G: Supports anonymous Virtual Memory Area (VMA) naming. (Currently, only Hi3516D V300 is supported.)| -I3ND6Y: Optimized OS kernel and driver startup performance.|
| Startup subsystem| NA | -I3NTCT: The Linux init process supports hot swap.|
| Distributed Data Management subsystem| NA | -I4H3JJ: Provides distributed objects for small-system devices.|
| Telephony subsystem| NA | -I4JQ2N: Provides HTTP JS APIs.<br>-I4JQ3G: Supports HTTP 2.0.|
| Kernel subsystem| Kernel (Linux 5.10): <br>- I4LUG4: Supports Contiguous Memory Area (CMA) reuse. (Currently, only Hi3516D V300 is supported.)<br>- I4LX4G: Supports anonymous Virtual Memory Area (VMA) naming. (Currently, only Hi3516D V300 is supported.) | - I3ND6Y: Optimized OS kernel and driver startup performance. |
| Startup subsystem| NA | - I3NTCT: The Linux init process supports hot swap. |
| Distributed Data Management subsystem| NA | - I4H3JJ: Provides distributed objects for small-system devices. |
| Telephony subsystem| NA | - I4JQ2N: Provides HTTP JS APIs.<br>- I4JQ3G: Supports HTTP 2.0. |
| Misc Services subsystem| I4MBQE:<br>Enables applications to read the system time.<br>Enables applications to read the system time zone.<br>Provides time change notifications.<br>Provides time zone change notifications.<br>Provides minute change notifications.| NA |
| Compilation and Building subsystem| I4K7E3: Provides a unified compilation command as the compilation entry.<br>-I4KCNB: Supports the unified gn template.| -I4MBQN: Supports a unified compilation entry and uses **build.sh** to compile mini- and small-system devices.<br>-I4MBQP: Supports a unified compilation process.<br>-I4MBQR: Supports unified product configuration.|
| File Storage subsystem| -I4MBS2: Provides StatFS JS interfaces for obtaining the total space and free space of a device.| NA |
| Driver subsystem| -I4L3KK: The drive capability of sensor components is enhanced. The sensor sampling rate can be dynamically configured, the three-axis direction can be statically configured, and the ambient light gain can be adjusted. <br>-I4L3LF: The sensor driver model capability is enhanced to support cross-process service obtaining and invoking of sensor HDIs. <br>-I4MBTS: Provides more capabilities for HDF input devices and supports data reporting of joystick devices. <br>-I4MBTR: The default reference implementation of the Display HDI interface for the standard system is provided based on the DRM display architecture, which helps vendors to adapt the HDI. <br>-I4HPR7: Provides the hcs macro parsing mechanism. During compilation, the hc-gen tool is used to parse the driver parameters into parameters involved in the macro definition. The driver accesses these macro definition parameters through the hcs macro-format interface. <br>-I4KVJQ: Supports system-level sleep/wakeup of the Linux and LiteOS kernels. <br>-I4L3ZZF: Supports synchronous/asynchronous power management invoking and provides a synchronous/asynchronous mechanism for HDF device sleep/wakeup management.| -I4L3KK: The drive capability of sensor components is enhanced. The sensor sampling rate can be dynamically configured, the three-axis direction can be statically configured, and the ambient light gain can be adjusted. <br>Provides more capabilities for HDF input devices (running on Linux) and supports data reporting of joystick devices. <br>-I4HPR7: Provides the hcs macro parsing mechanism. During compilation, the hc-gen tool is used to parse the driver parameters into parameters involved in the macro definition. The driver accesses these macro definition parameters through the hcs macro-format interface. <br>-I4KVJQ: Supports system-level sleep/wakeup of the Linux and LiteOS kernels. <br>-I4L3ZZF: Supports synchronous/asynchronous power management invoking and provides a synchronous/asynchronous mechanism for HDF device sleep/wakeup management.|
| Compilation and Building subsystem| - I4K7E3: Provides a unified compilation command as the compilation entry.<br>- I4KCNB: Supports the unified gn template. | - I4MBQN: Supports a unified compilation entry and uses **build.sh** to compile mini- and small-system devices.<br>- I4MBQP: Supports a unified compilation process.<br>- I4MBQR: Supports unified product configuration. |
| File Storage subsystem| - I4MBS2: Provides StatFS JS interfaces for obtaining the total space and free space of a device. | NA |
| Driver subsystem| - I4L3KK: The drive capability of sensor components is enhanced. The sensor sampling rate can be dynamically configured, the three-axis direction can be statically configured, and the ambient light gain can be adjusted. <br>- I4L3LF: The sensor driver model capability is enhanced to support cross-process service obtaining and invoking of sensor HDIs. <br>- I4MBTS: Provides more capabilities for HDF input devices and supports data reporting of joystick devices. <br>- I4MBTR: The default reference implementation of the Display HDI interface for the standard system is provided based on the DRM display architecture, which helps vendors to adapt the HDI. <br>- I4HPR7: Provides the hcs macro parsing mechanism. During compilation, the hc-gen tool is used to parse the driver parameters into parameters involved in the macro definition. The driver accesses these macro definition parameters through the hcs macro-format interface. <br>- I4KVJQ: Supports system-level sleep/wakeup of the Linux and LiteOS kernels. <br>- I4L3ZZF: Supports synchronous/asynchronous power management invoking and provides a synchronous/asynchronous mechanism for HDF device sleep/wakeup management. | - I4L3KK: The drive capability of sensor components is enhanced. The sensor sampling rate can be dynamically configured, the three-axis direction can be statically configured, and the ambient light gain can be adjusted. <br>Provides more capabilities for HDF input devices (running on Linux) and supports data reporting of joystick devices. <br>- I4HPR7: Provides the hcs macro parsing mechanism. During compilation, the hc-gen tool is used to parse the driver parameters into parameters involved in the macro definition. The driver accesses these macro definition parameters through the hcs macro-format interface. <br>- I4KVJQ: Supports system-level sleep/wakeup of the Linux and LiteOS kernels. <br>- I4L3ZZF: Supports synchronous/asynchronous power management invoking and provides a synchronous/asynchronous mechanism for HDF device sleep/wakeup management. |
| ArkUI| - I4MBUY: Added **target** to the event to obtain the size.<br>- I4MBUZ: The **\<Swiper>** component supports cache setting.<br>- I4MBV1: The **\<Image>** component supports synchronous and asynchronous rendering setting.<br>- I4MBV3: Added the component polymorphic style setting to the style setting feature.<br>- I4MBV5: Added the pop-up text for menu content extension to the **\<AlphabetIndexer>** component.<br>- I4MBV6: Added the custom container components to the component customization feature.<br>- I4MBV7: Added scroll bar style customization.<br>- I4MBV8: Added switching forbidden for the **\<Swiper>** component.<br>- I4MBV9: Added tab bar content customization for the **\<Tabs>** component.<br>- I4MBVA: Added title bar setting for the **\<Navigation>** component.<br>- I4MBVB: Added toolbar display/hide control for the **\<toolbar>** component.<br>- I4MBVC: Added content customization for the **\<toolbar>** component.<br>- I4MBVD: Added the SysCap declaration compilation feature.<br>- I4MBVE: Added the JSSDK compilation feature.<br>- I4MBVF: Added the **Config.json** compilation feature.<br>- I4MBVG: Added the breakpoint debugging feature for single-instance debugging.<br>- I4MBVH: Added the attach debugging feature for single-instance debugging.<br>- I4MBVI: Added the declarative paradigm compilation feature to support compilation and verification.<br>- I4MBVJ: Added the JS module shared compilation feature.<br>- I4MBVK: Added the HAR reference and compilation feature.<br>- I4MBVL: Added the HPM reference and compilation feature.<br>- I4MBVN: Added the vertical display of the slider bar.<br>- I4MBVO: Added the content customization feature for the **\<popup>** component.<br>- I4MBVP: Added the drawing capability for the **\<canvas>** component.<br>- I4MBVQ: Enhanced the capabilities of the **\<canvas>** component.<br>- I4MBVR: Added the touch target setting.<br>- I4MBVS: Added the support for Lottie animation.<br>- I4MBVT: Added the feature for obtaining the component size.<br>- I4MBVU: Added content customization to the **\<menu>** component.<br>- I4MBVV: Added the support for the **\<swipe>** gesture.<br>- I4MBVW: Added the inspector capability for UI preview.<br>- I4MBVX: Added the non-route file preview feature.<br>- I4MBVY: Added the NAPI preview feature.<br>- I4MBVZ: Added the declarative paradigm preview feature with the basic preview supported.<br>- I4MBW2: Added the declarative paradigm hot loading feature for modification to the existing nodes.<br>- I4MBW3: Added the declarative paradigm hot loading feature for node addition.<br>- I4MBW4: Added the declarative paradigm hot loading feature for node deletion.<br>- I4MBW5: Added the component preview feature and the page component preview.<br>Added the universal attribute **touchable** to specify whether a component is touchable. <br>Added the basic component **\<Marquee>**. <br>Added the basic component **\<Gauge>**. <br>Added the basic component **\<TextArea>**. <br>Added the basic component **\<TextInput>**. <br>Added the basic component **\<Toggle>**. <br>Added the container component **\<Stepper>**. <br>Added the container component **\<StepperItem>**. <br>Added the global UI method **\<ActionSheet>**.| NA |
| DFX subsystem| -I4MBQH: Added the **HiSysEvent** class and provided the query and subscription interfaces.<br>-I4MBQJ: Provides the tool query or subscription system event.<br>-I4MBQL: Added the C interface of the **HiAppEvent** class.| NA |
| Application subsystems| -I4MBU1: Added **Settings** data management APIs. <br>-I4MBU3: Added time setting. <br>-I4MBU5: Supports sound management. <br>-I4MBU6: Added **Settings** data management. <br>-I4MBU7: Added **Settings** default value management.<br>-I4MBU8: Added differentiated construction of multiple device forms in **Settings**.<br>-I4MBU9: Added component-based notifications.| NA |
| DFX subsystem| - I4MBQH: Added the **HiSysEvent** class and provided the query and subscription interfaces.<br>- I4MBQJ: Provides the tool query or subscription system event.<br>- I4MBQL: Added the C interface of the **HiAppEvent** class. | NA |
| Application subsystems| - I4MBU1: Added **Settings** data management APIs. <br>- I4MBU3: Added time setting. <br>- I4MBU5: Supports sound management. <br>- I4MBU6: Added **Settings** data management. <br>- I4MBU7: Added **Settings** default value management.<br>- I4MBU8: Added differentiated construction of multiple device forms in **Settings**.<br>- I4MBU9: Added component-based notifications. | NA |
### API Updates
......@@ -137,7 +137,7 @@ _[Changelog](api-diff/v3.1-beta/changelog-v3.1-beta.md)_
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples &amp; Codelabs
......@@ -149,17 +149,17 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| Name| Introduction| Programming Language|
| -------- | -------- | -------- |
| [eTS Common Event](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent) | This sample shows how to use **CommonEvent** APIs in Extended TypeScript (eTS) to create subscribers and subscribe to, publish, and unsubscribe from common events.| eTS |
| [ArkTS Common Event](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent) | This sample shows how to use **CommonEvent** APIs in ArkTS to create subscribers and subscribe to, publish, and unsubscribe from common events. | ArkTS |
| [Air Quality](https://gitee.com/openharmony/app_samples/tree/master/common/AirQuality)| This sample implements a simple air quality app using JS. The app displays air quality information using line wrapping and historical data in a bar chart.| JS |
| [Distributed Calculator](https://gitee.com/openharmony/app_samples/tree/master/common/DistributeCalc)| This sample implements a simple calculator app using JS distributed features. The calculator can perform simple numerical calculations and start a remote calculator Feature Ability (FA) to perform collaborative calculation.| JS |
| [eTS Notification](https://gitee.com/openharmony/app_samples/tree/master/common/Notification) | This sample shows how to create and delete a slot in eTS, and how to publish and cancel a notification.| eTS |
| [eTS Resource Management](https://gitee.com/openharmony/app_samples/tree/master/common/ResourceManager) | This sample shows how to call resource management APIs in eTS to obtain strings and images.| eTS |
| [ArkTS Notification](https://gitee.com/openharmony/app_samples/tree/master/common/Notification) | This sample shows how to create and delete a slot in ArkTS, and how to publish and cancel a notification. | ArkTS |
| [ArkTS Resource Management](https://gitee.com/openharmony/app_samples/tree/master/common/ResourceManager) | This sample shows how to call resource management APIs in ArkTS to obtain strings and images. | ArkTS |
| [Kika Keyboard](https://gitee.com/openharmony/app_samples/tree/master/CompleteApps/KikaInput) | This sample shows how to implement a lightweight input method app, Kika Keyboard, that can run on smart devices powered by OpenHarmony.| JS |
| [eTS Distributed Data Management](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) | This sample shows how to use distributed data management in eTS, including creating a **KvManager** instance and using KvStore data transfer.| eTS |
| [Lightweight Data Storage](https://gitee.com/openharmony/app_samples/tree/master/data/LiteStorage) | Lightweight data storage supports lightweight key-value operations and allows local apps to store a small amount of data. This sample shows how to add offerings to the shopping cart, remove offerings from the shopping cart, and saving the shopping cart. The shopping cart information is retained even when the app is closed. This reflects the lightweight storage feature.| eTS |
| [eTS Process](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Process) | This sample shows how to obtain process information and start a child process to run a shell script in eTS. With this sample, you can obtain the running time, obtain and change the working directory of a process, send a signal to a specific process, start or close a child process, and exit the current process.| eTS |
| [eTS Running Lock](https://gitee.com/openharmony/app_samples/tree/master/common/Runninglock) | This sample shows how to test the running lock that prevents the system from entering sleep mode. It uses the black and white wallpapers to simulate the screen-off and screen-on states.| eTS |
| [String Codec](https://gitee.com/openharmony/app_samples/tree/master/Util/UtilStringCodec) | This sample shows how to output strings in a specified format and output error codes in text format. It also demonstrates string encoding and decoding.| eTS |
| [ArkTS Distributed Data Management](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) | This sample shows how to use distributed data management in ArkTS, including creating a **KvManager** instance and using KvStore data transfer. | ArkTS |
| [Lightweight Data Storage](https://gitee.com/openharmony/app_samples/tree/master/data/LiteStorage) | Lightweight data storage supports lightweight key-value operations and allows local apps to store a small amount of data. This sample shows how to add offerings to the shopping cart, remove offerings from the shopping cart, and saving the shopping cart. The shopping cart information is retained even when the app is closed. This reflects the lightweight storage feature.| ArkTS |
| [ArkTS Process](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Process) | This sample shows how to obtain process information and start a child process to run a shell script in ArkTS. With this sample, you can obtain the running time, obtain and change the working directory of a process, send a signal to a specific process, start or close a child process, and exit the current process. | ArkTS |
| [ArkTS Running Lock](https://gitee.com/openharmony/app_samples/tree/master/common/Runninglock) | This sample shows how to test the running lock that prevents the system from entering sleep mode. It uses the black and white wallpapers to simulate the screen-off and screen-on states.| ArkTS |
| [String Codec](https://gitee.com/openharmony/app_samples/tree/master/Util/UtilStringCodec) | This sample shows how to output strings in a specified format and output error codes in text format. It also demonstrates string encoding and decoding.| ArkTS |
| [JS Audio Playback and Management](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)| This sample shows how to use the JS-based audio playback feature and set the volume.| JS |
| [JS Video](https://gitee.com/openharmony/app_samples/tree/master/media/JsVideo) | This sample shows how to use the JS UI component **\<video>** to implement video playback. You can play a video clip and pause the playback through the control bar of the **\<video>** component.| JS |
| [Dot Test](https://gitee.com/openharmony/app_samples/tree/master/DFX/JsDotTest)| This sample illustrates the dot test function, including application dotting and performance dotting.| JS |
......@@ -178,16 +178,16 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| Name| Introduction| Programming Language|
| -------- | -------- | -------- |
| [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)| This codelab shows how to implement synchronous writing and interaction between multiple devices based on the distributed feature.| eTS |
| [Synced Sketchpad (ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)| This codelab shows how to implement synchronous writing and interaction between multiple devices based on the distributed feature.| ArkTS |
| [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)| This codelab shows how to use the Distributed Data Service APIs to facilitate consistent data access between devices.| JS |
| [Relational Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData)| This codelab shows how to quickly develop database-related application services based on the relational database and data management capability.| JS |
| [Simplified Declarative UI Paradigm (eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleGalleryEts)| This codelab shows how to implement a gallery app based on OpenHarmony eTS UI components.| eTS |
| [One-Time Development for Multi-device Deployment (eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/Multi_device)| This codelab shows how to implement one-time layout development for multi-device deployment based on OpenHarmony eTS UI components.| eTS |
| [Shopping (eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ShoppingEts)| This codelab shows how to implement a shopping app based on OpenHarmony eTS UI components.| eTS |
| [Transition Animation (eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimation)| This codelab shows how to implement page transition, component transition, and transition of shared elements based on OpenHarmony eTS UI components.| eTS |
| [slider Usage (eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderExample)| This codelab shows how to use the OpenHarmony eTS UI component **\<slider>** to implement the animation effect when users adjust the size and speed of the windmill.| eTS |
| [Liquid Layout (eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/FlowLayoutEts)| This codelab shows how to implement the liquid layout based on the OpenHarmony eTS UI components.| eTS |
| [Dialog Box (eTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CustomDialogEts)| This codelab shows how to implement an alert dialog box and custom dialog box based on OpenHarmony eTS UI components.| eTS |
| [Simplified Declarative UI Paradigm (ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleGalleryEts) | This codelab shows how to implement a gallery app based on OpenHarmony ArkUI components. | ArkTS |
| [One-Time Development for Multi-device Deployment (ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/Multi_device) | This codelab shows how to implement one-time layout development for multi-device deployment based on OpenHarmony ArkTS UI components. | ArkTS |
| [Shopping (ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ShoppingEts) | This codelab shows how to implement a shopping app based on OpenHarmony ArkTS UI components. | ArkTS |
| [Transition Animation (ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimation) | This codelab shows how to implement page transition, component transition, and transition of shared elements based on OpenHarmony ArkUI components. | ArkTS |
| [slider Usage (ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderExample) | This codelab shows how to use the OpenHarmony ArkUI component **\<slider>** to implement the animation effect when users adjust the size and speed of the windmill. | ArkTS |
| [Liquid Layout (ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/FlowLayoutEts) | This codelab shows how to implement the liquid layout based on the OpenHarmony ArkTS UI components. | ArkTS |
| [Dialog Box (ArkTS)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CustomDialogEts) | This codelab shows how to implement an alert dialog box and custom dialog box based on OpenHarmony ArkTS UI components. | ArkTS |
## Resolved Issues
......
......@@ -194,7 +194,7 @@ For details, see the following:
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples & Codelabs
......@@ -204,23 +204,23 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| Subsystem name| Sample Name| Introduction| Programming Language|
| -------- | -------- | -------- | -------- |
| Telephony| [SMS](https://gitee.com/openharmony/app_samples/tree/master/Telephony/Message)| This sample shows how to send SMS messages.| eTS |
| Telephony| [Radio](https://gitee.com/openharmony/app_samples/tree/master/Telephony/RadioTech)| This sample shows how to use the radio function of the telephony service in eTS to obtain information, including the radio access technology, network status, network selection mode, ISO country code, signal strength list, and whether the radio function is enabled.| eTS |
| Device management| [Power Management](https://gitee.com/openharmony/app_samples/tree/master/common/PowerManager)| This sample shows how to power off a device, restart the system, and check the screen status.| eTS |
| Device management| [Sensor](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor)| This sample uses the orientation sensor APIs to implement the compass effect.| eTS |
| Device management| [Device Management](https://gitee.com/openharmony/app_samples/tree/master/device/DeviceManager)| This sample shows the use of the **DeviceManager** API in eTS, including obtaining the trusted device list, scanning for devices, authenticating devices, and subscribing to device status changes.| eTS |
| Account management| [Application Account Management](https://gitee.com/openharmony/app_samples/tree/master/Account/AppAccountManager)| This sample shows how to register/log in to an application and set the account information to demonstrate application account management.| eTS |
| ArkUI | [web](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Web)| This sample shows the function pages of the **\<Web>** component.| eTS |
| ArkUI | [Drag](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Drag)| This sample shows the drag operation function.| eTS |
| ArkUI | [Animation](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/ArkUIAnimation)| This sample demonstrates the effect of the **AnimatorProperty** and **Explicit Animation**.| eTS |
| Data management| [Querying the DDM Result Set](https://gitee.com/openharmony/app_samples/tree/master/data/DDMQuery)| This sample shows how to create a query object to query data in a key-value (KV) store and obtain the result set in distributed data management (DDM).| eTS |
| Data management| [eTS RDB](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) | This sample shows how to use a relational database (RDB) in eTS, including adding, deleting, modifying, and querying data.| eTS |
| Common event and notification| [Reminder Agent](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock)| This sample shows how to use the reminder agent by simulating an alarm clock.| eTS |
| Common event and notification| [Event notification](https://gitee.com/openharmony/app_samples/tree/master/Notification/Emitter)| This sample shows the in-process event notification. After a user selects an offering and submits an order, the selected offering is displayed in the order list.| eTS |
| Connectivity| [RPC](https://gitee.com/openharmony/app_samples/tree/master/Communication/RPC)| This sample shows the data exchange between the frontend and backend of a device. After the offering and quantity are selected at the frontend, the backend calculates the result and displays it at the frontend.| eTS |
| Connectivity| [WLAN](https://gitee.com/openharmony/app_samples/tree/master/Communication/Wlan) | This sample shows how to use WLAN with eTS, including disabling and enabling the WLAN, scanning the WLAN and obtaining the scanning result, listening for WLAN status and Wi-Fi connection status, obtaining the IP address, country code, and checking whether the device supports WLAN features.| eTS |
| Multimedia| [Recorder](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)| This sample shows how to use audio recording and playback of the media service.| eTS |
| Multimedia| [Multimedia](https://gitee.com/openharmony/app_samples/tree/master/media/MultiMedia)| This demo shows how to invoke the camera to take photos in eTS and how to use the **MediaLibrary** APIs to add, delete, modify, and query media files.| eTS |
| Telephony| [SMS](https://gitee.com/openharmony/app_samples/tree/master/Telephony/Message)| This sample shows how to send SMS messages.| ArkTS |
| Telephony| [Radio](https://gitee.com/openharmony/app_samples/tree/master/Telephony/RadioTech)| This sample shows how to use the radio function of the telephony service in ArkTS to obtain information, including the radio access technology, network status, network selection mode, ISO country code, signal strength list, and whether the radio function is enabled. | ArkTS |
| Device management| [Power Management](https://gitee.com/openharmony/app_samples/tree/master/common/PowerManager)| This sample shows how to power off a device, restart the system, and check the screen status.| ArkTS |
| Device management| [Sensor](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor)| This sample uses the orientation sensor APIs to implement the compass effect.| ArkTS |
| Device management| [Device Management](https://gitee.com/openharmony/app_samples/tree/master/device/DeviceManager)| This sample shows the use of the **DeviceManager** API in ArkTS, including obtaining the trusted device list, scanning for devices, authenticating devices, and subscribing to device status changes. | ArkTS |
| Account management| [Application Account Management](https://gitee.com/openharmony/app_samples/tree/master/Account/AppAccountManager)| This sample shows how to register/log in to an application and set the account information to demonstrate application account management.| ArkTS |
| ArkUI | [web](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Web)| This sample shows the function pages of the **\<Web>** component.| ArkTS |
| ArkUI | [Drag](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/Drag)| This sample shows the drag operation function.| ArkTS |
| ArkUI | [Animation](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/ArkUIAnimation)| This sample demonstrates the effect of the **AnimatorProperty** and **Explicit Animation**.| ArkTS |
| Data management| [Querying the DDM Result Set](https://gitee.com/openharmony/app_samples/tree/master/data/DDMQuery)| This sample shows how to create a query object to query data in a key-value (KV) store and obtain the result set in distributed data management (DDM).| ArkTS |
| Data management| [ArkTS RDB](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) | This sample shows how to use a relational database (RDB) in ArkTS, including adding, deleting, modifying, and querying data. | ArkTS |
| Common event and notification| [Reminder Agent](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock)| This sample shows how to use the reminder agent by simulating an alarm clock.| ArkTS |
| Common event and notification| [Event notification](https://gitee.com/openharmony/app_samples/tree/master/Notification/Emitter)| This sample shows the in-process event notification. After a user selects an offering and submits an order, the selected offering is displayed in the order list.| ArkTS |
| Connectivity| [RPC](https://gitee.com/openharmony/app_samples/tree/master/Communication/RPC)| This sample shows the data exchange between the frontend and backend of a device. After the offering and quantity are selected at the frontend, the backend calculates the result and displays it at the frontend.| ArkTS |
| Connectivity| [WLAN](https://gitee.com/openharmony/app_samples/tree/master/Communication/Wlan) | This sample shows how to use WLAN with ArkTS, including disabling and enabling the WLAN, scanning the WLAN and obtaining the scanning result, listening for WLAN status and Wi-Fi connection status, obtaining the IP address, country code, and checking whether the device supports WLAN features. | ArkTS |
| Multimedia| [Recorder](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)| This sample shows how to use audio recording and playback of the media service.| ArkTS |
| Multimedia| [Multimedia](https://gitee.com/openharmony/app_samples/tree/master/media/MultiMedia)| This demo shows how to invoke the camera to take photos in ArkTS and how to use the **MediaLibrary** APIs to add, delete, modify, and query media files. | ArkTS |
For more information, visit [Samples](https://gitee.com/openharmony/app_samples).
......@@ -231,13 +231,13 @@ For more information, visit [Samples](https://gitee.com/openharmony/app_samples)
| Codelab Name | Introduction | Programming Language|
| ------------------------------------------------------------ | ------------------------------------------------------------ | -------- |
| [Distributed Authentication](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH)| This codelab shows how to develop a distributed game authentication application in JS and how to use the distributed startup, **DeviceManager** objects, and device attribute display interfaces.| JS |
| [Distributed Game Controller](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication)| This codelab shows how to develop a game controller in eTS. By leveraging the distributed capabilities, one development board is used as the game controller, and another development board is used as the game server.| eTS |
| [Distributed Jigsaw Puzzle](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame)| This codelab shows how to develop a jigsaw puzzle. In this development, the RPC is used for cross-device communication, and **CommonEvent** is used to implement communication between the Service ability and FA.| eTS |
| [Distributed Control](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS)| This codelab shows how to develop a distributed control in eTS. By leveraging the distributed capabilities, one development board is used as the TV, and another development board is used as the remote control.| eTS |
| [Audio Recording](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)| This codelab shows how to use **AudioRecorder** to record an audio file and use **AudioPlayer** to play the recorded audio.| eTS |
| [Notepad](https://gitee.com/openharmony/codelabs/tree/master/Data/NotePad_OH_ETS)| This codelab shows how to develop a notepad in eTS. You can create, delete, and favorite notes, and use the lightweight database to store data persistently.| eTS |
| [Distributed Mail Editing](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS)| This codelab shows how to develop the distributed email editing function. By leveraging the distributed capabilities, a remote device in the same LAN and with the same login account can be started, and email editing can be continued on the remote device.| eTS |
| [Third-party Library](https://gitee.com/openharmony/codelabs/tree/master/ThirdPartyComponents/VCardDemo)| This codelab shows how to use vcard, a third-party library used in OpenHarmony to write and read contact data in a specified format (file with the extension name **vcard**).| eTS |
| [Distributed Game Controller](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication)| This codelab shows how to develop a game controller in ArkTS. By leveraging the distributed capabilities, one development board is used as the game controller, and another development board is used as the game server. | ArkTS |
| [Distributed Jigsaw Puzzle](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame)| This codelab shows how to develop a jigsaw puzzle. In this development, the RPC is used for cross-device communication, and **CommonEvent** is used to implement communication between the Service ability and FA.| ArkTS |
| [Distributed Control](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS)| This codelab shows how to develop a distributed control in ArkTS. By leveraging the distributed capabilities, one development board is used as the TV, and another development board is used as the remote control. | ArkTS |
| [Audio Recording](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)| This codelab shows how to use **AudioRecorder** to record an audio file and use **AudioPlayer** to play the recorded audio.| ArkTS |
| [Notepad](https://gitee.com/openharmony/codelabs/tree/master/Data/NotePad_OH_ETS)| This codelab shows how to develop a notepad in ArkTS. You can create, delete, and favorite notes, and use the lightweight database to store data persistently. | ArkTS |
| [Distributed Mail Editing](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS)| This codelab shows how to develop the distributed email editing function. By leveraging the distributed capabilities, a remote device in the same LAN and with the same login account can be started, and email editing can be continued on the remote device.| ArkTS |
| [Third-party Library](https://gitee.com/openharmony/codelabs/tree/master/ThirdPartyComponents/VCardDemo)| This codelab shows how to use vcard, a third-party library used in OpenHarmony to write and read contact data in a specified format (file with the extension name **vcard**).| ArkTS |
## Resolved Issues
......
......@@ -142,7 +142,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -117,7 +117,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -101,7 +101,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
## Resolved Issues
......
......@@ -104,7 +104,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Resolved Issues
......
......@@ -104,7 +104,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Resolved Issues
......
......@@ -102,7 +102,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Resolved Issues
......
......@@ -101,7 +101,7 @@ This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Resolved Issues
......
......@@ -176,7 +176,7 @@ This version has the following updates to OpenHarmony 3.1 Release.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples
......@@ -185,14 +185,12 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| Subsystem| Sample| Introduction| Programming Language|
| -------- | -------- | -------- | -------- |
| ArkUI | [MouseEvent](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) | This sample simulates a minesweeper game that calls mouse event-related APIs.| ArkTS |
| ArkUI | [Vibrator](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Vibrator) | This sample simulates the countdown scenario to show the use of the vibrator APIs.| ArkTS |
| DFX | [FaultLogger](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DFX/FaultLogger) | This sample illustrates how to obtain fault information of an application in ArkTS.| ArkTS |
| ArkUI | [Gallery](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) | This sample demonstrates the functions of different components such as universal events, universal attributes, and gestures.| ArkTS |
| Graphics| [JsWebGL](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/JsWebGL) | This sample shows how to use WebGL APIs to draw pentagrams and rectangles by invoking GPU resources.| JS |
| ArkUI | [ArkTSClock](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Tools/ArkTSClock) | This sample exemplifies how to implement a simple clock application using the ArkTS UI capability.| ArkTS |
| ArkUI | [ComponentCollection](https://gitee.com/openharmony/applications_app_samples/tree/master/code/UI/ArkTsComponentClollection/ComponentCollection) | This sample illustrates all the components, animations, and global methods of ArkUI.| ArkTS |
| ArkUI | [ArkTSClock](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Tools/ArkTSClock) | This sample exemplifies how to implement a simple clock application using the ArkTS UI capability. | ArkTS |
| Network management| [Http](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) | This sample simulates Postman, which requires the input of an API address and outputs the data obtained, to show the use of the data request APIs.| ArkTS |
| Network management| [Socket](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) | This sample demonstrates the application of Socket in network communication, including connection authentication and chat communication between two devices.| ArkTS |
| Network management| [Socket](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Socket) | This sample demonstrates the application of Socket in network communication, including connection authentication and chat communication between two devices.| ArkTS |
| Distributed data management| [DistributedRdb](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/DistributedAppDev/DistributedRdb) | This sample shows how to add, delete, modify, query, and synchronize data in the distributed relational database with ArkTS.| ArkTS |
| Ability| [WorkScheduler](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler) | This sample simulates the update process starting from downloading and saving an update package to sending a notification and installing the update package. Being processed by the background task management, the download task continues after the application exits. It stops until the download is complete.| ArkTS |
| Ability| [AbilityStartMode](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/AbilityStartMode) | This sample shows how to implement the standard, singleton, and specified ability launch modes in the stage model.| ArkTS |
......@@ -204,7 +202,6 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| ArkUI | [Game2048](https://gitee.com/openharmony/applications_app_samples/tree/master/code/Solutions/Game/Game2048) | This sample shows how to develop a 2048 game using the **\<Grid>** component.| ArkTS |
| Typical Setting Page of One-Time Development for Multi-Device Deployment| [Settings](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Settings) | This sample shows a typical page for setting an application. The page has different display effects in the small window and large window, reflecting the capability of one-time development for multi-device deployment.| ArkTS |
| Distributed data management| [Preference](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DataManagement/Preferences) | This sample shows the theme switching function of preferences.| ArkTS |
| ArkUI | [NativeAPI](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) | This sample shows how to call C++ APIs in ArkTS and how C++ APIs call back JS APIs to play the Gomoku game. The native APIs implement the calculation logic, and ArkTS implements UI rendering and re-rendering.| ArkTS/C++ |
| Globalization| [International](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/Internationalnation/International) | This sample shows how to use APIs related to i18n, intl, and resourceManager in ArkTS to set the system language, region, time, and time zone. It also provides locale setting examples.| ArkTS |
For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples).
......
......@@ -158,7 +158,7 @@ If an application developed using the SDK of an earlier version calls system API
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples
......
......@@ -181,7 +181,7 @@ For details about the API changes, see the following:
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples
......@@ -193,7 +193,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| ArkUI development framework| [HealthyDiet](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/HealthyDiet)| This sample app helps you keep food records and view food information. After you add food records, including the food type, weight, and meal time, the app can calculate nutrition data (calories, proteins, fats, and carbon water) for the meals and display the data in a bar chart.| ArkTS |
| ArkUI development framework| [MusicAlbum](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/MusicAlbum)| This sample shows the home page of a music album app. The adaptive layout and responsive layout are used to ensure that the app can be properly displayed on devices irrespective of screen sizes.| ArkTS |
| Ability framework and file management subsystem| [CustomShare](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/ApplicationModels/CustomShare) | Using this sample app, you can share texts, links, and images with third-party applications and display them in these applications.| ArkTS |
| Ability framework| [GalleryForm](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm)| This sample demonstrates the display of **Gallery** images in a widget and periodic update of the widget.| ArkTS |
| Ability framework| [GalleryForm](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/FormExtAbility) | This sample demonstrates the display of **Gallery** images in a widget and periodic update of the widget.| ArkTS |
| ArkUI development framework| [AppMarket](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/AppMarket) | This sample shows the home page of an application market, which contains the tab bar, banner, featured apps, and featured games.| ArkTS |
| ArkUI development framework| [Weather](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/MultiDeviceAppDev/Weather) | This sample demonstrates one-time development for multi-device deployment by showing how to develop a weather app and deploy it across different devices. The demo app includes the following: home page, **Manage City** page, **Add City** page, and **Update Time** page.| ArkTS |
| Multimedia subsystem| [MediaCollections](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/FileManagement/MediaCollections) | This sample shows the capabilities of online streaming, audio and video playback control, and volume adjustment.| ArkTS |
......
......@@ -193,7 +193,7 @@ For details about the API changes, see the following:
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples
......
......@@ -45,9 +45,9 @@ BLE connection parameters can be configured, and the connection process is optim
| Software/Tool| Version| Remarks|
| -------- | -------- | -------- |
| OpenHarmony | 3.2 Beta5 | NA |
| Public SDK | Ohos_sdk_public 3.2.10.6 (API Version 9 Beta5) | This toolkit is intended for application developers and does not contain system APIs that require system permissions. It is provided as standard in DevEco Studio.|
| (Optional) HUAWEI DevEco Studio| *To be released*| Recommended for developing OpenHarmony applications|
| (Optional) HUAWEI DevEco Device Tool| *To be released*| Recommended for developing OpenHarmony smart devices|
| Public SDK | Ohos_sdk_public 3.2.10.6 (API Version 9 Beta5) | This toolkit is intended for application developers and does not contain system APIs that require system permissions.<br>It is provided as standard in DevEco Studio.|
| (Optional) HUAWEI DevEco Studio| 3.1 Beta1 | Recommended for developing OpenHarmony applications |
| (Optional) HUAWEI DevEco Device Tool| 3.1 Beta2 | Recommended for developing OpenHarmony smart devices |
## Source Code Acquisition
......@@ -137,9 +137,9 @@ This version has the following updates to OpenHarmony 3.2 Beta4.
### SDK Updates
From this version, only the public SDK is released. It can also be downloaded through DevEco Studio.
From this version on, only the public SDK is released. You can obtain the public SDK from the mirror or download it from DevEco Studio for your application development.
To use the full SDK, you must download the source code, build the source code, and switch to the full SDK. For details, see [Guide to Building Full SDK](../application-dev/quick-start/full-sdk-compile-guide.md).
To use the full SDK that contains system APIs, you must download the full code, compile and build an SDK file, and switch to the full SDK on DevEco Studio. For details about how to compile the full SDK using the source code, see [Full SDK Compilation Guide](../application-dev/quick-start/full-sdk-compile-guide.md).
### Feature Updates
......@@ -162,12 +162,30 @@ To use the full SDK, you must download the source code, build the source code, a
| File storage| - Unified URI processing is added for application files.<br>- Temporary authorization and unified open entry are added for user data.<br>The following requirements are involved:<br>I687C8 [New capability] Unified URI processing for application files<br>I64U8W [Basic capability] Temporary authorization and unified open entry for user data| NA |
| Ability framework| - The restart of resident processes is optimized.<br>- The widget database can be switched.<br>- The asynchronous **onConnected** lifecycle is provided.<br>The following requirements are involved:<br>I65M3F [Basic capability] ShellCommand execution control<br>I65V83 [Basic capability] ServiceExtensionAbility support for asynchronous **onConnected** lifecycle<br>I61H21 [Basic capability] Change of the local widget database<br>I63UJ5 [Ability] [ability_runtime] Exception handling in API version 8 and earlier versions<br>I6BDCW [Basic capability] Forbidden to load code in the **data** directory during application loading<br>I6BDDU [Basic capability] Default ability launch mode of the FA model: Standard<br>I6BDE2 [Basic capability] Protection against frequent restart of resident applications| NA |
For details about the API changes, see [API Differences](api-diff/v3.2-beta5/Readme-EN.md).
For details about the API changes of each subsystem, see [Changelogs](changelogs/v3.2-beta5/Readme-EN.md).
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples
**Table 4** New samples
| Subsystem| Name| Introduction| Programming Language|
| -------- | -------- | -------- | -------- |
| Multimedia subsystem| [QR code scanning](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/media/Scan)| The sample app is used to scan QR code. With the app, you can select a QR code image from a folder to identify the QR code information.| ArkTS|
| ArkUI | [Home Page of the Application Market](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/MultiDeviceAppDev/AppMarket)| This sample shows the home page of the application market. The page has different display effects in the small window and large window, reflecting the capability of one-time development for multi-device deployment.| ArkTS|
| File management subsystem| [File Management](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/FileManager/FileIo)| This sample demonstrates file management. It uses the [mediaLibrary](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md), [userFileManager](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-userFileManager.md) and [fileio](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-fileio.md) APIs to add and access media library files and files in the application sandbox.| ArkTS|
| Ability framework| [Gallery Widget](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/ability/GalleryForm)| This sample demonstrates the display of **Gallery** images in a widget and periodic update of the widget.| ArkTS|
For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples).
## Resolved Issues
**Table 5** Resolved issues
......@@ -193,3 +211,4 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| I6BRTS | Invoking the **rdb::executeSql** interface may cause memory leakage.| Memory leakage occurs when the **rdb::executeSql** interface is repeatedly called during initialization. This interface is called only during application initialization, and therefore the impact of memory leakage is controllable.| 2023-02-10|
| I6AZ4T | Memory leakage exists for applications with the **\<textInput>** component.| Memory leakage occurs when the **\<textInput>** component is repeatedly called at a high frequency. The root cause is that the memory is not reclaimed during the calling of the third-party library flutter. We will first check whether the problem is caused by the open-source flutter component.| 2023-02-10|
<!--no_check-->
\ No newline at end of file
......@@ -588,7 +588,7 @@ For details about the API changes, see the following:
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
For details about the adaptation status, see [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples
......
# Readme
# JS API Differences
* JS API Differences
- [Ability framework](js-apidiff-ability.md)
- [Accessibility subsystem](js-apidiff-accessibility.md)
- [Account subsystem](js-apidiff-account.md)
- [Application subsystem](js-apidiff-application.md)
- [ArkUI development framework](js-apidiff-arkui.md)
- [Power management subsystem](js-apidiff-battery.md)
- [Bundle management framework](js-apidiff-bundle.md)
- [Communication subsystem](js-apidiff-communication.md)
- [Compiler and runtime subsystem](js-apidiff-compiler-and-runtime.md)
- [Customization subsystem](js-apidiff-customization.md)
- [DFX subsystem](js-apidiff-dfx.md)
- [Distributed data management subsystem](js-apidiff-distributed-data.md)
- [Distributed hardware subsystem](js-apidiff-distributed-hardware.md)
- [File management subsystem](js-apidiff-file-management.md)
- [Location subsystem](js-apidiff-geolocation.md)
- [Globalization subsystem](js-apidiff-global.md)
- [Misc services subsystem](js-apidiff-misc.md)
- [MSDP subsystem](js-apidiff-msdp.md)
- [Multimodal input subsystem](js-apidiff-multi-modal-input.md)
- [Multimedia subsystem](js-apidiff-multimedia.md)
- [Common event and notification subsystem](js-apidiff-notification.md)
- [Resource scheduler subsystem](js-apidiff-resource-scheduler.md)
- [Security subsystem](js-apidiff-security.md)
- [Pan-sensor subsystem](js-apidiff-sensor.md)
- [Startup subsystem](js-apidiff-start-up.md)
- [Telephony subsystem](js-apidiff-telephony.md)
- [Test subsystem](js-apidiff-unitest.md)
- [Update subsystem](js-apidiff-update.md)
- [USB subsystem](js-apidiff-usb.md)
- [User IAM subsystem](js-apidiff-user-iam.md)
- [Web subsystem](js-apidiff-web.md)
- [Window manager subsystem](js-apidiff-window.md)
\ No newline at end of file
- [Ability framework](js-apidiff-ability.md)
- [Accessibility subsystem](js-apidiff-accessibility.md)
- [Account subsystem](js-apidiff-account.md)
- [Application subsystem](js-apidiff-application.md)
- [ArkUI development framework](js-apidiff-arkui.md)
- [Power management subsystem](js-apidiff-battery.md)
- [Bundle management framework](js-apidiff-bundle.md)
- [Communication subsystem](js-apidiff-communication.md)
- [Compiler and runtime subsystem](js-apidiff-compiler-and-runtime.md)
- [Customization subsystem](js-apidiff-customization.md)
- [DFX subsystem](js-apidiff-dfx.md)
- [Distributed data management subsystem](js-apidiff-distributed-data.md)
- [Distributed hardware subsystem](js-apidiff-distributed-hardware.md)
- [File management subsystem](js-apidiff-file-management.md)
- [Location subsystem](js-apidiff-geolocation.md)
- [Globalization subsystem](js-apidiff-global.md)
- [Misc services subsystem](js-apidiff-misc.md)
- [MSDP subsystem](js-apidiff-msdp.md)
- [Multimodal input subsystem](js-apidiff-multi-modal-input.md)
- [Multimedia subsystem](js-apidiff-multimedia.md)
- [Common event and notification subsystem](js-apidiff-notification.md)
- [Resource scheduler subsystem](js-apidiff-resource-scheduler.md)
- [Security subsystem](js-apidiff-security.md)
- [Pan-sensor subsystem](js-apidiff-sensor.md)
- [Startup subsystem](js-apidiff-start-up.md)
- [Telephony subsystem](js-apidiff-telephony.md)
- [Test subsystem](js-apidiff-unitest.md)
- [Update subsystem](js-apidiff-update.md)
- [USB subsystem](js-apidiff-usb.md)
- [User IAM subsystem](js-apidiff-user-iam.md)
- [Web subsystem](js-apidiff-web.md)
- [Window manager subsystem](js-apidiff-window.md)
\ No newline at end of file
# JS API Differences
- [Ability framework](js-apidiff-ability.md)
- [Account subsystem](js-apidiff-account.md)
- [Application subsystem](js-apidiff-application.md)
- [ArkUI development framework](js-apidiff-arkui.md)
- [Power management subsystem](js-apidiff-battery.md)
- [Bundle management framework](js-apidiff-bundle.md)
- [Communication subsystem](js-apidiff-communication.md)
- [Compiler and runtime subsystem](js-apidiff-compiler-and-runtime.md)
- [Distributed data management subsystem](js-apidiff-distributed-data.md)
- [File management subsystem](js-apidiff-file-management.md)
- [Location subsystem](js-apidiff-geolocation.md)
- [Globalization subsystem](js-apidiff-global.md)
- [Misc services subsystem](js-apidiff-misc.md)
- [Multimedia subsystem](js-apidiff-multimedia.md)
- [Common event and notification subsystem](js-apidiff-notification.md)
- [Resource scheduler subsystem](js-apidiff-resource-scheduler.md)
- [Security subsystem](js-apidiff-security.md)
- [Startup subsystem](js-apidiff-start-up.md)
- [Telephony subsystem](js-apidiff-telephony.md)
- [Test subsystem](js-apidiff-unitest.md)
- [User IAM subsystem](js-apidiff-user-iam.md)
- [Web subsystem](js-apidiff-web.md)
- [Window manager subsystem](js-apidiff-window.md)
\ No newline at end of file
......@@ -11,7 +11,7 @@ ExtensionAbility组件是基于特定场景(例如服务卡片、输入法等
- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md):WORK_SCHEDULER类型的ExtensionAbility组件,用于提供延迟任务回调实现的能力。
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md):INPUT_METHOD类型的ExtensionAbility组件,提供对输入法框架的管理,包括隐藏输入法、查询已安装的输入法列表和显示输入法选择对话框
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md):INPUT_METHOD类型的ExtensionAbility组件,用于开发输入法应用
- [ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md):SERVICE类型的ExtensionAbility组件,用于提供后台服务场景相关能力。
......
# InputMethodExtensionAbility开发指南
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)是inputMethod类型的ExtensionAbility组件,提供输入法框架服务相关扩展能力。
## 使用场景
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)基于[ExtensionAbility](extensionability-overview.md)框架,用于开发输入法应用。
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)可以被其他组件启动或连接,并根据调用者的请求信息在后台处理相关事务
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)实例及其所在的ExtensionAbility进程的整个生命周期,都是由输入法框架进行调度管理。输入法框架提供了[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)基类,开发者需要派生此基类,以实现输入法应用生命周期开始和销毁时的相关初始化操作和资源清理工作等
InputMethodExtensionAbility通过[InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md)提供相关能力。
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md)通过[InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md)提供相关能力。
## 实现一个输入法应用
......@@ -66,8 +66,8 @@ InputMethodExtensionAbility通过[InputMethodExtensionContext](../reference/apis
}
onDestroy() {
console.info("onDestroy.");
this.context.destroy();
console.log("onDestroy.");
this.keyboardController.onDestroy(); // 销毁窗口并去注册事件监听
}
}
```
......@@ -103,10 +103,9 @@ InputMethodExtensionAbility通过[InputMethodExtensionContext](../reference/apis
public onDestroy(): void // 应用生命周期销毁
{
this.unRegisterListener(); // 注销事件监听
this.unRegisterListener(); // 去注册事件监听
let win = windowManager.findWindow(this.windowName);
win.destroyWindow(); // 销毁窗口
this.mContext.terminateSelf(); // 销毁InputMethodExtensionAbility服务
}
private initWindow(): void // 初始化窗口
......@@ -156,7 +155,7 @@ InputMethodExtensionAbility通过[InputMethodExtensionContext](../reference/apis
})
globalThis.inputAbility.on('inputStop', (imeId) => {
if (imeId == "包名/Ability名") {
this.onDestroy();
this.mContext.destroy(); // 销毁InputMethodExtensionAbility服务
}
});
}
......@@ -230,7 +229,7 @@ InputMethodExtensionAbility通过[InputMethodExtensionContext](../reference/apis
同时在resources/base/profile/main_pages.json文件的src字段中添加此文件路径。
```ts
```ets
import { numberSourceListData, sourceListType } from './keyboardKeyData'
@Component
......
# 线程模型
OpenHarmony应用中每个进程都会有一个主线程,主线程有如下职责:
在OpenHarmony应用中,每个进程都会有一个主线程,主线程具有以下职责:
1. 管理其他线程,包括Worker线程。
2. 与应用中多个UIAbility组件共用一个主线程。
3. 分发输入事件。
4. 执行UI绘制。
5. 处理应用代码的回调,包括事件处理和生命周期管理。
6. 接收Worker发送的消息。
1. 执行UI绘制;
2. 管理主线程的ArkTS引擎实例,使多个UIAbility组件能够运行在其之上;
3. 管理其他线程(例如Worker线程)的ArkTS引擎实例,例如启动和终止其他线程;
4. 分发交互事件;
5. 处理应用代码的回调,包括事件处理和生命周期管理;
6. 接收Worker线程发送的消息;
除了主线程外,还有一类独立的Worker线程,用于执行耗时操作。Worker线程在主线程中创建,与主线程相互独立,但不能直接操作UI。最多可以创建7个Worker线程。
![thread-model-stage](figures/thread-model-stage.png)
......@@ -20,4 +17,4 @@ OpenHarmony应用中每个进程都会有一个主线程,主线程有如下职
> **说明:**
>
> - Stage模型只提供了主线程和Worker线程,Emitter主要用于主线程内或者主线程和Worker线程的事件同步。
> - 执行`hdc shell`命令,进入设备的shell命令行。在shell命令行中,执行`ps -p <pid> -T`命令,可以查看指定应用进程的线程信息。其中,`<pid>`为需要指定的应用进程的进程ID。
\ No newline at end of file
> - 执行`hdc shell`命令,进入设备的shell命令行。在shell命令行中,执行`ps -p <pid> -T`命令,可以查看指定应用进程的线程信息。其中,`<pid>`为需要指定的应用进程的进程ID。
......@@ -7,37 +7,37 @@
在许多应用场景中都需要用到数据共享,比如将电话簿、短信、媒体库中的数据共享给其他应用等。当然,不是所有的数据都允许其他应用访问,比如帐号、密码等;有些数据也只允许其他应用查询而不允许其删改,比如短信等。所以对于各种数据共享场景,DataShare这样一个安全、便捷的可以跨应用的数据共享机制是十分必要的。
数据提供者无需进行繁琐的封装,可直接使用DataShare向其他应用共享数据;对数据访问方来说,因DataShare的访问方式不会因数据提供的方式而不同,只需要学习和使用一套接口即可,大大减少了学习时间和开发难度。
## 基本概念
跨应用数据共享有两种方式:
在进行同设备跨应用数据共享开发前,先了解以下相关概念。
- **使用DataShareExtensionAbility实现数据共享**
- **数据提供方**:提供数据及实现相关业务的应用程序,也称为生产者或服务端。
这种方式通过在HAP中实现一个extension,在extension中可以实现回调,在访问方调用对应接口时,会自动拉起提供方对应的extension,并调用对应回调
- **数据访问方**:访问数据提供方所提供的数据或业务的应用程序,也称为消费者或客户端
这种方式适用于跨应用数据访问时有业务的操作,不仅是对数据库的增删改查的情况
- **数据集**:用户要插入的数据集合,可以是一条或多条数据。数据集以键值对的形式存在,键为字符串类型,值支持数字、字符串、布尔值、无符号整型数组等多种数据类型
- **通过静默访问实现数据共享**
- **结果集**:用户查询之后的结果集合,其提供了灵活的数据访问方式,以便用户获取各项数据。
这种方式通过在HAP中配置数据库的访问规则,在访问方调用对应接口时,会自动通过系统服务读取HAP配置规则,按照规则返回数据,不会拉起数据提供方
- **谓词**:用户访问数据库中的数据所使用的筛选条件,经常被应用在更新数据、删除数据和查询数据等场景
这种方式适用于跨应用数据访问仅为数据库的增删改查,没有特殊业务的情况。
## 具体实现
数据提供方无需进行繁琐的封装,可直接使用DataShare向其他应用共享数据;对数据访问方来说,因DataShare的访问方式不会因数据提供的方式而不同,只需要学习和使用一套接口即可,大大减少了学习时间和开发难度。
## 基本概念
在进行同设备跨应用数据共享开发前,先了解以下相关概念。
跨应用数据共享有两种方式:
- **数据提供方**:提供数据及实现相关业务的应用程序,也称为生产者或服务端。
- **使用DataShareExtensionAbility实现数据共享**
- **数据访问方**:访问数据提供方所提供的数据或业务的应用程序,也称为消费者或客户端
这种方式通过在HAP中实现一个extension,在extension中可以实现回调,在访问方调用对应接口时,会自动拉起提供方对应的extension,并调用对应回调
- **数据集**:用户要插入的数据集合,可以是一条或多条数据。数据集以键值对的形式存在,键为字符串类型,值支持数字、字符串、布尔值、无符号整型数组等多种数据类型
这种方式适用于跨应用数据访问时有业务的操作,不仅是对数据库的增删改查的情况
- **结果集**:用户查询之后的结果集合,其提供了灵活的数据访问方式,以便用户获取各项数据。
- **通过静默访问实现数据共享**
- **谓词**:用户访问数据库中的数据所使用的筛选条件,经常被应用在更新数据、删除数据和查询数据等场景
这种方式通过在HAP中配置数据库的访问规则,在访问方调用对应接口时,会自动通过系统服务读取HAP配置规则,按照规则返回数据,不会拉起数据提供方
这种方式适用于跨应用数据访问仅为数据库的增删改查,没有特殊业务的情况。
## 约束限制
......
......@@ -17,6 +17,7 @@
在设备/data/log/faultlog/faultlogger/下面,以appfreeze-开头的日志。
日志格文件名格式是appfreeze-应用包名-应用UID-秒级时间
![appfreeze_20230308145160](figures/appfreeze_20230308145160.png)
### 通过DevEco Studio获取日志
......@@ -24,6 +25,7 @@
DevEco Studio会收集设备的故障日志到FaultLog下面:
DevEco Studio会将包名和故障和时间都分类好显示
![appfreeze_20230308145161](figures/appfreeze_20230308145161.png)
......@@ -113,23 +115,32 @@ faultlogger对外提供了故障查询接口,可以查询各种故障信息,
| memory | 跟当前时间当前进程的内存使用情况 |
OpenStacktraceCatcher当前进程堆栈示例:
示例堆栈表面窗口通过IPC向下发送事件的时候没有调用下去,停留在IPC通信阶段
![appfreeze_20230310105869](figures/appfreeze_20230310105869.png)
BinderCatcher信息示例:
示例表面当前1561进程向685进程请求通信,等待了超过10s没有得到响应。
![appfreeze_20230310105868](figures/appfreeze_20230310105868.png)
PeerBinder Stacktrace信息示例:
示例展示对端卡死进程685的堆栈信息
![appfreeze_20230310105870](figures/appfreeze_20230310105870.png)
cpuusage信息示例:
整机CPU信息
![appfreeze_20230310105871](figures/appfreeze_20230310105871.png)
memory信息示例:
当前进程内存信息
![appfreeze_20230310105872](figures/appfreeze_20230310105872.png)
### 日志主干特异性信息(应用主线程卡死超时)
......
......@@ -10,6 +10,10 @@
- [应用及文件系统空间统计](app-fs-space-statistics.md)
- [向应用沙箱推送文件](send-file-to-app-sandbox.md)
- [应用文件分享](share-app-file.md)
- 应用数据备份恢复
- [应用数据备份恢复概述](app-file-backup-overview.md)
- [应用接入数据备份恢复](app-file-backup-extension.md)
- [应用触发数据备份/恢复(仅对系统应用开放)](app-file-backup.md)
- 用户文件
- [用户文件概述](user-file-overview.md)
- 选择与保存用户文件(FilePicker)
......
# 应用接入数据备份恢复
应用接入数据备份恢复需要通过BackupExtensionAbility实现。
BackupExtensionAbility,是[Stage模型](../../application-dev/application-models/stage-model-development-overview.md)中扩展组件[ExtensionAbility](../application-models/extensionability-overview.md)的派生类。开发者可以通过修改配置文件定制备份恢复框架的行为,包括是否允许备份恢复,备份哪些文件等。
## 约束与限制
- 当备份恢复时,所有待备份文件及目录的路径不得超过4095字节,否则将导致未定义行为。
- 当备份目录时,应用进程必须拥有读取该目录及其所有子目录的权限(DAC中的`r`),否则将导致备份失败。
- 当备份文件时,应用进程必须拥有搜索该文件所有祖父级目录的权限(DAC中的`x`),否则将导致备份失败。
## 开发步骤
1. 在应用配置文件`module.json5`中注册`extensionAbilities`相关配置
新增`"extensionAbilities"`字段,其中注册类型`"type"`设置为`"backup"`,元数据信息["metadata"](../../application-dev/reference/apis/js-apis-bundleManager-metadata.md)新增一个`"name"``"ohos. extension. backup"`的条目。
BackupExtensionAbility配置文件示例:
```json
{
"extensionAbilities": [
{
"description": "$string:ServiceExtAbility",
"icon": "$media:icon",
"name": "BackupExtensionAbility",
"type": "backup",
"visible": true,
"metadata": [
{
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
],
"srcEntrance": "",
}
]
}
```
2. 新增元数据资源配置文件
在元数据资源配置文件中,定义备份恢复时需要传输的文件。元数据资源配置文件名称需要与`module.json5``"metadata.resource"`名称保持一致,其保存位置在Profile文件夹下。
元数据资源配置文件示例:
```json
{
"allowToBackupRestore": true,
"includes": [
"/data/storage/el2/base/files/users/*/*.json"
],
"excludes": [
"/data/storage/el2/base/files/users/*/hidden.json"
],
}
```
### 元数据资源配置文件说明
| 属性名称 | 数据类型 | 必填 | 含义 |
| -------------------- | ---------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| allowToBackupRestore | 布尔值 | 是 | 是否允许备份恢复,默认为false |
| includes | 字符串数组 | 否 | 应用沙箱中需要备份的文件和目录。<br>数组中的每一项均为模式串,可包含SHELL风格通配符(`*``?``[`)。<br>当模式串以非/开始时,表示一个相对于根路径的相对路径。<br>`includes`已配置时,备份恢复框架会采用开发者配置的模式串,否则将会采用下述代码段内容作为默认值。 |
| excludes | 字符串数组 | 否 | `includes`中无需备份的例外项。格式同`includes`<br>`excludes`已配置时,备份恢复框架会采用开发者配置的模式串,否则将会采用**空数组**作为默认值。 |
**includes默认值:**
```json
{
"includes": [
"data/storage/el2/database/",
"data/storage/el2/base/files/",
"data/storage/el2/base/preferences/",
"data/storage/el2/base/haps/*/database/",
"data/storage/el2/base/haps/*/base/files/",
"data/storage/el2/base/haps/*/base/preferences/",
]
}
```
# 应用数据备份恢复概述
用户在使用应用的过程中,会产生对应的应用数据,如配置信息、业务数据等。为了保证用户数据不会因为应用升级、迁移等操作而丢失,应用需要接入数据备份恢复。
在开发前,需要先了解ExtensionAbility组件,建议参考[ExtensionAbility组件概述](../application-models/extensionability-overview.md)
BackupExtensionAbility是Stage模型中扩展组件ExtensionAbility的派生类,用于提供备份及恢复应用数据的能力。它是一种无界面的扩展组件,随着备份恢复任务的启动而运行,随着备份恢复任务的结束而退出。
不同应用所需实现的场景不同,分为:
- [应用接入数据备份恢复](app-file-backup-extension.md):应用均可以接入数据备份恢复,在接入后,应用可通过修改配置文件定制备份恢复框架的行为,包括是否允许备份恢复、备份哪些数据。
应用本身无法触发数据的备份和恢复,仅能进行备份恢复的配置。
- [应用触发数据备份恢复(仅对系统应用开放)](app-file-backup.md):仅系统应用可以触发数据备份恢复,触发后备份恢复框架会确认各个应用是否接入了数据备份恢复。如果应用已接入,备份恢复框架将会根据应用的配置文件备份、恢复数据。
\ No newline at end of file
# 应用触发数据备份/恢复(仅对系统应用开放)
备份恢复是为设备上应用数据、公共数据和系统服务提供的完整的数据备份和恢复解决方案。系统应用开发者可以根据需求,按下述指导开发应用,以触发备份/恢复数据。
- [获取能力文件](#获取能力文件):获取当前系统用户内所有应用与备份恢复相关基础信息的能力文件。能力文件在应用备份/恢复数据时不可缺少。
- [应用备份数据](#应用备份数据):根据能力文件提供的应用信息,选择需要备份的应用数据并进行备份。
- [应用恢复数据](#应用恢复数据):根据能力文件提供的应用信息,选择需要恢复的应用数据并进行恢复。
- [应用恢复数据时安装应用](#应用恢复数据时安装应用):应用恢复数据的拓展功能,当用于恢复数据的应用未安装时,建议使用此功能,设备将先安装应用再恢复数据。
## 开发说明
备份恢复API的使用指导请参见[API参考](../reference/apis/js-apis-file-backup.md)
在使用备份恢复接口之前,需要:
1. [申请相关权限](../security/accesstoken-guidelines.md)`ohos.permission.BACKUP`
2. 导入依赖模块:`@ohos.file.backup`
```js
import backup from '@ohos.file.backup';
```
## 获取能力文件
获取当前系统用户内所有应用与备份恢复相关基础信息的能力文件。能力文件在应用备份恢复数据时是不可缺少的,开发者可以根据需要获取能力文件。
该文件包含设备类型、设备版本、应用的基础性信息,如应用名称、应用数据大小、应用版本信息、是否支持备份恢复、是否在恢复时安装应用。
调用`backup.getLocalCapabilities()`获取能力文件。
```js
import fs from '@ohos.file.fs';
try {
let fileData = await backup.getLocalCapabilities();
console.info('getLocalCapabilities success');
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
fs.copyFileSync(fileData.fd, fpath);
fs.closeSync(fileData.fd);
} catch (err) {
console.error('getLocalCapabilities failed with err: ' + err);
}
```
**返回的能力文件内容示例:**
| 属性名称 | 数据类型 | 必填 | 含义 |
| -------------- | -------- | ---- | ---------------------- |
| bundleInfos | 数组 | 是 | 应用信息列表 |
| allToBackup | 布尔值 | 是 | 是否允许备份恢复 |
| extensionName | 字符串 | 是 | 应用的扩展名 |
| name | 字符串 | 是 | 应用的包名 |
| needToInstall | 布尔值 | 是 | 应用恢复时是否需要安装 |
| spaceOccupied | 数值 | 是 | 应用数据占用的空间大小 |
| versionCode | 数值 | 是 | 应用的版本号 |
| versionName | 字符串 | 是 | 应用的版本名称 |
| deviceType | 字符串 | 是 | 设备类型 |
| systemFullName | 字符串 | 是 | 设备版本 |
```json
{
"bundleInfos" :[{
"allToBackup" : true,
"extensionName" : "BackupExtensionAbility",
"name" : "com.example.hiworld",
"needToInstall" : false,
"spaceOccupied" : 0,
"versionCode" : 1000000,
"versionName" : "1.0.0"
}],
"deviceType" : "default",
"systemFullName" : "OpenHarmony-4.0.0.0"
}
```
## 应用备份数据
开发者可以根据能力文件提供的应用信息,选择需要备份的应用数据。
备份过程中,备份恢复服务会将应用的数据打包成文件,打包后的文件会以打开的文件句柄形式,通过创建实例时所注册的回调[onFileReady](../reference/apis/js-apis-file-backup.md#onfileready)接口返回。
开发者可以根据需要将文件内容保存到本地。
**示例**
```ts
import fs from '@ohos.file.fs';
// 创建SessionBackup类的实例用于备份数据
let session = new backup.SessionBackup({
onFileReady: async (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
try {
let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName;
if (!fs.accessSync(bundlePath)) {
fs.mkdirSync(bundlePath);
}
fs.copyFileSync(file.fd, bundlePath + `/${file.uri}`);
fs.closeSync(file.fd);
console.info('onFileReady success');
} catch (e) {
console.error('onFileReady failed with err: ' + e);
}
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.info('onBundleBegin err: ' + err);
} else {
console.info('onBundleBegin bundleName: ' + bundleName);
}
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.info('onBundleEnd err: ' + err);
} else {
console.info('onBundleEnd bundleName: ' + bundleName);
}
},
onAllBundlesEnd: (err) => {
if (err) {
console.info('onAllBundlesEnd err: ' + err);
} else {
console.info('onAllBundlesEnd');
}
},
onBackupServiceDied: () => {
console.info('onBackupServiceDied');
},
});
// 此处可根据backup.getLocalCapabilities()提供的能力文件,选择需要备份的应用
// 也可直接根据应用包名称进行备份
const backupApps = [
"com.example.hiworld",
]
await session.appendBundles(backupApps);
console.info('appendBundles success');
```
## 应用恢复数据
开发者可以根据能力文件提供的应用信息,选择需要恢复的应用数据。
恢复过程中,备份恢复服务会根据开发者调用[getFileHandle](../reference/apis/js-apis-file-backup.md#getfilehandle)的请求内容,将应用待恢复数据的文件句柄,通过创建实例时注册的回调[onFileReady](../reference/apis/js-apis-file-backup.md#onfileready)接口返回。可以根据返回的[uri](../reference/apis/js-apis-file-backup.md#filemeta)将应用对应的待恢复数据写入到文件句柄中。写入完成后开发者调用[publishFile](../reference/apis/js-apis-file-backup.md#publishfile)通知服务写入完成。
待应用所有恢复数据准备就绪后,服务开始恢复应用数据。
**示例**
```ts
import fs from '@ohos.file.fs';
// 创建SessionRestore类的实例用于恢复数据
let session = new backup.SessionRestore({
onFileReady: async (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
try {
let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName + '/'+ file.uri;
if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath);
}
fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd);
// 恢复数据传输完成后,会通知服务端文件准备就绪
await session.publishFile({
bundleName: file.bundleName,
uri: file.uri,
});
console.info('onFileReady success');
} catch (e) {
console.error('onFileReady failed with err: ' + e);
}
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.info('onBundleBegin err: ' + err);
} else {
console.info('onBundleBegin bundleName: ' + bundleName);
}
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.info('onBundleEnd err: ' + err);
} else {
console.info('onBundleEnd bundleName: ' + bundleName);
}
},
onAllBundlesEnd: (err) => {
if (err) {
console.info('onAllBundlesEnd err: ' + err);
} else {
console.info('onAllBundlesEnd');
}
},
onBackupServiceDied: () => {
console.info('onBackupServiceDied');
},
});
const backupApps = [
"com.example.hiworld",
]
// 能力文件的获取方式可以根据开发者实际场景进行调整。此处仅为请求示例
// 开发者也可以根据能力文件内容的结构示例,自行构造能力文件内容
let fileData = await backup.getLocalCapabilities();
await session.appendBundles(fileData.fd, backupApps);
console.info('appendBundles success');
// 添加需要恢复的应用成功后,请根据需要恢复的应用名称,调用getFileHandle接口获取待恢复应用数文件的文件句柄
// 应用待恢复数据文件数请依据实际备份文件个数为准,此处仅为请求示例
await session.getFileHandle({
bundleName: restoreApps[0],
uri: "manage.json"
});
await session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
console.info('getFileHandle success');
```
## 应用恢复数据时安装应用
开发者在恢复数据时可以选择先安装应用后再进行恢复应用数据。与[应用恢复数据](#应用恢复数据)相比需要修改[能力文件](#获取能力文件)`bundleInfos`数组内的`needToInstall`字段修改为`true`
> **说明:**
> - [应用备份数据](#应用备份数据)不支持备份应用安装包,因此开发者需要自行准备应用安装包。
> - 开发者在调用[getFileHandle](../reference/apis/js-apis-file-backup.md#getfilehandle)时,传入固定的`FileMeta.uri`=`"/data/storage/el2/restore/bundle.hap"`,用于获取应用安装包的文件句柄。与应用恢复数据时一致,应用安装包的文件句柄,通过创建实例时注册的回调onFileReady接口返回给开发者,返回的`File.uri`=`"/data/storage/el2/restore/bundle.hap"`。
**示例**
```ts
import fs from '@ohos.file.fs';
// 创建SessionRestore类的实例用于恢复数据
let session = new backup.SessionRestore({
onFileReady: async (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
try {
let bundlePath;
if( file.uri == "/data/storage/el2/restore/bundle.hap" )
{
// 此处开发者请根据实际场景安装包的存放位置进行调整
} else {
bundlePath = await globalThis.context.filesDir + '/' + file.bundleName + '/'+ file.uri;
}
if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath);
}
fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd);
// 恢复数据传输完成后,会通知服务端文件准备就绪
await session.publishFile({
bundleName: file.bundleName,
uri: file.uri,
});
console.info('onFileReady success');
} catch (e) {
console.error('onFileReady failed with err: ' + e);
}
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.info('onBundleBegin err: ' + err);
} else {
console.info('onBundleBegin bundleName: ' + bundleName);
}
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.info('onBundleEnd err: ' + err);
} else {
console.info('onBundleEnd bundleName: ' + bundleName);
}
},
onAllBundlesEnd: (err) => {
if (err) {
console.info('onAllBundlesEnd err: ' + err);
} else {
console.info('onAllBundlesEnd');
}
},
onBackupServiceDied: () => {
console.info('onBackupServiceDied');
},
});
const backupApps = [
"com.example.hiworld",
]
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
let file = fs.openSync(fpath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE);
let content = "{\"bundleInfos\" :[{\"allToBackup\" : false,\"extensionName\" : \"\"," +
"\"name\" : \"cn.openharmony.inputmethodchoosedialog\",\"needToInstall\" : true,\"spaceOccupied\" : 0," +
"\"versionCode\" : 1000000,\"versionName\" : \"1.0.0\"}],\"deviceType\" : \"default\",\"systemFullName\" : \"OpenHarmony-4.0.6.2(Canary1)\"}";
fs.writeSync(file.fd, content);
fs.fsyncSync(file.fd);
await session.appendBundles(file.fd, backupApps);
console.info('appendBundles success');
// 开发者需要请求安装应用的文件句柄
await session.getFileHandle({
bundleName: restoreApps[0],
uri: "/data/storage/el2/restore/bundle.hap"
});
await session.getFileHandle({
bundleName: restoreApps[0],
uri: "manage.json"
});
await session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
console.info('getFileHandle success');
```
**恢复数据时安装应用所需的能力文件内容示例:**
```json
{
"bundleInfos" :[{
"allToBackup" : true,
"extensionName" : "BackupExtensionAbility",
"name" : "com.example.hiworld",
"needToInstall" : true,
"spaceOccupied" : 0,
"versionCode" : 1000000,
"versionName" : "1.0.0"
}],
"deviceType" : "default",
"systemFullName" : "OpenHarmony-4.0.0.0"
}
```
\ No newline at end of file
......@@ -14,7 +14,7 @@
音频打断策略预设了两种焦点模式([InterruptMode](../reference/apis/js-apis-audio.md#interruptmode9)):
- 共享焦点模式(SHARED_MODE):由同一应用创建的多个音频流,共享一个音频焦点。这些音频流之间的并发规则由应用自主决定,音频打断策略不会介入。当其他应用创建的音频流与该应用的音频流并发播放时,才会触发音频打断策略的管控。
- 共享焦点模式(SHARE_MODE):由同一应用创建的多个音频流,共享一个音频焦点。这些音频流之间的并发规则由应用自主决定,音频打断策略不会介入。当其他应用创建的音频流与该应用的音频流并发播放时,才会触发音频打断策略的管控。
- 独立焦点模式(INDEPENDENT_MODE):应用创建的每一个音频流均会独立拥有一个音频焦点,当多个音频流并发播放时,会触发音频打断策略的管控。
......
......@@ -59,6 +59,7 @@ AVPlayer提供功能完善一体化播放能力,应用只需要提供流媒体
| -------- | -------- |
| 本地点播 | 协议格式:支持file&nbsp;descriptor,禁止file&nbsp;path |
| 网络点播 | 协议格式:支持http/https/hls |
| 网络直播 | 协议格式:支持hls |
支持的音频播放格式如下:
......
......@@ -151,9 +151,6 @@ export default class AudioRendererDemo {
console.info(`${TAG}: creating AudioRenderer success`);
this.renderModel = renderer;
this.renderModel.on('stateChange', (state) => { // 设置监听事件,当转换到指定的状态时触发回调
if (state == 1) {
console.info('audio renderer state is: STATE_PREPARED');
}
if (state == 2) {
console.info('audio renderer state is: STATE_RUNNING');
}
......
......@@ -23,17 +23,17 @@
1. 创建实例createAVPlayer(),AVPlayer初始化idle状态。
2. 设置业务需要的监听事件,搭配全流程场景使用。支持的监听事件包括:
| 事件类型 | 说明 |
| 事件类型 | 说明 |
| -------- | -------- |
| stateChange | 必要事件,监听播放器的state属性改变。 |
| error | 必要事件,监听播放器的错误信息。 |
| durationUpdate | 用于进度条,监听进度条长度,刷新资源时长。 |
| timeUpdate | 用于进度条,监听进度条当前位置,刷新当前时间。 |
| seekDone | 响应API调用,监听seek()请求完成情况。<br/>当使用seek()跳转到指定播放位置后,如果seek操作成功,将上报该事件。 |
| speedDone | 响应API调用,监听setSpeed()请求完成情况。<br/>当使用setSpeed()设置播放倍速后,如果setSpeed操作成功,将上报该事件。 |
| volumeChange | 响应API调用,监听setVolume()请求完成情况。<br/>当使用setVolume()调节播放音量后,如果setVolume操作成功,将上报该事件。 |
| bufferingUpdate | 用于网络播放,监听网络播放缓冲信息,用于上报缓冲百分比以及缓存播放进度。 |
| audioInterrupt | 监听音频焦点切换信息,搭配属性audioInterruptMode使用。<br/>如果当前设备存在多个音频正在播放,音频焦点被切换(即播放其他媒体如通话等)时将上报该事件,应用可以及时处理。 |
| stateChange | 必要事件,监听播放器的state属性改变。 |
| error | 必要事件,监听播放器的错误信息。 |
| durationUpdate | 用于进度条,监听进度条长度,刷新资源时长。 |
| timeUpdate | 用于进度条,监听进度条当前位置,刷新当前时间。 |
| seekDone | 响应API调用,监听seek()请求完成情况。<br/>当使用seek()跳转到指定播放位置后,如果seek操作成功,将上报该事件。 |
| speedDone | 响应API调用,监听setSpeed()请求完成情况。<br/>当使用setSpeed()设置播放倍速后,如果setSpeed操作成功,将上报该事件。 |
| volumeChange | 响应API调用,监听setVolume()请求完成情况。<br/>当使用setVolume()调节播放音量后,如果setVolume操作成功,将上报该事件。 |
| bufferingUpdate | 用于网络播放,监听网络播放缓冲信息,用于上报缓冲百分比以及缓存播放进度。 |
| audioInterrupt | 监听音频焦点切换信息,搭配属性audioInterruptMode使用。<br/>如果当前设备存在多个音频正在播放,音频焦点被切换(即播放其他媒体如通话等)时将上报该事件,应用可以及时处理。 |
3. 设置资源:设置属性url,AVPlayer进入initialized状态。
> **说明:**
......@@ -59,7 +59,7 @@
## 完整示例
参考以下示例,完整地播放一首音乐。
```ts
import media from '@ohos.multimedia.media';
import fs from '@ohos.file.fs';
......@@ -68,7 +68,9 @@ import common from '@ohos.app.ability.common';
export class AVPlayerDemo {
private avPlayer;
private count: number = 0;
private isSeek: boolean = true; // 用于区分模式是否支持seek操作
private fileSize: number = -1;
private fd: number = 0;
// 注册avplayer回调函数
setAVPlayerCallback() {
// seek操作结果回调函数
......@@ -102,8 +104,13 @@ export class AVPlayerDemo {
case 'playing': // play成功调用后触发该状态机上报
console.info('AVPlayer state playing called.');
if (this.count !== 0) {
console.info('AVPlayer start to seek.');
this.avPlayer.seek(this.avPlayer.duration); //seek到音频末尾
if (this.isSeek === true) {
console.info('AVPlayer start to seek.');
this.avPlayer.seek(this.avPlayer.duration); //seek到音频末尾
} else {
// 当播放模式不支持seek操作时继续播放到结尾
console.info('AVPlayer wait to play end.');
}
} else {
this.avPlayer.pause(); // 调用暂停接口暂停播放
}
......@@ -145,6 +152,7 @@ export class AVPlayerDemo {
// 打开相应的资源文件地址获取fd,并为url赋值触发initialized状态机上报
let file = await fs.open(path);
fdPath = fdPath + '' + file.fd;
this.isSeek = true; // 支持seek操作
this.avPlayer.url = fdPath;
}
......@@ -158,8 +166,85 @@ export class AVPlayerDemo {
// 返回类型为{fd,offset,length},fd为HAP包fd地址,offset为媒体资源偏移量,length为播放长度
let context = getContext(this) as common.UIAbilityContext;
let fileDescriptor = await context.resourceManager.getRawFd('01.mp3');
this.isSeek = true; // 支持seek操作
// 为fdSrc赋值触发initialized状态机上报
this.avPlayer.fdSrc = fileDescriptor;
}
// 以下demo为使用fs文件系统打开沙箱地址获取媒体文件地址并通过dataSrc属性进行播放(seek模式)示例
async avPlayerDataSrcSeekDemo() {
// 创建avPlayer实例对象
this.avPlayer = await media.createAVPlayer();
// 创建状态机变化回调函数
this.setAVPlayerCallback();
// dataSrc播放模式的的播放源地址,当播放为Seek模式时fileSize为播放文件的具体大小,下面会对fileSize赋值
let src = {
fileSize: -1,
callback: (buf, length, pos) => {
let num = 0;
if (buf == undefined || length == undefined || pos == undefined) {
return -1;
}
num = fs.readSync(this.fd, buf, { offset: pos, length: length });
if (num > 0 && (this.fileSize >= pos)) {
return num;
}
return -1;
}
}
let context = getContext(this) as common.UIAbilityContext;
// 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
let pathDir = context.filesDir;
let path = pathDir + '/01.mp3';
await fs.open(path).then((file) => {
this.fd = file.fd;
})
// 获取播放文件的大小
this.fileSize = fs.statSync(path).size;
src.fileSize = this.fileSize;
this.isSeek = true; // 支持seek操作
this.avPlayer.dataSrc = src;
}
// 以下demo为使用fs文件系统打开沙箱地址获取媒体文件地址并通过dataSrc属性进行播放(No seek模式)示例
async avPlayerDataSrcNoSeekDemo() {
// 创建avPlayer实例对象
this.avPlayer = await media.createAVPlayer();
// 创建状态机变化回调函数
this.setAVPlayerCallback();
let context = getContext(this) as common.UIAbilityContext;
let src: object = {
fileSize: -1,
callback: (buf, length, pos) => {
let num = 0;
if (buf == undefined || length == undefined) {
return -1;
}
num = fs.readSync(this.fd, buf);
if (num > 0) {
return num;
}
return -1;
}
}
// 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
let pathDir = context.filesDir;
let path = pathDir + '/01.mp3';
await fs.open(path).then((file) => {
this.fd = file.fd;
})
this.isSeek = false; // 不支持seek操作
this.avPlayer.dataSrc = src;
}
// 以下demo为通过url设置网络地址来实现播放直播码流的demo
async avPlayerLiveDemo() {
// 创建avPlayer实例对象
this.avPlayer = await media.createAVPlayer();
// 创建状态机变化回调函数
this.setAVPlayerCallback();
this.isSeek = false; // 不支持seek操作
this.avPlayer.url = 'http://xxx.xxx.xxx.xxx:xx/xx/index.m3u8';
}
}
```
......@@ -25,21 +25,21 @@
1. 创建实例createAVPlayer(),AVPlayer初始化idle状态。
2. 设置业务需要的监听事件,搭配全流程场景使用。支持的监听事件包括:
| 事件类型 | 说明 |
| 事件类型 | 说明 |
| -------- | -------- |
| stateChange | 必要事件,监听播放器的state属性改变。 |
| error | 必要事件,监听播放器的错误信息。 |
| durationUpdate | 用于进度条,监听进度条长度,刷新资源时长。 |
| timeUpdate | 用于进度条,监听进度条当前位置,刷新当前时间。 |
| seekDone | 响应API调用,监听seek()请求完成情况。<br/>当使用seek()跳转到指定播放位置后,如果seek操作成功,将上报该事件。 |
| speedDone | 响应API调用,监听setSpeed()请求完成情况。<br/>当使用setSpeed()设置播放倍速后,如果setSpeed操作成功,将上报该事件。 |
| volumeChange | 响应API调用,监听setVolume()请求完成情况。<br/>当使用setVolume()调节播放音量后,如果setVolume操作成功,将上报该事件。 |
| bitrateDone | 响应API调用,用于HLS协议流,监听setBitrate()请求完成情况。<br/>当使用setBitrate()指定播放比特率后,如果setBitrate操作成功,将上报该事件。 |
| availableBitrates | 用于HLS协议流,监听HLS资源的可选bitrates,用于setBitrate()。 |
| bufferingUpdate | 用于网络播放,监听网络播放缓冲信息。 |
| startRenderFrame | 用于视频播放,监听视频播放首帧渲染时间。 |
| videoSizeChange | 用于视频播放,监听视频播放的宽高信息,可用于调整窗口大小、比例。 |
| audioInterrupt | 监听音频焦点切换信息,搭配属性audioInterruptMode使用。<br/>如果当前设备存在多个媒体正在播放,音频焦点被切换(即播放其他媒体如通话等)时将上报该事件,应用可以及时处理。 |
| stateChange | 必要事件,监听播放器的state属性改变。 |
| error | 必要事件,监听播放器的错误信息。 |
| durationUpdate | 用于进度条,监听进度条长度,刷新资源时长。 |
| timeUpdate | 用于进度条,监听进度条当前位置,刷新当前时间。 |
| seekDone | 响应API调用,监听seek()请求完成情况。<br/>当使用seek()跳转到指定播放位置后,如果seek操作成功,将上报该事件。 |
| speedDone | 响应API调用,监听setSpeed()请求完成情况。<br/>当使用setSpeed()设置播放倍速后,如果setSpeed操作成功,将上报该事件。 |
| volumeChange | 响应API调用,监听setVolume()请求完成情况。<br/>当使用setVolume()调节播放音量后,如果setVolume操作成功,将上报该事件。 |
| bitrateDone | 响应API调用,用于HLS协议流,监听setBitrate()请求完成情况。<br/>当使用setBitrate()指定播放比特率后,如果setBitrate操作成功,将上报该事件。 |
| availableBitrates | 用于HLS协议流,监听HLS资源的可选bitrates,用于setBitrate()。 |
| bufferingUpdate | 用于网络播放,监听网络播放缓冲信息。 |
| startRenderFrame | 用于视频播放,监听视频播放首帧渲染时间。 |
| videoSizeChange | 用于视频播放,监听视频播放的宽高信息,可用于调整窗口大小、比例。 |
| audioInterrupt | 监听音频焦点切换信息,搭配属性audioInterruptMode使用。<br/>如果当前设备存在多个媒体正在播放,音频焦点被切换(即播放其他媒体如通话等)时将上报该事件,应用可以及时处理。 |
3. 设置资源:设置属性url,AVPlayer进入initialized状态。
> **说明:**
......@@ -68,7 +68,7 @@
### 完整示例
```ts
import media from '@ohos.multimedia.media';
import fs from '@ohos.file.fs';
......@@ -78,7 +78,9 @@ export class AVPlayerDemo {
private avPlayer;
private count: number = 0;
private surfaceID: string; // surfaceID用于播放画面显示,具体的值需要通过Xcomponent接口获取,相关文档链接见上面Xcomponent创建方法
private isSeek: boolean = true; // 用于区分模式是否支持seek操作
private fileSize: number = -1;
private fd: number = 0;
// 注册avplayer回调函数
setAVPlayerCallback() {
// seek操作结果回调函数
......@@ -113,8 +115,13 @@ export class AVPlayerDemo {
case 'playing': // play成功调用后触发该状态机上报
console.info('AVPlayer state playing called.');
if (this.count !== 0) {
console.info('AVPlayer start to seek.');
this.avPlayer.seek(this.avPlayer.duration); //seek到视频末尾
if (this.isSeek === true) {
console.info('AVPlayer start to seek.');
this.avPlayer.seek(this.avPlayer.duration); //seek到视频末尾
} else {
// 当播放模式不支持seek操作时继续播放到结尾
console.info('AVPlayer wait to play end.');
}
} else {
this.avPlayer.pause(); // 调用暂停接口暂停播放
}
......@@ -152,10 +159,11 @@ export class AVPlayerDemo {
let context = getContext(this) as common.UIAbilityContext;
// 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
let pathDir = context.filesDir;
let path = pathDir + '/H264_AAC.mp4';
let path = pathDir + '/H264_AAC.mp4';
// 打开相应的资源文件地址获取fd,并为url赋值触发initialized状态机上报
let file = await fs.open(path);
fdPath = fdPath + '' + file.fd;
this.isSeek = true; // 支持seek操作
this.avPlayer.url = fdPath;
}
......@@ -169,8 +177,85 @@ export class AVPlayerDemo {
// 返回类型为{fd,offset,length},fd为HAP包fd地址,offset为媒体资源偏移量,length为播放长度
let context = getContext(this) as common.UIAbilityContext;
let fileDescriptor = await context.resourceManager.getRawFd('H264_AAC.mp4');
this.isSeek = true; // 支持seek操作
// 为fdSrc赋值触发initialized状态机上报
this.avPlayer.fdSrc = fileDescriptor;
}
// 以下demo为使用fs文件系统打开沙箱地址获取媒体文件地址并通过dataSrc属性进行播放(seek模式)示例
async avPlayerDataSrcSeekDemo() {
// 创建avPlayer实例对象
this.avPlayer = await media.createAVPlayer();
// 创建状态机变化回调函数
this.setAVPlayerCallback();
// dataSrc播放模式的的播放源地址,当播放为Seek模式时fileSize为播放文件的具体大小,下面会对fileSize赋值
let src = {
fileSize: -1,
callback: (buf, length, pos) => {
let num = 0;
if (buf == undefined || length == undefined || pos == undefined) {
return -1;
}
num = fs.readSync(this.fd, buf, { offset: pos, length: length });
if (num > 0 && (this.fileSize >= pos)) {
return num;
}
return -1;
}
}
let context = getContext(this) as common.UIAbilityContext;
// 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
let pathDir = context.filesDir;
let path = pathDir + '/H264_AAC.mp4';
await fs.open(path).then((file) => {
this.fd = file.fd;
})
// 获取播放文件的大小
this.fileSize = fs.statSync(path).size;
src.fileSize = this.fileSize;
this.isSeek = true; // 支持seek操作
this.avPlayer.dataSrc = src;
}
// 以下demo为使用fs文件系统打开沙箱地址获取媒体文件地址并通过dataSrc属性进行播放(No seek模式)示例
async avPlayerDataSrcNoSeekDemo() {
// 创建avPlayer实例对象
this.avPlayer = await media.createAVPlayer();
// 创建状态机变化回调函数
this.setAVPlayerCallback();
let context = getContext(this) as common.UIAbilityContext;
let src: object = {
fileSize: -1,
callback: (buf, length, pos) => {
let num = 0;
if (buf == undefined || length == undefined) {
return -1;
}
num = fs.readSync(this.fd, buf);
if (num > 0) {
return num;
}
return -1;
}
}
// 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
let pathDir = context.filesDir;
let path = pathDir + '/H264_AAC.mp4';
await fs.open(path).then((file) => {
this.fd = file.fd;
})
this.isSeek = false; // 不支持seek操作
this.avPlayer.dataSrc = src;
}
// 以下demo为通过url设置网络地址来实现播放直播码流的demo
async avPlayerLiveDemo() {
// 创建avPlayer实例对象
this.avPlayer = await media.createAVPlayer();
// 创建状态机变化回调函数
this.setAVPlayerCallback();
this.isSeek = false; // 不支持seek操作
this.avPlayer.url = 'http://xxx.xxx.xxx.xxx:xx/xx/index.m3u8'; // 播放hls网络直播码流
}
}
```
......@@ -18,7 +18,7 @@
<br>上图是OpenHarmony应用程序发布的快速修复的包格式
* 从图中可以看出包含两种包格式:
* appqf(Application Quick Fix)
<br> appqf与应用的app pack包是一一对应关系,具体可参考[应用程序包结构](application-package-structure-stage)的介绍。
<br> appqf与应用的app pack包是一一对应关系,具体可参考[应用程序包结构](application-package-structure-stage.md)的介绍。
* appqf包是OpenHarmony应用用于发布到应用市场的单元,不能够直接安装到设备上。
* 它是由一个或多个hqf(Harmony Ability Package Quick Fix)组成,这些hqf包在应用市场会从appqf包中拆分出来,再被分发到具体的设备上。
* appqf包上架到应用市场前要有开发者的签名信息。签名方式可可参考[Hap包签名工具](../security/hapsigntool-overview.md)的介绍。
......
......@@ -308,4 +308,43 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
return wantParams;
}
};
```
## onAcquireFormData<sup>10+</sup>
onAcquireFormData?(formId: string): { [key: string]: Object }
卡片提供方接收卡片请求自定义数据的通知接口。
**系统接口**: 此接口为系统接口。
**系统能力**:SystemCapability.Ability.Form
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| formId | string | 是 | 卡片标识。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------------------------------------ | ----------------------------------------------------------- |
| {[key: string]: any} | 卡片的自定义数据,由开发者自行决定传入的键值对。 |
**示例:**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormData(formId) {
console.log('FormExtensionAbility onAcquireFormData, formId: ${formId}');
let wantParams = {
'temperature': '20',
'time': '2022-8-8 09:59',
};
return wantParams;
}
};
```
\ No newline at end of file
......@@ -1865,3 +1865,95 @@ try {
}
```
## acquireFormData<sup>10+</sup>
acquireFormData(formId: string, callback: AsyncCallback\<void>): void
请求卡片提供方数据。使用callback异步回调。
**需要权限**:ohos.permission.REQUIRE_FORM
**系统能力**:SystemCapability.Ability.Form
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- |
| formId | string | 是 | 卡片标识。 |
**错误码:**
以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)
| 错误码ID | 错误信息 |
| -------- | -------- |
| 16500050 | An IPC connection error happened. |
| 16500060 | A service connection error happened, please try again later. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
**示例:**
```ts
import formHost from '@ohos.app.form.formHost';
let formId = '12400633174999288';
try {
formHost.acquireFormData(formId, (error) => {
if (error) {
console.error(`error, code: ${error.code}, message: ${error.message}`);
}
});
} catch(error) {
console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
## acquireFormData<sup>10+</sup>
function acquireFormData(formId: string): Promise\<void\>;
请求卡片提供方数据。使用Promise异步回调。
**需要权限**:ohos.permission.REQUIRE_FORM
**系统能力**:SystemCapability.Ability.Form
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | --------------- | ---- | -------------------------------- |
| formId | string | 是 | 卡片标识。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)
| 错误码ID | 错误信息 |
| -------- | -------- |
| 16500050 | An IPC connection error happened. |
| 16500060 | A service connection error happened, please try again later. |
| 16500100 | Failed to obtain the configuration information. |
| 16501000 | An internal functional error occurred. |
```ts
import formHost from '@ohos.app.form.formHost';
let formId = '12400633174999288';
try {
formHost.acquireFormData(formId).then(() => {
console.log('formHost acquireFormData success');
}).catch((error) => {
console.error(`error, code: ${error.code}, message: ${error.message}`);
});
} catch(error) {
console.error(`catch error, code: ${error.code}, message: ${error.message}`);
}
```
......@@ -102,6 +102,8 @@ import formInfo from '@ohos.app.form.formInfo';
| ABILITY_NAME_KEY | 'ohos.extra.param.key.ability_name' | ability名称。 |
| DEVICE_ID_KEY | 'ohos.extra.param.key.device_id' | 设备标识。 |
| BUNDLE_NAME_KEY | 'ohos.extra.param.key.bundle_name' | 指示指定要获取的捆绑Bundle名称的键。 |
| LAUNCH_REASON_KEY<sup>10+</sup> | 'ohos.extra.param.key.form_launch_reason' | 卡片创建原因。 |
| PARAM_FORM_CUSTOMIZE_KEY<sup>10+</sup> | 'ohos.extra.param.key.form_customize' | 自定义数据。 |
## FormDimension
......@@ -137,4 +139,15 @@ import formInfo from '@ohos.app.form.formInfo';
| 名称 | 值 | 说明 |
| ----------- | ---- | ------------ |
| FORM_VISIBLE | 1 | 表示卡片为可见。 |
| FORM_INVISIBLE | 2 | 表示卡片为不可见。 |
\ No newline at end of file
| FORM_INVISIBLE | 2 | 表示卡片为不可见。 |
## LaunchReason<sup>10+</sup>
卡片创建原因枚举。
**系统能力**:SystemCapability.Ability.Form
| 名称 | 值 | 说明 |
| ----------- | ---- | ------------ |
| FORM_DEFAULT | 1 | 表示卡片创建原因为默认创建。 |
| FORM_SHARE | 2 | 表示卡片创建原因为共享创建。 |
\ No newline at end of file
# @ohos.arkui.componentSnapshot(组件截图)
本模块提供获取组件截图的能力,包括已加载的组件的截图和没有加载的组件的截图。
> **说明:**
>
> 本模块首批接口从 API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> 示例效果请以真机运行为准,当前 IDE 预览器不支持。
## 导入模块
```js
import componentSnapshot from "@ohos.arkui.componentSnapshot";
```
## componentSnapshot.get
get(id: string, callback: AsyncCallback<image.PixelMap>): void
获取已加载的组件的截图,传入组件的[ID 标识](../arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | ---- | ------------------------------------------------------------------------------ |
| id | string | 是 | 目标组件的[ID 标识](../arkui-ts/ts-universal-attributes-component-id.md#组件标识) |
| callback | AsyncCallback&lt;image.PixelMap&gt; | 是 | 截图返回结果的回调。 |
**示例:**
```js
import componentSnapshot from '@ohos.arkui.componentSnapshot'
import image from '@ohos.multimedia.image'
@Entry
@Component
struct SnapshotExample {
@State pixmap: image.PixelMap = undefined
build() {
Column() {
Image(this.pixmap)
.width(300).height(300)
// ...Component
// ...Components
// ...Components
Button("click to generate UI snapshot")
.onClick(() => {
componentSnapshot.get("root", (error: BusinessError, pixmap: image.PixelMap) => {
this.pixmap = pixmap
// save pixmap to file
// ....
})
})
}
.width('80%')
.margin({ left: 10, top: 5, bottom: 5 })
.height(200)
.border({ color: '#880606', width: 2 })
.id("root")
}
}
```
## componentSnapshot.get
get(id: string): Promise<image.PixelMap>
获取已加载的组件的截图,传入组件的[ID 标识](../arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过Promise返回结果。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------- | ---- | -------------------- |
| id | string | 是 | 目标组件的[ID 标识](../arkui-ts/ts-universal-attributes-component-id.md#组件标识) |
**返回值:**
| 类型 | 说明 |
| ----------------------------- | -------------- |
| Promise&lt;image.PixelMap&gt; | 截图返回的结果。 |
**示例:**
```js
import componentSnapshot from '@ohos.arkui.componentSnapshot'
import image from '@ohos.multimedia.image'
@Entry
@Component
struct SnapshotExample {
@State pixmap: image.PixelMap = undefined
build() {
Column() {
Image(this.pixmap)
.width(300).height(300)
// ...Component
// ...Components
// ...Components
Button("click to generate UI snapshot")
.onClick(() => {
componentSnapshot.get("root")
.then((pixmap: image.PixelMap) => {
this.pixmap = pixmap
// save pixmap to file
// ....
})
})
}
.width('80%')
.margin({ left: 10, top: 5, bottom: 5 })
.height(200)
.border({ color: '#880606', width: 2 })
.id("root")
}
}
```
## componentSnapshot.createFromBuilder
createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>): void
在应用后台渲染CustomBuilder自定义组件,并输出其截图。通过回调返回结果。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------- | ---- | -------------------- |
| builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | 是 | 自定义组件构建函数。 |
| callback | AsyncCallback&lt;image.PixelMap&gt; | 是 | 截图返回结果的回调。 |
**示例:**
```js
import componentSnapshot from '@ohos.arkui.componentSnapshot'
import image from '@ohos.multimedia.image'
@Entry
@Component
struct OffscreenSnapshotExample {
@State pixmap: image.PixelMap = undefined
@Builder
RandomBuilder() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text('Test menu item 1')
.fontSize(20)
.width(100)
.height(50)
.textAlign(TextAlign.Center)
Divider().height(10)
Text('Test menu item 2')
.fontSize(20)
.width(100)
.height(50)
.textAlign(TextAlign.Center)
}.width(100)
}
build() {
Column() {
Button("click to generate offscreen UI snapshot")
.onClick(()=> {
componentSnapshot.createFromBuilder(this.RandomBuilder.bind(this),
(error: BusinessError, pixmap: image.PixelMap) => {
this.pixmap = pixmap
// save pixmap to file
// ....
})
})
}.width('80%').margin({ left: 10, top: 5, bottom: 5 }).height(200)
.border({ color: '#880606', width: 2 })
}
}
```
## componentSnapshot.createFromBuilder
createFromBuilder(builder: CustomBuilder): Promise<image.PixelMap>
在应用后台渲染CustomBuilder自定义组件,并输出其截图。通过Promise返回结果。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------- | ---- | -------------------- |
| builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | 是 | 自定义组件构建函数。 |
**返回值:**
| 类型 | 说明 |
| ----------------------------- | -------------- |
| Promise&lt;image.PixelMap&gt; | 截图返回的结果。 |
**示例:**
```js
import componentSnapshot from '@ohos.arkui.componentSnapshot'
import image from '@ohos.multimedia.image'
@Entry
@Component
struct OffscreenSnapshotExample {
@State pixmap: image.PixelMap = undefined
@Builder
RandomBuilder() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text('Test menu item 1')
.fontSize(20)
.width(100)
.height(50)
.textAlign(TextAlign.Center)
Divider().height(10)
Text('Test menu item 2')
.fontSize(20)
.width(100)
.height(50)
.textAlign(TextAlign.Center)
}.width(100)
}
build() {
Column() {
Button("click to generate offscreen UI snapshot")
.onClick(()=> {
componentSnapshot.createFromBuilder(this.RandomBuilder.bind(this))
.then((pixmap: image.PixelMap) {
this.pixmap = pixmap
// save pixmap to file
// ....
})
})
}.width('80%').margin({ left: 10, top: 5, bottom: 5 }).height(200)
.border({ color: '#880606', width: 2 })
}
}
```
......@@ -4172,6 +4172,7 @@ audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) =>
| sampleRates<sup>9+</sup> | Array&lt;number&gt; | 是 | 否 | 支持的采样率。 |
| channelCounts<sup>9+</sup> | Array&lt;number&gt; | 是 | 否 | 支持的通道数。 |
| channelMasks<sup>9+</sup> | Array&lt;number&gt; | 是 | 否 | 支持的通道掩码。 |
| displayName<sup>10+</sup> | string | 是 | 否 | 设备显示名。 |
| networkId<sup>9+</sup> | string | 是 | 否 | 设备组网的ID。<br/>此接口为系统接口。 |
| interruptGroupId<sup>9+</sup> | number | 是 | 否 | 设备所处的焦点组ID。<br/>此接口为系统接口。 |
| volumeGroupId<sup>9+</sup> | number | 是 | 否 | 设备所处的音量组ID。<br/>此接口为系统接口。 |
......
......@@ -2657,7 +2657,7 @@ writeUInt16BE(value: number, offset?: number): number
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | number | 是 | 写入Buffer的数据。 |
| offset | number | 否 | 偏移量。 默认值: 0。 |
| offset | number | 否 | 偏移量。 默认值0。 |
**返回值:**
......@@ -2906,7 +2906,7 @@ Blob的构造函数。
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| sources | string[]&nbsp;\|&nbsp;ArrayBuffer[]&nbsp;\|&nbsp;TypedArray[]&nbsp;\|&nbsp;DataView[]&nbsp;\|&nbsp;Blob[] | 是 | Blob实例的数据源。 |
| options | Object | 否 | options:<br/>-&nbsp;endings:'transparent'或'native'<br/>-&nbsp;type:Blob内容类型 |
| options | Object | 否 | options:<br/>- endings:含义为结束符'\n'的字符串如何被输出,为'transparent'或'native'。native代表行结束符会跟随系统。'transparent'代表会保持Blob中保存的结束符不变。此参数非必填,默认值为'transparent'。<br/>- type:Blob内容类型。其目的是让类型传达数据的MIME媒体类型,但是不执行类型格式的验证。此参数非必填,默认参数为''。 |
**示例:**
......@@ -2951,9 +2951,9 @@ slice(start?: number, end?: number, type?: string): Blob
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| start | number | 否 | 起始位置。 |
| end | number | 否 | 结束位置。 |
| type | string | 否 | 内容类型。 |
| start | number | 否 | 起始位置。默认值为0。 |
| end | number | 否 | 结束位置。默认值为原Blob对象中的数据长度。 |
| type | string | 否 | 内容类型。默认值为''。 |
**返回值:**
| 类型 | 说明 |
......
......@@ -3,8 +3,8 @@
该模块向云空间提供通知或更改端云服务状态的能力。
> **说明:**
> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块接口为系统接口,三方应用不支持调用。
> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块接口为系统接口,三方应用不支持调用。
## 导入模块
......
# @ohos.file.picker (选择器)
> **说明:**
> 该模块接口从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
>
> 该模块接口从API version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
选择器(Picker)是一个封装PhotoViewPicker、DocumentViewPicker、AudioViewPicker等系统应用选择与保存能力的模块。应用可以自行选择使用哪种picker实现文件选择和文件保存的功能。
......
......@@ -667,6 +667,8 @@ getUserStorageStats(callback: AsyncCallback&lt;StorageStats&gt;): void
});
```
## storageStatistics.getUserStorageStats<sup>9+</sup>
getUserStorageStats(userId: number): Promise&lt;StorageStats&gt;
异步获取指定用户各类别存储空间大小(单位为Byte),以promise方式返回。
......
......@@ -811,7 +811,7 @@ httpRequest.off('dataProgress');
| 名称 | 类型 | 必填 | 说明 |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| method | [RequestMethod](#requestmethod) | 否 | 请求方式,默认为GET。 |
| extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | 否 | 发送请求的额外数据,默认无此字段。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content,以UTF-8编码形式作为请求体。<sup>6+</sup><br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送;ArrayBuffer类型的参数不会做拼接处理。<sup>6+</sup> |
| extraData | string<sup>6+</sup> \| Object<sup>6+</sup> \| ArrayBuffer<sup>8+</sup> | 否 | 发送请求的额外数据,默认无此字段。<br />- 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content,以UTF-8编码形式作为请求体。当'Content-Type'为'application/x-www-form-urlencoded'时,请求提交的信息主体数据应在key和value进行URL转码后按照键值对"key1=value1&key2=value2&key3=value3"的方式进行编码。<sup>6+</sup><br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送;ArrayBuffer类型的参数不会做拼接处理。<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型,默认无此字段。如果设置了此参数,系统将优先返回指定的类型。 |
| usingCache<sup>9+</sup> | boolean | 否 | 是否使用缓存,默认为true。 |
| priority<sup>9+</sup> | number | 否 | 优先级,范围[1,1000],默认是1。 |
......
......@@ -362,12 +362,12 @@ Audio/Video播放demo可参考:[音频播放开发指导](../../media/using-av
| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | 是 | 是 | 媒体文件描述,只允许在**idle**状态下设置,静态属性。<br/>使用场景:应用中的媒体资源被连续存储在同一个文件中。<br/>支持的视频格式(mp4、mpeg-ts、webm、mkv)。<br>支持的音频格式(m4a、aac、mp3、ogg、wav)。<br/>**使用示例**<br/>假设一个连续存储的媒体文件: <br/>视频1(地址偏移:0,字节长度:100);<br/>视频2(地址偏移:101,字节长度:50);<br/>视频3(地址偏移:151,字节长度:150);<br/>1. 播放视频1:AVFileDescriptor { fd = 资源句柄; offset = 0; length = 100; }。<br/>2. 播放视频2:AVFileDescriptor { fd = 资源句柄; offset = 101; length = 50; }。<br/>3. 播放视频3:AVFileDescriptor { fd = 资源句柄; offset = 151; length = 150; }。<br/>假设是一个独立的媒体文件: 请使用src=fd://xx。 |
| dataSrc<sup>10+</sup> | [AVDataSrcDescriptor](#avdatasrcdescriptor10) | 是 | 是 | 流式媒体资源描述,只允许在**idle**状态下设置,静态属性。<br/>使用场景:应用播放从远端下载到本地的文件,在应用未下载完整音视频资源时,提前播放已获取的资源文件。<br/>支持的视频格式(mp4、mpeg-ts、webm、mkv)。<br>支持的音频格式(m4a、aac、mp3、ogg、wav)。<br/>**使用示例**<br/>假设用户正在从远端服务器获取音视频媒体文件,希望下载到本地的同时播放已经下载好的部分: <br/>1.用户需要获取媒体文件的总大小size(单位为字节),获取不到时设置为-1。<br/>2.用户需要实现回调函数func用于填写数据,如果size = -1,则func形式为:func(buffer: ArrayBuffer, length: number),此时播放器只会按照顺序获取数据;否则func形式为:func(buffer: ArrayBuffer, length: number, pos: number),播放器会按需跳转并获取数据。<br/>3.用户设置AVDataSrcDescriptor {fileSize = size, callback = func}。<br/>**注意事项**<br/>如果播放的是mp4/m4a格式用户需要保证moov字段(媒体信息字段)在mdat字段(媒体数据字段)之前,或者moov之前的字段小于10M,否则会导致解析失败无法播放。 |
| surfaceId<sup>9+</sup> | string | 是 | 是 | 视频窗口ID,默认无窗口,只允许在**initialized**状态下设置,静态属性。<br/>使用场景:视频播放的窗口渲染,纯音频播放不用设置。<br/>**使用示例**<br/>[通过Xcomponent创建surfaceId](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid)。 |
| loop<sup>9+</sup> | boolean | 是 | 是 | 视频循环播放属性,默认'false',设置为'true'表示循环播放,动态属性。<br/>只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 |
| loop<sup>9+</sup> | boolean | 是 | 是 | 视频循环播放属性,默认'false',设置为'true'表示循环播放,动态属性。<br/>只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。<br/>直播场景不支持loop设置。 |
| videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | 是 | 是 | 视频缩放模式,默认VIDEO_SCALE_TYPE_FIT_CROP,动态属性。<br/>只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 |
| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | 是 | 是 | 音频焦点模型,默认SHARE_MODE,动态属性。<br/>只允许在**prepared**/**playing**/**paused**/**completed**状态下设置。 |
| audioRendererInfo<sup>10+</sup> | [audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8) | 是 | 是 | 设置音频渲染信息,默认值contentType为CONTENT_TYPE_MUSIC,streamUsage为STREAM_USAGE_MEDIA。<br/>只允许在**initialized**状态下设置 |
| state<sup>9+</sup> | [AVPlayerState](#avplayerstate9) | 是 | 否 | 音视频播放的状态,全状态有效,可查询参数。 |
| currentTime<sup>9+</sup> | number | 是 | 否 | 视频的当前播放位置,单位为毫秒(ms),可查询参数。<br/>返回为(-1)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。 |
| currentTime<sup>9+</sup> | number | 是 | 否 | 视频的当前播放位置,单位为毫秒(ms),可查询参数。<br/>返回为(-1)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。<br/>直播场景默认返回(-1)。 |
| duration<sup>9+</sup><a name=avplayer_duration></a> | number | 是 | 否 | 视频时长,单位为毫秒(ms),可查询参数。<br/>返回为(-1)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。<br/>直播场景默认返回(-1)。 |
| width<sup>9+</sup> | number | 是 | 否 | 视频宽,单位为像素(px),可查询参数。<br/>返回为(0)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。 |
| height<sup>9+</sup> | number | 是 | 否 | 视频高,单位为像素(px),可查询参数。<br/>返回为(0)表示无效值,**prepared**/**playing**/**paused**/**completed**状态下有效。 |
......@@ -1003,6 +1003,7 @@ for (let i = 0; i < arrayDescription.length; i++) {
seek(timeMs: number, mode?:SeekMode): void
跳转到指定播放位置,只能在prepared/playing/paused/complete状态调用,可以通过[seekDone事件](#seekDone_on)确认是否生效。
注:直播场景不支持seek。
**系统能力:** SystemCapability.Multimedia.Media.AVPlayer
......@@ -1068,6 +1069,7 @@ avPlayer.off('seekDone')
setSpeed(speed: PlaybackSpeed): void
设置倍速模式,只能在prepared/playing/paused/complete状态调用,可以通过[speedDone事件](#speedDone_on)确认是否生效。
注:直播场景不支持setSpeed。
**系统能力:** SystemCapability.Multimedia.Media.AVPlayer
......@@ -1345,6 +1347,7 @@ avPlayer.off('endOfStream')
on(type: 'timeUpdate', callback: Callback\<number>): void
监听资源播放当前时间,单位为毫秒(ms),用于刷新进度条当前位置,默认间隔1s时间上报,因用户操作(seek)产生的时间变化会立刻上报。
注:直播场景不支持timeUpdate上报。
**系统能力:** SystemCapability.Multimedia.Media.AVPlayer
......@@ -1388,6 +1391,7 @@ avPlayer.off('timeUpdate')
on(type: 'durationUpdate', callback: Callback\<number>): void
监听资源播放资源的时长,单位为毫秒(ms),用于刷新进度条长度,默认只在prepared上报一次,同时允许一些特殊码流刷新多次时长。
注:直播场景不支持durationUpdate上报。
**系统能力:** SystemCapability.Multimedia.Media.AVPlayer
......
......@@ -30,7 +30,7 @@ getSync(key: string, def?: string): string
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 待查询的系统参数Key。 |
| def | string | 否 | 默认值。 |
| def | string | 否 | def 为所要获取的系统参数的默认值 <br> def为可选参数,仅当系统参数不存在时生效 <br>def可以传undefined(返回空)或自定义的任意值 |
**返回值:**
......@@ -124,7 +124,7 @@ get(key: string, def?: string): Promise&lt;string&gt;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 待查询的系统参数Key。 |
| def | string | 否 | 默认值。 |
| def | string | 否 | def 为所要获取的系统参数的默认值 <br> def为可选参数,仅当系统参数不存在时生效 <br>def可以传undefined(返回空)或自定义的任意值 |
**返回值:**
......
......@@ -29,7 +29,7 @@ getSync(key: string, def?: string): string
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 待查询的系统参数Key。 |
| def | string | 否 | 默认值。 |
| def | string | 否 | def 为所要获取的系统参数的默认值 <br> def为可选参数,仅当系统参数不存在时生效 <br>def可以传undefined(返回空)或自定义的任意值 |
**返回值:**
......@@ -123,7 +123,7 @@ get(key: string, def?: string): Promise&lt;string&gt;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 待查询的系统参数Key。 |
| def | string | 否 | 默认值。 |
| def | string | 否 | def 为所要获取的系统参数的默认值 <br> def为可选参数,仅当系统参数不存在时生效 <br>def可以传undefined(返回空)或自定义的任意值 |
**返回值:**
......
......@@ -369,15 +369,15 @@ create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean }): Te
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------------------------------------------------ |
| encoding | string | 否 | 编码格式 |
| encoding | string | 否 | 编码格式,默认值是'utf-8'。 |
| options | Object | 否 | 编码相关选项参数,存在两个属性fatal和ignoreBOM。 |
**表1.1**options
| 名称 | 参数类型 | 必填 | 说明 |
| --------- | -------- | ---- | ------------------ |
| fatal | boolean | 否 | 是否显示致命错误。 |
| ignoreBOM | boolean | 否 | 是否忽略BOM标记。 |
| fatal | boolean | 否 | 是否显示致命错误,默认值是false。 |
| ignoreBOM | boolean | 否 | 是否忽略BOM标记,默认值是false。 |
**示例:**
......@@ -445,15 +445,15 @@ TextDecoder的构造函数。
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| encoding | string | 否 | 编码格式。 |
| encoding | string | 否 | 编码格式,默认值是'utf-8'。 |
| options | Object | 否 | 编码相关选项参数,存在两个属性fatal和ignoreBOM。 |
**表1** options
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| fatal | boolean | 否 | 是否显示致命错误。 |
| ignoreBOM | boolean | 否 | 是否忽略BOM标记。 |
| fatal | boolean | 否 | 是否显示致命错误,默认值是false。 |
| ignoreBOM | boolean | 否 | 是否忽略BOM标记,默认值是false。 |
**示例:**
......@@ -518,7 +518,7 @@ TextEncoder用于将字符串编码为字节数组,支持多种编码格式,
| 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| encoding | string | 是 | 否 | 编码格式,默认值是utf-8。 |
| encoding | string | 是 | 否 | 编码格式,默认值是'utf-8'。 |
### constructor
......
......@@ -234,7 +234,7 @@ postMessageEventExt(message: WebMessageExt): void
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | :------------- |
| message | [WebMessageExt](#webmessageext) | 是 | 要发送的消息。 |
| message | [WebMessageExt](#webmessageext10) | 是 | 要发送的消息。 |
**错误码:**
......@@ -491,7 +491,7 @@ static setHttpDns(secureDnsMode:SecureDnsMode, secureDnsConfig:string): void
| 参数名 | 类型 | 必填 | 说明 |
| ------------------ | ------- | ---- | ------------- |
| secureDnsMode | [SecureDnsMode](#securednsmode) | 是 | 使用HTTPDNS的模式。|
| secureDnsMode | [SecureDnsMode](#securednsmode10) | 是 | 使用HTTPDNS的模式。|
| secureDnsConfig | string | 是 | HTTPDNS server的配置,必须是https协议并且只允许配置一个server。 |
**示例:**
......@@ -1754,7 +1754,7 @@ zoom(factor: number): void
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------- | ---- | ------------------------------------------------------------ |
| factor | number | 是 | 基于当前网页所需调整的相对缩放比例,正值为放大,负值为缩小。 |
| factor | number | 是 | 基于当前网页所需调整的相对缩放比例,入参要求大于0,当入参为1时为默认加载网页的缩放比例,入参小于1为缩小,入参大于1为放大。 |
**错误码:**
......@@ -2137,24 +2137,24 @@ struct WebComponent {
this.ports = this.controller.createWebMessagePorts();
// 2、在应用侧的消息端口(如端口1)上注册回调事件。
this.ports[1].onMessageEvent((result: web_webview.WebMessage) => {
let msg = 'Got msg from HTML:';
if (typeof(result) == "string") {
console.log("received string message from html5, string is:" + result);
msg = msg + result;
} else if (typeof(result) == "object") {
if (result instanceof ArrayBuffer) {
console.log("received arraybuffer from html5, length is:" + result.byteLength);
msg = msg + "lenght is " + result.byteLength;
} else {
console.log("not support");
}
let msg = 'Got msg from HTML:';
if (typeof(result) == "string") {
console.log("received string message from html5, string is:" + result);
msg = msg + result;
} else if (typeof(result) == "object") {
if (result instanceof ArrayBuffer) {
console.log("received arraybuffer from html5, length is:" + result.byteLength);
msg = msg + "lenght is " + result.byteLength;
} else {
console.log("not support");
}
this.receivedFromHtml = msg;
})
// 3、将另一个消息端口(如端口0)发送到HTML侧,由HTML侧保存并使用。
this.controller.postMessage('__init_port__', [this.ports[0]], '*');
} else {
console.log("not support");
}
this.receivedFromHtml = msg;
})
// 3、将另一个消息端口(如端口0)发送到HTML侧,由HTML侧保存并使用。
this.controller.postMessage('__init_port__', [this.ports[0]], '*');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
......@@ -2523,6 +2523,37 @@ struct WebComponent {
}
```
支持开发者基于默认的UserAgent去定制UserAgent。
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State ua: string = ""
aboutToAppear():void {
web_webview.once('webInited', () => {
try {
// 应用侧用法示例,定制UserAgent。
this.ua = this.controller.getUserAgent() + 'xxx';
} catch(error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.userAgent(this.ua)
}
}
}
```
### getTitle
getTitle(): string
......@@ -3191,7 +3222,7 @@ import image from "@ohos.multimedia.image"
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State pixelmap: image.PixelMap = undefined;
@State pixelmap: image.PixelMap = undefined;
build() {
Column() {
......@@ -3297,12 +3328,12 @@ struct WebComponent {
.onClick(() => {
try {
this.controller.hasImage((error, data) => {
if (error) {
console.info(`hasImage error: ` + JSON.stringify(error))
return;
}
console.info("hasImage: " + data);
});
if (error) {
console.info(`hasImage error: ` + JSON.stringify(error))
return;
}
console.info("hasImage: " + data);
});
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
......@@ -3352,11 +3383,11 @@ struct WebComponent {
.onClick(() => {
try {
this.controller.hasImage().then((data) => {
console.info('hasImage: ' + data);
})
.catch(function (error) {
console.error("error: " + error);
})
console.info('hasImage: ' + data);
})
.catch(function (error) {
console.error("error: " + error);
})
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
......@@ -4131,7 +4162,7 @@ struct WebComponent {
通过WebCookie可以控制Web组件中的cookie的各种行为,其中每个应用中的所有web组件共享一个WebCookieManager实例。
### getCookie
### getCookie
static getCookie(url: string): string
......@@ -4187,7 +4218,7 @@ struct WebComponent {
}
```
### setCookie
### setCookie
static setCookie(url: string, value: string): void
......@@ -4238,7 +4269,7 @@ struct WebComponent {
}
```
### saveCookieAsync
### saveCookieAsync
static saveCookieAsync(callback: AsyncCallback\<void>): void
......@@ -4284,7 +4315,7 @@ struct WebComponent {
}
```
### saveCookieAsync
### saveCookieAsync
static saveCookieAsync(): Promise\<void>
......@@ -4331,7 +4362,7 @@ struct WebComponent {
}
```
### putAcceptCookieEnabled
### putAcceptCookieEnabled
static putAcceptCookieEnabled(accept: boolean): void
......@@ -4372,7 +4403,7 @@ struct WebComponent {
}
```
### isCookieAllowed
### isCookieAllowed
static isCookieAllowed(): boolean
......@@ -4410,7 +4441,7 @@ struct WebComponent {
}
```
### putAcceptThirdPartyCookieEnabled
### putAcceptThirdPartyCookieEnabled
static putAcceptThirdPartyCookieEnabled(accept: boolean): void
......@@ -4451,7 +4482,7 @@ struct WebComponent {
}
```
### isThirdPartyCookieAllowed
### isThirdPartyCookieAllowed
static isThirdPartyCookieAllowed(): boolean
......@@ -4489,7 +4520,7 @@ struct WebComponent {
}
```
### existCookie
### existCookie
static existCookie(): boolean
......@@ -4527,7 +4558,7 @@ struct WebComponent {
}
```
### deleteEntireCookie
### deleteEntireCookie
static deleteEntireCookie(): void
......@@ -4558,7 +4589,7 @@ struct WebComponent {
}
```
### deleteSessionCookie
### deleteSessionCookie
static deleteSessionCookie(): void
......
......@@ -204,7 +204,7 @@ postMessage(message: Object, options?: PostMessageOptions): void
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| message | Object | 是 | 发送至Worker的数据。 |
| options | [PostMessageOptions](#postmessageoptions) | 否 | 可传输对象是&nbsp;ArrayBuffer&nbsp;的实例对象。若不填入该参数,默认设置为"undefined"。|
| options | [PostMessageOptions](#postmessageoptions) | 否 | 可传输对象是&nbsp;ArrayBuffer&nbsp;的实例对象。若不填入该参数,默认设置为 undefined。|
**错误码:**
......@@ -905,7 +905,7 @@ Worker线程向宿主线程发送消息。
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| message | Object | 是 | 发送至宿主线程的数据。 |
| options | [PostMessageOptions](#postmessageoptions) | 否 | 可传输对象是ArrayBuffer的实例对象。若不填入该参数,默认设置为"undefined"。|
| options | [PostMessageOptions](#postmessageoptions) | 否 | 可传输对象是ArrayBuffer的实例对象。若不填入该参数,默认设置为 undefined。|
**错误码:**
......@@ -1296,7 +1296,7 @@ postMessage(message: Object, options?: PostMessageOptions): void
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| message | Object | 是 | 发送至Worker的数据。 |
| options | [PostMessageOptions](#postmessageoptions) | 否 | 可传输对象是&nbsp;ArrayBuffer&nbsp;的实例对象。若不填入该参数,默认设置为"undefined"。|
| options | [PostMessageOptions](#postmessageoptions) | 否 | 可传输对象是&nbsp;ArrayBuffer&nbsp;的实例对象。若不填入该参数,默认设置为 undefined。|
**示例:**
......@@ -1766,7 +1766,7 @@ Worker线程向宿主线程发送消息。
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| message | Object | 是 | 发送至宿主线程的数据。 |
| options | [PostMessageOptions](#postmessageoptions) | 否 | 可传输对象是ArrayBuffer的实例对象。若不填入该参数,默认设置为"undefined"。|
| options | [PostMessageOptions](#postmessageoptions) | 否 | 可传输对象是ArrayBuffer的实例对象。若不填入该参数,默认设置为 undefined。|
**示例:**
......
......@@ -41,6 +41,7 @@ Text(content?: string | Resource)
| maxFontSize | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 设置文本最大显示字号。<br/>需配合minFontSize以及maxline或布局大小限制使用,单独设置不生效。 <br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| textCase | [TextCase](ts-appendix-enums.md#textcase) | 设置文本大小写。<br />默认值:TextCase.Normal <br/>从API version 9开始,该接口支持在ArkTS卡片中使用。|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 组件支持设置文本是否可复制粘贴。<br />默认值:CopyOptions.None <br/>该接口支持在ArkTS卡片中使用。 |
| draggable<sup>9+</sup> | boolean | 设置选中文本拖拽效果。<br/>不能和[onDragStart](ts-universal-events-drag-drop.md)事件同时使用;<br/>需配合copyOption一起使用,支持对选中文本的拖拽以及选中内容复制到输入框。<br/>默认值:false |
| textShadow<sup>10+</sup> | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明) | 设置文字阴影效果。 |
| heightAdaptivePolicy<sup>10+</sup> | [TextHeightAdaptivePolicy](ts-appendix-enums.md#TextHeightAdaptivePolicy10) | 设置文本自适应高度的方式。 |
| textIndent<sup>10+</sup> | number&nbsp;\|&nbsp;string | 设置首行文本缩进,默认值0。 |
......
......@@ -4328,7 +4328,7 @@ resend(): void
}
```
### cancel<sup>9+</sup>
### cancel<sup>9+</sup>
cancel(): void
......
......@@ -4,6 +4,7 @@
- [支持的标准库介绍](third_party_libc/musl.md)
- 附录
- [Native api中没有导出的符号列表](third_party_libc/musl-peculiar-symbol.md)
- [Native api中由于权限管控可能调用失败的符号列表](third_party_libc/musl-permission-control-symbol.md)
- [Native api中导出的EGL符号列表](third_party_opengl/egl-symbol.md)
- [Native api中导出的OpenGL ES 3.0符号列表](third_party_opengl/openglesv3-symbol.md)
- [Native api中支持的OpenSL ES接口列表](third_party_opensles/opensles.md)
\ No newline at end of file
......@@ -1876,4 +1876,24 @@
**授权方式**:system_grant
**ACL使能**:TRUE
\ No newline at end of file
**ACL使能**:TRUE
## ohos.permission.ACCESS_CAST_ENGINE_MIRROR
允许应用使用镜像投屏能力。
**权限级别**:system_basic
**授权方式**:system_grant
**ACL使能**:TRUE
## ohos.permission.ACCESS_CAST_ENGINE_STREAM
允许应用调用系统资源投射能力。
**权限级别**:system_basic
**授权方式**:system_grant
**ACL使能**:TRUE
......@@ -13,9 +13,11 @@ Flex为采用弹性布局的容器。容器内部的所有子元素,会自动
- 第一次布局子组件主轴尺寸长度总和等于容器主轴尺寸长度,不需要二次布局。
![layout-performance-1](figures/layout-performance-1.png)
- 第一次布局子组件主轴尺寸长度总和小于容器主轴尺寸长度,且包含设置有效的flexGrow属性的子组件,设置有效的flexGrow属性的子组件会触发二次布局,拉伸布局填满容器。
![layout-performace-2](figures/layout-performace-2.gif)
- 第一次布局子组件主轴尺寸长度总和大于容器主轴尺寸长度,且包含设置有效的flexShrink属性(flex子组件默认值为1,为有效值)的子组件,设置有效的flexShrink属性的子组件会触发二次布局,压缩布局填满容器。
......
......@@ -8,7 +8,7 @@ Web组件用于在应用程序中显示Web页面内容,为开发者提供页
- 页面交互:Web组件提供丰富的页面交互的方式,包括:设置前端页面深色模式,新窗口中加载页面,位置权限管理,Cookie管理,应用侧使用前端页面JavaScript等能力。
- 页面调试:Web组件支持使用Devtools工具调试前端页面。
- 页面调试:Web组件支持使用[Devtools工具](web-debugging-with-devtools.md)调试前端页面。
下面通过常见使用场景举例,来具体介绍Web组件功能特性。
......@@ -2,7 +2,7 @@
# 轻量带屏解决方案之恒玄芯片移植案例
本文章基于恒玄科技`BES2600W`芯片的欧智通[Multi-modal V200Z-R开发板](https://gitee.com/openharmony/device_board_fnlink),进行轻量带屏开发板的标准移植,开发了智能开关面板样例,同时实现了`ace_engine_lite``graphic_ui``aafwk_lite``appexecfwk_lite``HDF`等部件基于`OpenHarmony LiteOS-M`内核的适配。移植架构上采用`Board``SoC`分离的方案,工具链`Newlib C`库与`Musl C`库可选,`LiteOS-M`内核编译采用`gn`结合`Kconfig`图形化配置等需求。
本文章基于恒玄科技`BES2600W`芯片的欧智通[Multi-modal V200Z-R开发板](https://gitee.com/openharmony/device_board_fnlink),进行轻量带屏开发板的标准移植,开发了智能开关面板样例,同时实现了`ace_engine_lite``arkui_ui_lite``aafwk_lite``appexecfwk_lite``HDF`等部件基于`OpenHarmony LiteOS-M`内核的适配。移植架构上采用`Board``SoC`分离的方案,工具链`Newlib C`库与`Musl C`库可选,`LiteOS-M`内核编译采用`gn`结合`Kconfig`图形化配置等需求。
## 编译构建
......@@ -1313,7 +1313,7 @@ aafwk_lite + appexecfwk_lite (AAFWK + APPEXECFWK)
|
ace_engine_lite + jerryscript + i18n_lite + resmgr_lite + utils/native/lite/... (ACE,JS引擎及其依赖)
|
graphic_ui + graphic_utils (图形框架)
arkui_ui_lite + graphic_utils (图形框架)
|
giflib + libjpeg + libpng + qrcodegen + freetype... (图形第三方库)
```
......
......@@ -2,7 +2,7 @@
# 小型系统STM32MP1芯片移植案例
本文章基于意法半导体`STM32MP157`芯片的小熊派[BearPi-HM Micro开发板](https://gitee.com/openharmony/device_board_bearpi),进行小型带屏开发板的移植,实现了`ace_engine_lite``graphic_ui``aafwk_lite``appexecfwk_lite``HDF`等部件基于`OpenHarmony LiteOS-A`内核的适配。移植架构上采用`Board``SoC`分离的方案。
本文章基于意法半导体`STM32MP157`芯片的小熊派[BearPi-HM Micro开发板](https://gitee.com/openharmony/device_board_bearpi),进行小型带屏开发板的移植,实现了`ace_engine_lite``arkui_ui_lite``aafwk_lite``appexecfwk_lite``HDF`等部件基于`OpenHarmony LiteOS-A`内核的适配。移植架构上采用`Board``SoC`分离的方案。
## 编译构建
......
......@@ -28,11 +28,15 @@
### 目录<a name="section141331948134020"></a>
```
/foundation/arkui
├── ui_lite # UI模块,包括UI控件、动画、字体等功能
/foundation/graphic
├── surface # 共享内存
├── ui # UI模块,包括UI控件、动画、字体等功能
├── utils # 图形基础库和硬件适配层
└── wms # 窗口管理和输入事件管理
├── surface_lite # 共享内存
├── graphic_utils_lite # 图形基础库和硬件适配层
/foundation/window
└── window_manager_lite # 窗口管理和输入事件管理
```
### 约束<a name="section15729113104112"></a>
......@@ -48,13 +52,13 @@
**图形子系统**
[graphic\_surface](https://gitee.com/openharmony/graphic_surface)
[graphic\_surface_lite](https://gitee.com/openharmony/graphic_surface_lite)
[graphic\_ui](https://gitee.com/openharmony/graphic_ui)
[arkui\_ui_lite](https://gitee.com/openharmony/arkui_ui_lite)
[graphic\_wms](https://gitee.com/openharmony/graphic_wms)
[window\_window_manager_lite](https://gitee.com/openharmony/window_window_manager_lite)
[graphic\_utils](https://gitee.com/openharmony/graphic_utils)
[graphic\_graphic_utils_lite](https://gitee.com/openharmony/graphic_graphic_utils_lite)
## 1.2 标准系统<a name="section1249610812538"></a>
......
......@@ -140,10 +140,10 @@ repo sync -c
| startup_frameworks_syspara_lite | startup_syspara_lite | 仓名变更 |
| startup_hals_syspara_lite | - | 只读归档 |
| startup_interfaces_kits_syspara_lite | - | 只读归档 |
| graphic_lite | graphic_surface | 仓名变更 |
| - | graphic_ui | 新增组件 |
| - | graphic_utils | 新增组件 |
| - | graphic_wms | 新增组件 |
| graphic_lite | graphic_surface_lite | 仓名变更 |
| - | arkui_ui_lite | 仓名变更 |
| - | graphic_graphic_utils_lite | 仓名变更 |
| - | window_manager_lite | 仓名变更 |
| - | third_party_giflib | 新增组件 |
| - | third_party_qrcodegen | 新增组件 |
| - | drivers_adapter_khdf_linux | 新增组件 |
......
......@@ -464,4 +464,65 @@ WebAsyncController类下接口迁移至web.webview.webview.WebviewController,
}
}
}
```
\ No newline at end of file
```
## cl.web.11 删除webDebuggingAccess接口
该接口定义不合理,该属性对所有web实例生效的,属于全局配置。用本次新增的接口setWebDebuggingAccess替换。
**变更影响**
该接口删除无法再使用,请使用新增的接口setWebDebuggingAccess替换。
**关键的接口/组件变更**
| 类名 | 接口类型 | 接口声明 | 变更类型 |
| -- | -- | -- | -- |
|WebAttribute | method | webDebugggingAccess(webDebugggingAccess: boolean): WebAttribute| 删除 |
**适配指导**
该接口删除无法再使用,请使用新增的接口setWebDebuggingAccess替换。
## cl.web.12 新增setWebDebuggingAccess接口
WebviewController提供静态方法来设置调试模式开关,该设置对所有web实例生效。
**变更影响**
原有webDebugggingAccess属性定义不合理,因此新增该静态接口来设置调试模式开关。应用侧需要使用该接口来打开调试模式开关。
**关键的接口/组件变更**
| 类名 | 接口类型 | 接口声明 | 变更类型 |
| -- | -- | -- | -- |
|webview.WebviewController | method | static setWebDebugggingAccess(webDebugggingAccess: boolean): void| 新增 |
**适配指导**
以打开调试开关为例,示例代码如下:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
aboutToAppear():void {
try {
web_webview.WebviewController.setWebDebuggingAccess(true);
} catch(error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
\ No newline at end of file
# 软总线子系统ChangeLog
## cl.softbus.1 IPC接口中unregisterDeathRecipient接口返回值变更,更改为void。
unregisterDeathRecipient(recipient: DeathRecipient, flags: number)方法返回值为boolean,更正为void。
**变更影响**
该unregisterDeathRecipient接口如果需要继续使用,建议优先使用removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean方法。
**关键的接口/组件变更**
- 变更前:
```js
unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean
```
- 变更后:
```js
unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void
```
**适配指导**
# 软总线子系统ChangeLog
## cl.softbus.1 IPC接口中unregisterDeathRecipient接口返回值变更,更改为void。
unregisterDeathRecipient(recipient: DeathRecipient, flags: number)方法返回值为boolean,更正为void。
**变更影响**
该unregisterDeathRecipient接口如果需要继续使用,建议优先使用removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean方法。
**关键的接口/组件变更**
- 变更前:
```js
unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean
```
- 变更后:
```js
unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void
```
**适配指导**
该unregisterDeathRecipient接口如果需要继续使用,建议优先使用removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean方法。
\ No newline at end of file
# arkui子系统ChangeLog
## cl.arkui.1 List组件和Gird组件滚动条默认状态变更
List组件和Gird组件滚动条默认状态从BarState.Off变更为BarState.Auto。
**变更影响**
List组件和Gird组件,如果没有设置滚动条状态,变更前不会显示滚动条,变更以后滚动时会显示滚动条,滚动停止两秒后滚动条隐藏。
**关键接口/组件变更**
List组件和Gird组件滚动条API接口文档:
- [List组件属性](../../../application-dev/reference/arkui-ts/ts-container-list.md#属性)
- [Grid组件属性](../../../application-dev/reference/arkui-ts/ts-container-grid.md#属性)
**适配指导**
对于不需要滚动条的场景,需要将List组件或Grid组件的scrollBar属性设置为BarState.Off。
参考代码如下:
```ts
// xxx.ets
@Entry
@Component
struct ListItemExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
build() {
Column() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}
}, item => item)
}
.width('90%')
.scrollBar(BarState.Off)
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
}
}
```
\ No newline at end of file
......@@ -11,6 +11,10 @@
- [如何实现列表项的新增和删除](how-to-add-delete-listitems.md)
- [如何通过显示动画实现书籍翻页动效](book-flip-animation.md)
- [如何为同一组件在不同场景下绑定不同的业务逻辑](different-operations-for-one-component.md)
- [如何实现列表项滑动显示快捷菜单](listitem-slide-to-display-menu.md)
- [如何在网格组件中通过拖拽交换子组件的位置](griditem-drag-and-drop.md)
### 网络管理
- [如何请求并加载网络图片](how-to-load-images-from-internet.md)
......
## 如何在网格Grid中通过拖拽交换子组件位置
### 场景说明
在使用网格Grid的应用中,可以通过拖拽子组件GridItem的方式,交换子组件的显示位置。
### 效果呈现
本示例在模拟器中显示的最终效果如下(预览器中显示效果略有差异):
![listitem-slide](figures/griditem-drag.gif)
### 运行环境
- IDE:DevEco Studio 3.1 Beta2
- SDK:Ohos_sdk_public 3.2.11.5 (API Version 9 Release)
### 实现原理
1. 设置Grid的editMode属性为true,使Grid进入编辑模式,从而可以拖拽Grid组件内部GridItem。
2. 在Grid的相关拖拽事件中进行拖拽逻辑处理:
1. 在onItemDragStart事件中显示拖拽过程中的图片,即被拖拽的GridItem。
2. 在onItemDrop事件中根据拖拽前后的位置,完成两个GridItem位置交换的逻辑。
### 开发步骤
1. 构建Grid组件及子组件GridItem,开启Grid组件的editMode属性。
```ts
build() {
Column({ space: 5 }) {
Grid(this.scroller) {
ForEach(this.numbers, (day: string) => {
GridItem() {
...
}
})
}
.editMode(true)
...
}.width('100%').margin({ top: 5 })
}
```
2. 当长按GridItem时触发onItemDragStart事件,在该事件中提供被拖拽GridItem的显示逻辑。
```ts
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => {
return this.pixelMapBuilder()
})
```
其中,pixelMapBuilder构造拖拽过程中显示的图片,即被拖拽的GridItem。
```ts
@State text: string = 'drag'
@Builder pixelMapBuilder() {
Column() {
Text(this.text)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
}
}
```
拖拽过程中GridItem显示的内容,在触摸事件发生时进行传递。
```ts
ForEach(this.numbers, (day: string) => {
GridItem() {
Text(day)
...
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
this.text = day
}
})
}
})
```
3. 停止拖拽时触发onItemDrop事件,在该事件中完成两个GridItem位置交换的逻辑。
为了防止GridItem被拖拽到空白的区域,在交换之前判断拖拽插入的位置是否超出当前已有内容的范围:
```ts
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => {
if(insertIndex < this.numbers.length){
this.changeIndex(itemIndex, insertIndex)
}
})
```
其中,changeIndex为具体交换数组元素位置的逻辑:
```ts
changeIndex(index1: number, index2: number) {
[this.numbers[index1], this.numbers[index2]] = [this.numbers[index2], this.numbers[index1]];
}
```
### 完整代码
通过上述步骤可以完成整个示例的开发,完整代码如下:
```ts
@Entry
@Component
struct Index {
@State numbers: String[] = []
scroller: Scroller = new Scroller()
@State text: string = 'drag'
//拖拽过程中展示的样式
@Builder pixelMapBuilder() {
Column() {
Text(this.text)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
}
}
aboutToAppear() {
for (let i = 1;i <= 15; i++) {
this.numbers.push(i + '')
}
}
//交换数组中元素位置
changeIndex(index1: number, index2: number) {
[this.numbers[index1], this.numbers[index2]] = [this.numbers[index2], this.numbers[index1]];
}
build() {
Column({ space: 5 }) {
Grid(this.scroller) {
ForEach(this.numbers, (day: string) => {
GridItem() {
Text(day)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
this.text = day
}
})
}
})
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.onScrollIndex((first: number) => {
console.info(first.toString())
})
.width('90%')
.backgroundColor(0xFAEEE0)
.height('100%')
//设置Grid是否进入编辑模式,进入编辑模式可以拖拽Grid组件内部GridItem
.editMode(true)
//第一次拖拽此事件绑定的组件时,触发回调
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => {
//设置拖拽过程中显示的图片
return this.pixelMapBuilder()
})
//绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调
//itemIndex为拖拽起始位置,insertIndex为拖拽插入位置
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => {
//不支持拖拽到已有内容以外的位置
if(insertIndex < this.numbers.length){
this.changeIndex(itemIndex, insertIndex)
}
})
}.width('100%').margin({ top: 5 })
}
}
```
\ No newline at end of file
# 如何实现列表项ListItem滑动显示快捷菜单
## 场景说明
在使用列表List的应用中,可以滑动列表项ListItem显示快捷菜单,快速完成对列表项的操作。List垂直布局时滑动操作支持左滑和右滑。
## 效果呈现
本示例最终效果如下:
![listitem-slide](figures/listitem-slide-demo.gif)
## 运行环境
- IDE:DevEco Studio 3.1 Beta2
- SDK:Ohos_sdk_public 3.2.11.5 (API Version 9 Release)
## 实现原理
1. 自定义组件实现划出后的快捷菜单。
2. 利用ListItem组件的swipeAction属性,设置ListItem的划出组件为上述自定义组件。
## 开发步骤
1. 实现自定义组件。本示例使用Row、Image组件组装一个包含两个图标按钮的快捷菜单组件。在定义组件时,给定入参便于后续定位到被滑动的ListItem。本示例中,当滑动出菜单后,点击删除按钮可以删除当前ListItem。
```ts
@Builder itemEnd(index:number) {
Row () {
Image($r("app.media.ic_public_settings_filled"))
...
})
Image($r("app.media.ic_public_delete_filled"))
...
.onClick(()=>{
this.itemIndexArr.splice(index,1)
})
}.padding(4).justifyContent(FlexAlign.SpaceEvenly)
}
```
2. 使用ForEach循环渲染列表,并为ListItem设置swipeAction属性为上述自定义组件,设置属性时绑定入参。
swipeAction支持设置不同的滑动方向:
* start:List垂直布局时,向右滑动ListItem时在左侧显示的组件。本示例中未配置。
* end:List垂直布局时,向左滑动ListItem时在右侧显示的组件。
```ts
ForEach(this.itemIndexArr,(item,index) =>{
ListItem(){
Text('' + item)
...
}.swipeAction({ end:this.itemEnd.bind(this,index), edgeEffect: SwipeEdgeEffect.Spring})
},item=>item)
```
## 完整代码
通过上述步骤可以完成整个示例的开发,完整代码如下:
```ts
@Entry
@Component
struct Index {
@State itemIndexArr:number[] = [1,2]
@Builder itemEnd(index:number) {
Row () {
Image($r("app.media.ic_public_settings_filled"))
.width(32)
.height(32)
.margin(4)
.onClick(()=>{
console.info('Click Setting Icon')
})
Image($r("app.media.ic_public_delete_filled"))
.width(32)
.height(32)
.margin(4)
.onClick(()=>{
this.itemIndexArr.splice(index,1)
})
}.padding(4).justifyContent(FlexAlign.SpaceEvenly)
}
build() {
Column() {
List({space:10}) {
ForEach(this.itemIndexArr,(item,index) =>{
ListItem(){
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.margin({ top: 10 })
.borderRadius(16)
.textAlign(TextAlign.Center)
.backgroundColor(Color.White)
}.swipeAction({ end:this.itemEnd.bind(this,index), edgeEffect: SwipeEdgeEffect.Spring})
},item=>item)
}
Row() {
Image($r("app.media.ic_public_add_norm"))
.width(40)
.height(40)
.margin(4)
.onClick(()=>{
this.itemIndexArr.push(this.itemIndexArr.length + 1)
})
}
}
.padding(10)
.backgroundColor(0xDCDCDC)
.width('100%')
.height('100%')
}
}
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册