提交 391474a7 编写于 作者: X xsz233

Merge branch 'master' of gitee.com:xsz233/docs_api

......@@ -129,8 +129,10 @@ zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @Austin23
zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @Austin23
zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23
zh-cn/application-dev/ability/ @RayShih
zh-cn/application-dev/ui/ @HelloCrease
zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515
zh-cn/application-dev/ui/ @HelloCrease @qieqiewl @tomatodevboy @niulihua
zh-cn/application-dev/notification/ @RayShih
zh-cn/application-dev/windowmanager/ @ge-yafang
zh-cn/application-dev/webgl/ @ge-yafang
......@@ -445,8 +447,19 @@ zh-cn/application-dev/reference/apis/js-apis-formextensioncontext.md @RayShih @l
zh-cn/application-dev/reference/apis/js-apis-formhost.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-formInfo.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-formprovider.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errcode-inputmethod-framework.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errcode-usb.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-colorspace-manager.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-display.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-distributed-data_object.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-pasteboard.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-window.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-missionManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
......
......@@ -18,15 +18,15 @@
- master:最新开发版本。
- OpenHarmony 3.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta2.md)了解版本详情。
- OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
已更新至OpenHarmony 3.1.1 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.1-release.md)了解版本详情。
版本已更新至OpenHarmony 3.1.3 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.3-release.md)了解版本详情。
- OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。
该版本已更新至OpenHarmony 3.0.5 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md)了解版本详情。
该版本已更新至OpenHarmony 3.0.6 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md)了解版本详情。
- OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。
......@@ -34,7 +34,7 @@
### 历史稳定版本
OpenHarmony_v1.x_release:OpenHarmony 1.1.4 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md)了解版本详情。
OpenHarmony_v1.x_release:OpenHarmony 1.1.5 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md)了解版本详情。
如需了解更多版本详情,点击[此处](zh-cn/release-notes/)
......
# Legal Notices
**Copyright (c) 2020-2022 OpenAtom OpenHarmony. All rights reserved.**
## Copyright
All copyrights of the OpenHarmony documents are reserved by OpenAtom OpenHarmony.
The OpenHarmony documents are licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). For easier understanding, you can visit [Creative Commons](https://creativecommons.org/licenses/by/4.0/) to get a human-readable summary of the license. For the complete content, see [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode).
## Trademarks and Permissions
No content provided in the OpenHarmony documentation shall be deemed as a grant of the approval or right to use any trademark, name, or logo of the OpenAtom Foundation and OpenAtom OpenHarmony. No third parties shall use any of the aforementioned trademarks, names, or logos in any way without explicit prior written permission of the OpenAtom Foundation.
## Disclaimer
The information in the OpenHarmony documents is subject to change without notice.
The OpenHarmony documents are provided without any express or implied warranty. In any case, the OpenAtom Foundation or the copyright owner is not liable for any direct or indirect loss arising from the use of the OpenHarmony documents, regardless of the cause or legal theory, even if the OpenHarmony documents have stated that there is a possibility of such loss.
<!--no_check-->
\ No newline at end of file
......@@ -10,7 +10,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
| Class/Interface | Function | Description |
| --------------- | -------- | ----------- |
| IRemoteBroker | sptr<IRemoteObject> AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. |
| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr<IRemoteObject> AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. |
| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. |
| IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. |
......@@ -25,10 +25,10 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
```
class ITestAbility : public IRemoteBroker {
public:
// DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string.
DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility");
int TRANS_ID_PING_ABILITY = 1; // Define the message code.
virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions.
// DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string.
DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility");
int TRANS_ID_PING_ABILITY = 1; // Define the message code.
virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions.
};
```
......
......@@ -66,25 +66,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
To allow your application to access device location information, declare the required permissions in the **module.json** file of your application. The sample code is as follows:
```
{
"module": {
"reqPermissions": [
"name": "ohos.permission.LOCATION",
"reason": "$string:reason_description",
"usedScene": {
"ability": ["com.myapplication.LocationAbility"],
"when": "inuse"
}
]
}
}
```
For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
You can declare the required permission in your application's configuration file. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
......
# Rendering Control
ArkTS provides conditional rendering and loop rendering. Conditional rendering can render state-specific UI content based on the application status. Loop rendering iteratively obtains data from the data source and creates the corresponding component during each iteration.
## Conditional Rendering
Use **if/else** for conditional rendering.
> **NOTE**
>
> - State variables can be used in the **if/else** statement.
>
> - The **if/else** statement can be used to implement rendering of child components.
>
> - The **if/else** statement must be used in container components.
>
> - Some container components limit the type or number of subcomponents. When **if/else** is placed in these components, the limitation applies to components created in **if/else** statements. For example, when **if/else** is used in the **\<Grid>** container component, whose child components can only be **\<GridItem>**, only the **\<GridItem>** component can be used in the **if/else** statement.
```ts
Column() {
if (this.count < 0) {
Text('count is negative').fontSize(14)
} else if (this.count % 2 === 0) {
Text('count is even').fontSize(14)
} else {
Text('count is odd').fontSize(14)
}
}
```
## Loop Rendering
You can use **ForEach** to obtain data from arrays and create components for each data item.
```
ForEach(
arr: any[],
itemGenerator: (item: any, index?: number) => void,
keyGenerator?: (item: any, index?: number) => string
)
```
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
| arr | any[] | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.|
| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.|
| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.|
> **NOTE**
>
> - **ForEach** must be used in container components.
>
> - The generated child components should be allowed in the parent container component of **ForEach**.
>
> - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**.
>
> - The call sequence of **itemGenerator** functions may be different from that of the data items in the array. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage:
>
> ```ts
> ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }),
> item => Text(`${item.i}. item.data.label`),
> item => item.data.id.toString())
> ```
## Example
```ts
// xxx.ets
@Entry
@Component
struct MyComponent {
@State arr: number[] = [10, 20, 30]
build() {
Column({ space: 5 }) {
Button('Reverse Array')
.onClick(() => {
this.arr.reverse()
})
ForEach(this.arr, (item: number) => {
Text(`item value: ${item}`).fontSize(18)
Divider().strokeWidth(2)
}, (item: number) => item.toString())
}
}
}
```
![forEach1](figures/forEach1.gif)
## Lazy Loading
You can use **LazyForEach** to iterate over provided data sources and create corresponding components during each iteration.
```ts
LazyForEach(
dataSource: IDataSource,
itemGenerator: (item: any) => void,
keyGenerator?: (item: any) => string
): void
interface IDataSource {
totalCount(): number;
getData(index: number): any;
registerDataChangeListener(listener: DataChangeListener): void;
unregisterDataChangeListener(listener: DataChangeListener): void;
}
interface DataChangeListener {
onDataReloaded(): void;
onDataAdd(index: number): void;
onDataMove(from: number, to: number): void;
onDataDelete(index: number): void;
onDataChange(index: number): void;
}
```
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | --------------------- | ---- | ------------------------------------------------------------ |
| dataSource | IDataSource | Yes | Object used to implement the **IDataSource** API. You need to implement related APIs. |
| itemGenerator | (item: any) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.|
| keyGenerator | (item: any) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**.|
### Description of IDataSource
| Name | Description |
| ------------------------------------------------------------ | ---------------------- |
| totalCount(): number | Obtains the total number of data records. |
| getData(index: number): any | Obtains the data corresponding to the specified index. |
| registerDataChangeListener(listener:DataChangeListener): void | Registers a listener for data changes.|
| unregisterDataChangeListener(listener:DataChangeListener): void | Deregisters a listener for data changes.|
### Description of DataChangeListener
| Name | Description |
| -------------------------------------------------------- | -------------------------------------- |
| onDataReloaded(): void | Invoked when all data is reloaded. |
| onDataAdded(index: number): void (deprecated) | Invoked when data is added to the position indicated by the specified index. |
| onDataMoved(from: number, to: number): void (deprecated) | Invoked when data is moved from the **from** position to the **to** position.|
| onDataDeleted(index: number): void (deprecated) | Invoked when data is deleted from the position indicated by the specified index. |
| onDataChanged(index: number): void (deprecated) | Invoked when data in the position indicated by the specified index is changed. |
| onDataAdd(index: number): void 8+ | Invoked when data is added to the position indicated by the specified index. |
| onDataMove(from: number, to: number): void 8+ | Invoked when data is moved from the **from** position to the **to** position.|
| onDataDelete(index: number): void 8+ | Invoked when data is deleted from the position indicated by the specified index. |
| onDataChange(index: number): void 8+ | Invoked when data in the position indicated by the specified index is changed. |
## Example
```ts
// xxx.ets
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 {
// Initialize the data list.
private dataArray: string[] = ['/path/image0.png', '/path/image1.png', '/path/image2.png', '/path/image3.png']
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({ space: 3 }) {
LazyForEach(this.data, (item: string) => {
ListItem() {
Row() {
Image(item).width(50).height(50)
Text(item).fontSize(20).margin({ left: 10 })
}.margin({ left: 10, right: 10 })
}
.onClick(() => {
// The count increases by one each time the list is clicked.
this.data.pushData('/path/image' + this.data.totalCount() + '.png')
})
}, item => item)
}
}
}
```
> **NOTE**
>
> - **LazyForEach** must be used in the container component. Currently, only the **\<List>**, **\<Grid>**, and **\<Swiper>** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time.
>
> - **LazyForEach** must create and only one child component in each iteration.
>
> - The generated child components must be allowed in the parent container component of **LazyForEach**.
>
> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement.
>
> - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**.
>
> - The call sequence of **itemGenerator** functions may be different from that of the data items in the data source. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage:
>
> ```ts
> LazyForEach(dataSource,
> item => Text(`${item.i}. item.data.label`)),
> item => item.data.id.toString())
> ```
![lazyForEach](figures/lazyForEach.gif)
......@@ -45,6 +45,7 @@
- [@ohos.application.formInfo](js-apis-formInfo.md)
- [@ohos.application.formProvider](js-apis-formprovider.md)
- [@ohos.application.missionManager](js-apis-missionManager.md)
- [@ohos.application.quickFixManager](js-apis-application-quickFixManager.md)
- [@ohos.application.Want](js-apis-application-Want.md)
- [@ohos.continuation.continuationManager](js-apis-continuation-continuationExtraParams.md)
- [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md)
......@@ -68,13 +69,13 @@
- [@ohos.bundle](js-apis-Bundle.md)
- [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md)
- [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md)
- [@ohos.bundleState](js-apis-deviceUsageStatistics.md)
- [@ohos.distributedBundle)](js-apis-Bundle-distributedBundle.md)
- [@ohos.zlib](js-apis-zlib.md)
- bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md)
- bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)
- bundle/[BundleInfo](js-apis-bundle-BundleInfo.md)
- bundle/[BundleInstaller](js-apis-bundle-BundleInstaller.md)
- bundle/[BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md)
- bundle/[CustomizeData](js-apis-bundle-CustomizeData.md)
- bundle/[DispatchInfo](js-apis-dispatchInfo.md)
- bundle/[ElementName](js-apis-bundle-ElementName.md)
......@@ -90,12 +91,13 @@
- UI Page
- [@ohos.animator](js-apis-animator.md)
- [@ohos.mediaquery](js-apis-mediaquery.md)
- [@ohos.promptAction](js-apis-promptAction.md)
- [@ohos.router](js-apis-router.md)
- [@ohos.uiAppearance](js-apis-uiappearance.md)
- Graphics
- [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md)
- [@ohos.display ](js-apis-display.md)
- [@ohos.effectKit](js-apis-effectKit.md)
- [@ohos.graphics.colorSpaceManager](js-apis-colorSpaceManager.md)
- [@ohos.screen](js-apis-screen.md)
- [@ohos.screenshot](js-apis-screenshot.md)
- [@ohos.window](js-apis-window.md)
......@@ -145,6 +147,7 @@
- [@ohos.document](js-apis-document.md)
- [@ohos.environment](js-apis-environment.md)
- [@ohos.fileio](js-apis-fileio.md)
- [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- [@ohos.securityLabel](js-apis-securityLabel.md)
- [@ohos.statfs](js-apis-statfs.md)
......@@ -260,6 +263,7 @@
- [@ohos.application.testRunner](js-apis-testRunner.md)
- [@ohos.uitest](js-apis-uitest.md)
- APIs No Longer Maintained
- [@ohos.bundleState](js-apis-deviceUsageStatistics.md)
- [@ohos.bytrace](js-apis-bytrace.md)
- [@ohos.data.storage](js-apis-data-storage.md)
- [@ohos.data.distributedData](js-apis-distributed-data.md)
......@@ -284,3 +288,4 @@
- [@system.sensor](js-apis-system-sensor.md)
- [@system.storage](js-apis-system-storage.md)
- [@system.vibrator](js-apis-system-vibrate.md)
- [console](js-apis-logs.md)
# BundleStatusCallback
The **BundleStatusCallback** module provides bundle callback information, which is obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md).
> **NOTE**
>
> 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.
## BundleStatusCallback
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Description |
| ------ | --------------------------------------------- | -------------------------------------- |
| add | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is added.|
| update | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is updated.|
| remove | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is removed.|
......@@ -106,8 +106,8 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description |
| -------------------- | --------------------- | ---- | ---------------------------------------------------- |
| type | "BundleStatusChange" | Yes | Event type. |
| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register. |
| type | string | Yes | Event type. Only **BundleStatusChange** is supported. |
| bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | Yes | Callback to register. |
| callback | AsyncCallback\<string> | Yes | Callback used to return a successful result or error information.|
## innerBundleManager.on
......@@ -130,10 +130,10 @@ This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| -------------------- | -------------------- | ---- | ------------------ |
| type | "BundleStatusChange" | Yes | Event type. |
| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register.|
| Name | Type | Mandatory| Description |
| -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
| type | string | Yes | Event type. Only **BundleStatusChange** is supported.|
| bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | Yes | Callback to register. |
**Return value**
......@@ -163,7 +163,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------------------------------------------------- |
| type | "BundleStatusChange" | Yes | Event type. |
| type | string | Yes | Event type. Only **BundleStatusChange** is supported. |
| callback | AsyncCallback\<string> | Yes | Callback used to return a successful result or error information.|
## innerBundleManager.off
......@@ -186,9 +186,9 @@ This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | -------------------- | ---- | ---------------- |
| type | "BundleStatusChange" | Yes | Event type.|
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ------------------------------------------ |
| type | string | Yes | Event type. Only **BundleStatusChange** is supported.|
**Return value**
......
# quickFixManager
The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire application.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import quickFixManager from '@ohos.application.quickFixManager';
```
## HapModuleQuickFixInfo
Defines the quick fix information at the HAP file level.
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| moduleName | Read only | string | Yes | Name of the HAP file. |
| originHapHash | Read only | string | Yes | Hash value of the HAP file. |
| quickFixFilePath | Read only | string | Yes | Installation path of the quick fix file. |
## ApplicationQuickFixInfo
Defines the quick fix information at the application level.
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| bundleName | Read only | string | Yes | Bundle name of the application. |
| bundleVersionCode | Read only | number | Yes | Internal version number of the application. |
| bundleVersionName | Read only | string | Yes | Version number of the application that is shown to users. |
| quickFixVersionCode | Read only | number | Yes | Version code of the quick fix patch package. |
| quickFixVersionName | Read only | string | Yes | Text description of the version number of the quick fix patch package. |
| hapModuleQuickFixInfo | Read only | Array\<[HapModuleQuickFixInfo](#hapmodulequickfixinfo)> | Yes | Quick fix information at the HAP file level. |
## quickFixManager.applyQuickFix
applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<void>): void;
Applies a quick fix patch. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | No| Quick fix files, each of which must contain a valid file path.|
| callback | AsyncCallback\<void> | No| Callback used to return the result.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"]
quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => {
if (error) {
console.info( `applyQuickFix failed with error + ${error}`)
} else {
console.info( 'applyQuickFix success')
}
})
```
## quickFixManager.applyQuickFix
applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise\<void>;
Applies a quick fix patch. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | No| Quick fix files, each of which must contain a valid file path.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"]
quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => {
console.info('applyQuickFix success')
}).catch((error) => {
console.info(`applyQuickFix err: + ${error}`)
})
```
## quickFixManager.getApplicationQuickFixInfo
getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\<ApplicationQuickFixInfo>): void;
Obtains the quick fix information of the application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | No|Bundle name of the application. |
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | No| Callback used to return the quick fix information.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let bundleName = "bundleName"
quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => {
if (error) {
console.info(`getApplicationQuickFixInfo error: + ${error}`)
} else {
console.info(`getApplicationQuickFixInfo success: + ${data}`)
}
})
```
## quickFixManager.getApplicationQuickFixInfo
getApplicationQuickFixInfo(bundleName: string): Promise\<ApplicationQuickFixInfo>;
Obtains the quick fix information of the application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | No| Bundle name of the application. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let bundleName = "bundleName"
quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => {
console.info(`getApplicationQuickFixInfo success: + ${data}`)
}).catch((error) => {
console.info(`getApplicationQuickFixInfo err: + ${error}`)
})
```
# ElementName
The **ElementName** module provides the element name information.
The **ElementName** module provides the element name information, which can be obtained through [Context.getElementName](js-apis-Context.md).
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## ElementName
## ElementName<sup>(deprecated)<sup>
**System capability**: SystemCapability.BundleManager.BundleFramework
> This API is deprecated since API version 9. You are advised to use [ElementName](js-apis-bundleManager-elementName.md) instead.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ----------------------- | ---------| ---- | ---- | ------------------------- |
| deviceId | string | Yes | Yes | Device ID. |
| bundleName | string | Yes | Yes | Bundle name of the application. |
| abilityName | string | Yes | Yes | Name of the ability. |
| uri | string | Yes | Yes | URI. |
| shortName | string | Yes | Yes | Short name of the ability. |
| moduleName<sup>9+</sup> | string | Yes | Yes | Name of the HAP file to which the ability belongs. |
| deviceId | string | Yes | Yes | Device ID. |
| bundleName | string | Yes | Yes | Bundle name of the application. |
| abilityName | string | Yes | Yes | Name of the ability. |
| uri | string | Yes | Yes | Resource ID. |
| shortName | string | Yes | Yes | Short name of the ability. |
| moduleName<sup>9+</sup> | string | Yes | Yes | Name of the HAP file to which the ability belongs. |
<!--no_check-->
\ No newline at end of file
......@@ -403,7 +403,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100.
**Example**
```js
call.formatPhoneNumber("138xxxxxxxx",{
call.formatPhoneNumber("138xxxxxxxx", {
countryCode: "CN"
}, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
......
# Color Space Management
The **colorSpaceManager** module provides APIs for creating and managing color space objects and obtaining basic color space attributes.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import colorSpaceManager from '@ohos.graphics.colorSpaceManager';
```
## ColorSpace
Enumerates the color space types.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
| Name | Value | Description |
| --------------------------- | ------ | ----------------------- |
| UNKNOWN | 0 | Unknown type.|
| ADOBE_RGB_1998 | 1 | Adobe RGB (1998).|
| DCI_P3 | 2 | DCI-P3.|
| DISPLAY_P3 | 3 | Display P3.|
| SRGB | 4 | SRGB.<br>This is the default color space type.|
| CUSTOM | 5 | Custom type.|
## ColorSpacePrimaries
Defines the color space primaries. A color space is defined by chromaticity coordinates of the red, green, and blue additive primaries, the white point, and the gamma.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
| Name | Type| Readable| Writable| Description |
| ---------------------------- | -------- | ---- | ---- | ----------------------------------------------------- |
| redX | number | Yes | Yes | X coordinate of the red color in the color space.|
| redY | number | Yes | Yes | Y coordinate of the red color in the color space.|
| greenX | number | Yes | Yes | X coordinate of the green color in the color space.|
| greenY | number | Yes | Yes | Y coordinate of the green color in the color space.|
| blueX | number | Yes | Yes | X coordinate of the blue color in the color space.|
| blueY | number | Yes | Yes | Y coordinate of the blue color in the color space.|
| whitePointX | number | Yes | Yes | X coordinate of the white point in the color space.|
| whitePointY | number | Yes | Yes | Y coordinate of the white point in the color space.|
## colorSpaceManager.create
create(colorSpaceName: ColorSpace): ColorSpaceManager
Creates a standard color space object.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Parameters**
| Parameter | Type | Mandatory| Description |
| --------------- | ------------------------ | ---- | -----------------------------|
| colorSpaceName | [ColorSpace](#colorspace)| Yes | Type of the color space.<br>**UNKNOWN** and **CUSTOM** cannot be used when creating standard color space objects. |
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| [ColorSpaceManager](#colorspacemanager) | Color space object created. |
**Example**
```js
let colorSpace = null;
try {
colorSpace = colorSpaceManager.create(colorSpaceManager.ColorSpace.SRGB);
} catch (err) {
console.log(`Failed to create SRGB colorSpace. Cause: ` + JSON.stringify(err));
}
```
## colorSpaceManager.create
create(primaries: ColorSpacePrimaries, gamma: number): ColorSpaceManager
Creates a custom color space object.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Parameters**
| Parameter | Type | Mandatory| Description |
| --------------- | ------------------------------------------ | ---- | -----------------------------|
| primaries | [ColorSpacePrimaries](#colorspaceprimaries)| Yes | Primaries of the color space. |
| gamma | number | Yes | Gamma of the color space. |
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| [ColorSpaceManager](#colorspacemanager) | Color space object created.<br>The color space type is **CUSTOM** of [ColorSpace](#colorspace).|
**Example**
```js
let colorSpace = null;
try {
let primaries = {
redX: 0.1,
redY: 0.1,
greenX: 0.2,
greenY: 0.2,
blueX: 0.3,
blueY: 0.3,
whitePointX: 0.4,
whitePointY: 0.4
};
let gamma = 2.2;
colorSpace = colorSpaceManager.create(primaries, gamma);
} catch (err) {
console.log(`Failed to create colorSpace with customized primaries and gamma. Cause: ` + JSON.stringify(err));
}
```
## ColorSpaceManager
Implements management of color space objects.
Before calling any of the following APIs, you must use [create()](#colorspacemanagercreate) to create a color space object.
### getColorSpaceName
getColorSpaceName(): ColorSpace
Obtains the color space type.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| [ColorSpace](#colorspace) | Color space type.|
**Example**
```js
try {
let csType = colorSpace.getColorSpaceName();
} catch (err) {
console.log(`Fail to get colorSpace's name. Cause: ` + JSON.stringify(err));
}
```
### getWhitePoint
getWhitePoint(): Array\<number\>
Obtains the coordinates of the white point of the color space.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| Array\<number\> | Coordinates [x, y] of the white point.|
**Example**
```js
try {
let wp = colorSpace.getWhitePoint();
} catch (err) {
console.log(`Failed to get white point. Cause: ` + JSON.stringify(err));
}
```
### getGamma
getGamma(): number
Obtains the gamma of the color space.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| number | Gamma of the color space.|
**Example**
```js
try {
let gamma = colorSpace.getGamma();
} catch (err) {
console.log(`Failed to get gamma. Cause: ` + JSON.stringify(err));
}
```
......@@ -47,10 +47,11 @@ Starts an ability with the **want** parameter. This API uses an asynchronous cal
```js
let want = {
"bundleName": "com.example.myapp",
"abilityName": "MyAbility"};
this.context.startAbility(want, (err) => {
console.log('startAbility result:' + JSON.stringify(err));
'bundleName': 'com.example.myapp',
'abilityName': 'MyAbility'
};
this.context.startAbility(want, (err) => {
console.log('startAbility result:' + JSON.stringify(err));
});
```
......@@ -79,8 +80,8 @@ Starts an ability with the mandatory **want** and optional **options** parameter
```js
let want = {
"bundleName": "com.example.myapp",
"abilityName": "MyAbility"
'bundleName': 'com.example.myapp',
'abilityName': 'MyAbility'
};
this.context.startAbility(want).then((data) => {
console.log('success:' + JSON.stringify(data));
......@@ -110,15 +111,15 @@ Starts an ability with the **want** and **options** parameters. This API uses an
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
'deviceId': '',
'bundleName': 'com.extreme.test',
'abilityName': 'MainAbility'
};
var options = {
windowMode: 0,
};
this.context.startAbility(want, options, (error) => {
console.log("error.code = " + error.code)
console.log('error.code = ' + error.code)
})
```
......@@ -140,7 +141,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re
```js
this.context.terminateSelf((err) => {
console.log('terminateSelf result:' + JSON.stringify(err));
console.log('terminateSelf result:' + JSON.stringify(err));
});
```
......
......@@ -16,7 +16,7 @@ import connection from '@ohos.net.connection'
getDefaultNet(callback: AsyncCallback\<NetHandle>): void
Obtains the default active data network. This API uses an asynchronous callback to return the result.
Obtains the default active data network. This API uses an asynchronous callback to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities.
**Required permission**: ohos.permission.GET_NETWORK_INFO
......@@ -41,7 +41,7 @@ connection.getDefaultNet(function (error, netHandle) {
getDefaultNet(): Promise\<NetHandle>
Obtains the default active data network. This API uses a promise to return the result.
Obtains the default active data network. This API uses a promise to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities.
**Required permission**: ohos.permission.GET_NETWORK_INFO
......@@ -65,7 +65,7 @@ connection.getDefaultNet().then(function (netHandle) {
getDefaultNetSync(): NetHandle;
Obtains the default active data network in synchronous mode.
Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities.
**Required permission**: ohos.permission.GET_NETWORK_INFO
......@@ -88,8 +88,7 @@ let netHandle = connection.getDefaultNetSync();
hasDefaultNet(callback: AsyncCallback\<boolean>): void
Checks whether the default data network is activated. This API uses an asynchronous callback to return the result.
The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network.
Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
**Required permission**: ohos.permission.GET_NETWORK_INFO
......@@ -114,8 +113,7 @@ connection.hasDefaultNet(function (error, has) {
hasDefaultNet(): Promise\<boolean>
Checks whether the default data network is activated. This API uses a promise to return the result.
The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network.
Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any.
**Required permission**: ohos.permission.GET_NETWORK_INFO
......
......@@ -4,6 +4,8 @@ The **Prompt** module provides APIs for creating and showing toasts, dialog boxe
> **NOTE**
>
> The APIs of this module are deprecated since API Version 9. You are advised to use [@ohos.promptAction](js-apis-promptAction.md) instead.
>
> 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
......@@ -35,6 +37,8 @@ prompt.showToast({
});
```
![en-us_image_0001](figures/en-us_image_0001.gif)
## ShowToastOptions
Describes the options for showing the toast.
......@@ -43,9 +47,9 @@ Describes the options for showing the toast.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| message | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| Yes | Text to display. |
| message | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | Yes | Text to display. |
| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.|
| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. |
| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. It does not have an upper limit. The default unit is vp. |
## prompt.showDialog
......@@ -92,6 +96,8 @@ prompt.showDialog({
})
```
![en-us_image_0002](figures/en-us_image_0002.gif)
## prompt.showDialog
showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSuccessResponse&gt;):void
......@@ -132,6 +138,8 @@ prompt.showDialog({
});
```
![en-us_image_0004](figures/en-us_image_0004.gif)
## ShowDialogOptions
Describes the options for showing the dialog box.
......@@ -140,8 +148,8 @@ Describes the options for showing the dialog box.
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| title | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| No | Title of the dialog box. |
| message | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| No | Text body. |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Title of the dialog box. |
| message | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Text body. |
| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.|
## ShowDialogSuccessResponse
......@@ -170,7 +178,6 @@ Shows an action menu. This API uses a callback to return the result asynchronous
| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. |
| callback | AsyncCallback&lt;[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.|
**Example**
```js
......@@ -195,6 +202,8 @@ prompt.showActionMenu({
})
```
![en-us_image_0005](figures/en-us_image_0005.gif)
## prompt.showActionMenu
showActionMenu(options: ActionMenuOptions): Promise&lt;ActionMenuSuccessResponse&gt;
......@@ -238,6 +247,8 @@ prompt.showActionMenu({
console.info('showActionMenu error: ' + err);
})
```
![en-us_image_0006](figures/en-us_image_0006.gif)
## ActionMenuOptions
Describes the options for showing the action menu.
......@@ -246,7 +257,7 @@ Describes the options for showing the action menu.
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| title | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| No | Title of the text to display. |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Title of the text to display. |
| buttons | Array&lt;[Button](#button)&gt; | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.|
## ActionMenuSuccessResponse
......@@ -267,5 +278,5 @@ Describes the menu item button in the action menu.
| Name | Type | Mandatory | Description |
| ----- | ---------------------------------------- | ---- | ------- |
| text | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| Yes | Button text.|
| color | string\| [Resource](../../ui/ts-types.md#resource-type)<sup>9+</sup>| Yes | Text color of the button.|
| text | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | Yes | Button text.|
| color | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | Yes | Text color of the button.|
# Prompt
The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import promptAction from '@ohos.promptAction'
```
## promptAction.showToast
showToast(options: ShowToastOptions): void
Shows a toast.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------------------------------- | ---- | ------- |
| options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.|
**Error codes**
For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
**Example**
```js
try {
promptAction.showToast({
message: 'Message Info',
duration: 2000,
});
} catch (error) {
console.error(`showToast args error code is ${error.code}, message is ${error.message}`);
};
```
![en-us_image_0001](figures/en-us_image_0001.gif)
## ShowToastOptions
Describes the options for showing the toast.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| message | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| Yes | Text to display. |
| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.|
| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. |
## promptAction.showDialog
showDialog(options: ShowDialogOptions): Promise&lt;ShowDialogSuccessResponse&gt;
Shows a dialog box. This API uses a promise to return the result synchronously.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | --------------------------------------- | ---- | ------ |
| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.|
**Return value**
| Type | Description |
| ---------------------------------------- | -------- |
| Promise&lt;[ShowDialogSuccessResponse](#showdialogsuccessresponse)&gt; | Promise used to return the dialog box response result.|
**Error codes**
For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
**Example**
```js
try {
promptAction.showDialog({
title: 'Title Info',
message: 'Message Info',
buttons: [
{
text: 'button1',
color: '#000000',
},
{
text: 'button2',
color: '#000000',
}
],
})
.then(data => {
console.info('showDialog success, click button: ' + data.index);
})
.catch(err => {
console.info('showDialog error: ' + err);
})
} catch (error) {
console.error(`showDialog args error code is ${error.code}, message is ${error.message}`);
};
```
![en-us_image_0002](figures/en-us_image_0002.gif)
## promptAction.showDialog
showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSuccessResponse&gt;):void
Shows a dialog box. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------ |
| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.|
| callback | AsyncCallback&lt;[ShowDialogSuccessResponse](#showdialogsuccessresponse)&gt; | Yes | Callback used to return the dialog box response result. |
**Error codes**
For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
**Example**
```js
try {
promptAction.showDialog({
title: 'showDialog Title Info',
message: 'Message Info',
buttons: [
{
text: 'button1',
color: '#000000',
},
{
text: 'button2',
color: '#000000',
}
]
}, (err, data) => {
if (err) {
console.info('showDialog err: ' + err);
return;
}
console.info('showDialog success callback, click button: ' + data.index);
});
} catch (error) {
console.error(`showDialog args error code is ${error.code}, message is ${error.message}`);
};
```
![en-us_image_0002](figures/en-us_image_0002.gif)
## ShowDialogOptions
Describes the options for showing the dialog box.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| No | Title of the dialog box. |
| message | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| No | Text body. |
| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.|
## ShowDialogSuccessResponse
Describes the dialog box response result.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Description |
| ----- | ------ | ------------------- |
| index | number | Index of the selected button in the **buttons** array.|
## promptAction.showActionMenu
showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenuSuccessResponse&gt;):void
Shows an action menu. This API uses a callback to return the result asynchronously.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------- |
| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. |
| callback | AsyncCallback&lt;[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.|
**Error codes**
For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
**Example**
```js
try {
promptAction.showActionMenu({
title: 'Title Info',
buttons: [
{
text: 'item1',
color: '#666666',
},
{
text: 'item2',
color: '#000000',
},
]
}, (err, data) => {
if (err) {
console.info('showActionMenu err: ' + err);
return;
}
console.info('showActionMenu success callback, click button: ' + data.index);
})
} catch (error) {
console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`);
};
```
![en-us_image_0005](figures/en-us_image_0005.gif)
## promptAction.showActionMenu
showActionMenu(options: ActionMenuOptions): Promise&lt;ActionMenuSuccessResponse&gt;
Shows an action menu. This API uses a promise to return the result synchronously.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | --------------------------------------- | ---- | ------- |
| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise&lt;[ActionMenuSuccessResponse](#actionmenusuccessresponse)&gt; | Promise used to return the action menu response result.|
**Error codes**
For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md).
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
**Example**
```js
try {
promptAction.showActionMenu({
title: 'showActionMenu Title Info',
buttons: [
{
text: 'item1',
color: '#666666',
},
{
text: 'item2',
color: '#000000',
},
]
})
.then(data => {
console.info('showActionMenu success, click button: ' + data.index);
})
.catch(err => {
console.info('showActionMenu error: ' + err);
})
} catch (error) {
console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`);
};
```
![en-us_image_0005](figures/en-us_image_0005.gif)
## ActionMenuOptions
Describes the options for showing the action menu.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| No | Title of the dialog box. |
| buttons | Array&lt;[Button](#button)&gt; | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.|
## ActionMenuSuccessResponse
Describes the action menu response result.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ------------------------ |
| index | number | No | Index of the selected button in the **buttons** array, starting from **0**.|
## Button
Describes the menu item button in the action menu.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ----- | ---------------------------------------- | ---- | ------- |
| text | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| Yes | Button text.|
| color | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| Yes | Text color of the button.|
......@@ -1840,10 +1840,10 @@ Defines the network status.
| Name | Value | Description |
| ----------------------------- | ---- | -------------------------- |
| REG_STATE_NO_SERVICE | 0 | The device cannot use any service. |
| REG_STATE_IN_SERVICE | 1 | The device can use services normally. |
| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service.|
| REG_STATE_POWER_OFF | 3 | The cellular radio service is disabled. |
| REG_STATE_NO_SERVICE | 0 | The device cannot use any services, including data, SMS, and call services. |
| REG_STATE_IN_SERVICE | 1 | The device can use services properly, including data, SMS, and call services. |
| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service. |
| REG_STATE_POWER_OFF | 3 | The device cannot communicate with the network because the cellular radio service is disabled or the modem is powered off. |
## NsaState
......
......@@ -73,7 +73,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async
**Example**
```js
var screenshotOptions = {
let screenshotOptions = {
"screenRect": {
"left": 200,
"top": 100,
......@@ -85,14 +85,18 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async
"rotation": 0,
"displayId": 0
};
screenshot.save(screenshotOptions, (err, pixelMap) => {
if (err) {
console.log('Failed to save screenshot: ' + JSON.stringify(err));
return;
}
console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // Release the memory in time after the PixelMap is used.
});
try {
screenshot.save(screenshotOptions, (err, pixelMap) => {
if (err) {
console.log('Failed to save screenshot. Code: ' + JSON.stringify(err));
return;
}
console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // Release the memory in time after the PixelMap is used.
});
} catch (exception) {
console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception));
};
```
## screenshot.save
......@@ -114,14 +118,18 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async
**Example**
```js
screenshot.save((err, pixelMap) => {
if (err) {
console.log('Failed to save screenshot: ' + JSON.stringify(err));
return;
}
console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // Release the memory in time after the PixelMap is used.
});
try {
screenshot.save((err, pixelMap) => {
if (err) {
console.log('Failed to save screenshot. Code: ' + JSON.stringify(err));
return;
}
console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // Release the memory in time after the PixelMap is used.
});
} catch (exception) {
console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception));
};
```
## screenshot.save
......@@ -149,7 +157,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis
**Example**
```js
var screenshotOptions = {
let screenshotOptions = {
"screenRect": {
"left": 200,
"top": 100,
......@@ -161,11 +169,15 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis
"rotation": 0,
"displayId": 0
};
let promise = screenshot.save(screenshotOptions);
promise.then((pixelMap) => {
console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // Release the memory in time after the PixelMap is used.
}).catch((err) => {
console.log('Failed to save screenshot: ' + JSON.stringify(err));
});
try {
let promise = screenshot.save(screenshotOptions);
promise.then((pixelMap) => {
console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // Release the memory in time after the PixelMap is used.
}).catch((err) => {
console.log('Failed to save screenshot. Code: ' + JSON.stringify(err));
});
} catch (exception) {
console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception));
};
```
......@@ -689,7 +689,7 @@ promise.then(data => {
## sim.**setShowName**<sup>8+</sup>
setShowName\(slotId: number, name: string,callback: AsyncCallback<void\>\): void
setShowName\(slotId: number, name: string, callback: AsyncCallback<void\>\): void
Sets a display name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
......@@ -710,7 +710,7 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy
**Example**
```js
let name = 'China Mobile';
let name = "China Mobile";
sim.setShowName(0, name, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
......@@ -744,7 +744,7 @@ Sets a display name for the SIM card in the specified slot. This API uses a prom
**Example**
```js
let name = 'China Mobile';
let name = "China Mobile";
let promise = sim.setShowName(0, name);
promise.then(data => {
console.log(`setShowName success, promise: data->${JSON.stringify(data)}`);
......@@ -818,7 +818,7 @@ promise.then(data => {
## sim.**setShowNumber**<sup>8+</sup>
setShowNumber\(slotId: number, number: string,callback: AsyncCallback<void\>\): void
setShowNumber\(slotId: number, number: string, callback: AsyncCallback<void\>\): void
Sets a display number for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
......@@ -848,7 +848,7 @@ sim.setShowNumber(0, number, (err, data) => {
## sim.**setShowNumber**<sup>8+</sup>
setShowNumber\(slotId: number,number: string\): Promise\<void\>
setShowNumber\(slotId: number, number: string\): Promise\<void\>
Sets a display number for the SIM card in the specified slot. This API uses a promise to return the result.
......@@ -885,7 +885,7 @@ promise.then(data => {
## sim.**getShowNumber**<sup>8+</sup>
getShowNumber(slotId: number,callback: AsyncCallback<string\>): void
getShowNumber(slotId: number, callback: AsyncCallback<string\>): void
Obtains the display number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
......@@ -1097,7 +1097,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses an asy
```js
let lockInfo = {
lockType: sim.LockType.PIN_LOCK,
password = "1234",
password: "1234",
state: sim.LockState.LOCK_OFF
};
sim.setLockState(0, lockInfo, (err, data) => {
......@@ -1136,7 +1136,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom
```js
let lockInfo = {
lockType: sim.LockType.PIN_LOCK,
password = "1234",
password: "1234",
state: sim.LockState.LOCK_OFF
};
let promise = sim.setLockState(0, lockInfo);
......@@ -1344,7 +1344,7 @@ promise.then(data => {
## sim.**unlockPin**<sup>7+</sup>
unlockPin(slotId: number,pin: string ,callback: AsyncCallback<LockStatusResponse\>): void
unlockPin(slotId: number, pin: string, callback: AsyncCallback<LockStatusResponse\>): void
Unlocks PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
......@@ -1374,7 +1374,7 @@ sim.unlockPin(0, pin, (err, data) => {
## sim.**unlockPin**<sup>7+</sup>
unlockPin(slotId: number,pin: string): Promise&lt;LockStatusResponse\>
unlockPin(slotId: number, pin: string): Promise&lt;LockStatusResponse\>
Unlocks the PIN of the SIM card in the specified slot. This API uses a promise to return the result.
......@@ -1411,7 +1411,7 @@ promise.then(data => {
## sim.**unlockPuk**<sup>7+</sup>
unlockPuk(slotId: number,newPin: string,puk: string ,callback: AsyncCallback<LockStatusResponse\>): void
unlockPuk(slotId: number, newPin: string, puk: string ,callback: AsyncCallback<LockStatusResponse\>): void
Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
......@@ -1443,7 +1443,7 @@ sim.unlockPuk(0, newPin, puk, (err, data) => {
## sim.**unlockPuk**<sup>7+</sup>
unlockPuk(slotId: number,newPin: string,puk: string): Promise&lt;LockStatusResponse\>
unlockPuk(slotId: number, newPin: string, puk: string): Promise&lt;LockStatusResponse\>
Unlocks the PUK of the SIM card in the specified slot. This API uses a promise to return the result.
......@@ -1482,7 +1482,7 @@ promise.then(data => {
## sim.**unlockPin**2<sup>8+</sup>
unlockPin2(slotId: number,pin2: string ,callback: AsyncCallback<LockStatusResponse\>): void
unlockPin2(slotId: number, pin2: string, callback: AsyncCallback<LockStatusResponse\>): void
Unlocks PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
......@@ -1512,7 +1512,7 @@ sim.unlockPin2(0, pin2, (err, data) => {
## sim.**unlockPin**2<sup>8+</sup>
unlockPin2(slotId: number,pin2: string): Promise&lt;LockStatusResponse\>
unlockPin2(slotId: number, pin2: string): Promise&lt;LockStatusResponse\>
Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result.
......@@ -1539,7 +1539,7 @@ Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to
```js
let pin2='1234';
let promise = sim.unlockPin2(0,pin2);
let promise = sim.unlockPin2(0, pin2);
promise.then(data => {
console.log(`unlockPin2 success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
......@@ -1851,7 +1851,7 @@ Sets voice mailbox information for the SIM card in the specified slot. This API
**Example**
```js
sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com" , (err, data) => {
sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com", (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
......@@ -2602,8 +2602,8 @@ Unlocks the SIM card in the specified slot. This API uses an asynchronous callba
```js
let persoLockInfo = {
lockType = sim.PersoLockType.PN_PIN_LOCK,
password = "1234"
lockType: sim.PersoLockType.PN_PIN_LOCK,
password: "1234"
};
sim.unlockSimLock(0, persoLockInfo, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
......@@ -2640,8 +2640,8 @@ Unlocks the SIM card in the specified slot. This API uses a promise to return th
```js
let persoLockInfo = {
lockType = sim.PersoLockType.PN_PIN_LOCK,
password = "1234"
lockType: sim.PersoLockType.PN_PIN_LOCK,
password: "1234"
};
let promise = sim.unlockSimLock(0, persoLockInfo);
promise.then(data => {
......
......@@ -160,7 +160,7 @@ promise.then(data => {
## sms.setDefaultSmsSlotId<sup>7+</sup>
setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback&lt;void&gt;\): void
setDefaultSmsSlotId\(slotId: number, callback: AsyncCallback&lt;void&gt;\): void
Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result.
......@@ -180,7 +180,7 @@ Sets the default slot of the SIM card used to send SMS messages. This API uses a
**Example**
```js
sms.setDefaultSmsSlotId(0,(err, data) => {
sms.setDefaultSmsSlotId(0, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
......@@ -610,8 +610,8 @@ let updateSimMessageOptions = {
slotId: 0,
msgIndex: 1,
newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE,
pdu = "xxxxxxx",
smsc = "test"
pdu: "xxxxxxx",
smsc: "test"
};
sms.updateSimMessage(updateSimMessageOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
......@@ -650,8 +650,8 @@ let updateSimMessageOptions = {
slotId: 0,
msgIndex: 1,
newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE,
pdu = "xxxxxxx",
smsc = "test"
pdu: "xxxxxxx",
smsc: "test"
};
let promise = sms.updateSimMessage(updateSimMessageOptions);
promise.then(data => {
......@@ -1054,13 +1054,13 @@ Encodes MMS messages. This API uses an asynchronous callback to return the resul
```js
let mmsAcknowledgeInd = {
transactionId = "100",
version = 0x10,
reportAllowed = 128
transactionId: "100",
version: sms.MmsVersionType.MMS_VERSION_1_0,
reportAllowed: sms.ReportType.MMS_YES
};
let mmsInformation = {
messageType = 133,
mmsType = mmsAcknowledgeInd
messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND,
mmsType: mmsAcknowledgeInd
};
sms.encodeMms(mmsInformation, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
......@@ -1096,10 +1096,10 @@ Encodes MMS messages. This API uses a promise to return the result.
let mmsAcknowledgeInd = {
transactionId: "100",
version: sms.MmsVersionType.MMS_VERSION_1_0,
reportAllowed = sms.ReportType.MMS_YES
reportAllowed: sms.ReportType.MMS_YES
};
let mmsInformation = {
messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND,
messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND,
mmsType: mmsAcknowledgeInd
};
let promise = sms.encodeMms(mmsInformation);
......
......@@ -88,7 +88,7 @@ console.log("Result: "+ data.getDefaultCellularDataSlotIdSync())
## data.setDefaultCellularDataSlotId
setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\<void\>): void
setDefaultCellularDataSlotId(slotId: number, callback: AsyncCallback\<void\>): void
Sets the default slot of the SIM card used for mobile data. This API uses an asynchronous callback to return the result.
......@@ -108,7 +108,7 @@ This is a system API.
**Example**
```js
data.setDefaultCellularDataSlotId(0,(err, data) => {
data.setDefaultCellularDataSlotId(0, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
......@@ -313,7 +313,7 @@ Checks whether the cellular data roaming service is enabled. This API uses an as
**Example**
```js
data.isCellularDataRoamingEnabled(0,(err, data) => {
data.isCellularDataRoamingEnabled(0, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
......
......@@ -59,7 +59,9 @@ Sets an attribute.
let arrayBuffer = new ArrayBuffer(1024);
let bufView = new DataView(arrayBuffer);
let thatSer = new xml.XmlSerializer(bufView);
thatSer.setAttributes("importance", "high");
thatSer.startElement("note");
thatSer.setAttributes("importance", "high");
thatSer.endElement();
```
......
# Zip
> **NOTE**
>
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Constraints
......@@ -30,9 +30,9 @@ Zips a file. This API uses a promise to return the result.
**Return value**
| Type | Description |
| -------------- | ---------------------------------------------------- |
| Promise\<void> | Returns **ERROR_CODE_OK** if the operation is successful; returns **ERROR_CODE_ERRNO** otherwise.|
| Type | Description |
| -------------- | ------------------------------------------------------------ |
| Promise\<void> | Returns [ERROR_CODE_OK](#ziperrorcode) if the operation is successful.<br>Returns [ERROR_CODE_ERRNO](#ziperrorcode) if the operation fails.|
**Example 1**
......@@ -96,7 +96,7 @@ Unzips a file. This API uses a promise to return the result.
| Type | Description |
| -------------- | ------------------------------------------------------------ |
| Promise\<void> | Returns **ERROR_CODE_OK** if the operation is successful; returns **ERROR_CODE_ERRNO** otherwise.|
| Promise\<void> | Returns [ERROR_CODE_OK](#ziperrorcode) if the operation is successful.<br>Returns [ERROR_CODE_ERRNO](#ziperrorcode) if the operation fails.|
**Example**
......
......@@ -137,9 +137,9 @@
| Name | Description |
| -------- | ---------------------- |
| Top | Top edge in the vertical direction. |
| Center<sup>(deprecated) </sup> | Center position in the vertical direction.<br> This API is deprecated since API version 9. |
| Center<sup>(deprecated) </sup> | Center position in the vertical direction.<br>This API is deprecated since API version 9. |
| Bottom | Bottom edge in the vertical direction. |
| Baseline<sup>(deprecated) </sup> | Text baseline position in the cross axis direction.<br> This API is deprecated since API version 9.|
| Baseline<sup>(deprecated) </sup> | Text baseline position in the cross axis direction.<br>This API is deprecated since API version 9. |
| Start | Start position in the horizontal direction. |
| Middle<sup>(deprecated) </sup> | Center position in the horizontal direction.<br>This API is deprecated since API version 9. |
| End | End position in the horizontal direction. |
......@@ -249,7 +249,7 @@
| End | The child components are aligned with the end edge of the main axis. The last component is aligned with the main-end, and other components are aligned with the next one.|
| SpaceBetween | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The first component is aligned with the main-start, the last component is aligned with the main-end, and the remaining components are distributed so that the space between any two adjacent components is the same.|
| SpaceAround | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The space between the first component and main-start, and that between the last component and cross-main are both half the size of the space between two adjacent components.|
| SpaceEvenly | The child components are equally distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between two adjacent components are the same.|
| SpaceEvenly | The child components are evenly distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between any two adjacent components are the same. |
## ItemAlign
......@@ -355,9 +355,9 @@
| Name | Description |
| -------- | -------------------------------------- |
| Clip | Extra-long text is truncated. |
| Clip | Extra-long text is clipped. |
| Ellipsis | An ellipsis (...) is used to represent clipped text.|
| None | No truncation or ellipsis is used for extra-long text. |
| None | No clipping or ellipsis is used for extra-long text. |
## TextDecorationType
......@@ -413,9 +413,9 @@
| Name | Description |
| ----------- | -------------------- |
| None | Copy and paste is not allowed. |
| InApp | Intra-application copy and paste is allowed.|
| LocalDevice | Intra-device copy and paste is allowed.|
| None | Copy is not allowed. |
| InApp | Intra-application copy is allowed.|
| LocalDevice | Intra-device copy is allowed.|
## HitTestMode<sup>9+</sup>
......
......@@ -10,10 +10,10 @@ You can set the background of a component.
| Name| Type| Description|
| -------- | -------- | -------- |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component. |
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Background image of the component.<br>**src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)<br>**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used. |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.|
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)<br>**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used.|
| backgroundImageSize | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.<br>Default value: **ImageSize.Auto**|
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.<br>Default value:<br>**{<br>x: 0,<br>y: 0<br>}** |
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} <br> When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.|
## Example
......
......@@ -11,8 +11,8 @@ Layout constraints refer to constraints on the aspect ratio and display priority
| Name | Type | Description |
| --------------- | ------ | ---------------------------------------- |
| aspectRatio | number | Aspect ratio of the component. |
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components.|
| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height. |
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components. |
## Example
......@@ -22,29 +22,32 @@ Layout constraints refer to constraints on the aspect ratio and display priority
@Entry
@Component
struct AspectRatioExample {
private children : string[] = ['1', '2', '3', '4', '5', '6']
private children: string[] = ['1', '2', '3', '4', '5', '6']
build() {
Column({space: 20}) {
Column({ space: 20 }) {
Text('using container: row').fontSize(14).fontColor(0xCCCCCC).width('100%')
Row({space: 10}) {
Row({ space: 10 }) {
ForEach(this.children, (item) => {
// Component width = Component height x 1.5 = 90
Text(item)
.backgroundColor(0xbbb2cb)
.fontSize(20)
.aspectRatio(1.5)
.height(60)
// Component height = Component width/1.5 = 60/1.5 = 40
Text(item)
.backgroundColor(0xbbb2cb)
.fontSize(20)
.aspectRatio(1.5)
.width(60)
}, item=>item)
}, item => item)
}
.size({width: "100%", height: 100})
.size({ width: "100%", height: 100 })
.backgroundColor(0xd2cab3)
.clip(true)
// Grid child component width/height = 3/2
Text('using container: grid').fontSize(14).fontColor(0xCCCCCC).width('100%')
Grid() {
ForEach(this.children, (item) => {
......@@ -54,12 +57,12 @@ struct AspectRatioExample {
.fontSize(40)
.aspectRatio(1.5)
}
}, item=>item)
}, item => item)
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.size({width: "100%", height: 165})
.size({ width: "100%", height: 165 })
.backgroundColor(0xd2cab3)
}.padding(10)
}
......@@ -67,47 +70,53 @@ struct AspectRatioExample {
```
**Figure 1** Portrait display
![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif)
**Figure 2** Landscape display
![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif)
```ts
class ContainerInfo {
label : string = ''
size : string = ''
label: string = '';
size: string = '';
}
class ChildInfo {
text : string = ''
priority : number = 0
text: string = '';
priority: number = 0;
}
@Entry
@Component
struct DisplayPriorityExample {
private container : ContainerInfo[] = [
{label: 'Big container', size: '90%'},
{label: 'Middle container', size: '50%'},
{label: 'Small container', size: '30%'}
// Display the container size.
private container: ContainerInfo[] = [
{ label: 'Big container', size: '90%' },
{ label: 'Middle container', size: '50%' },
{ label: 'Small container', size: '30%' }
]
private children : ChildInfo[] = [
{text: '1\n(priority:2)', priority: 2},
{text: '2\n(priority:1)', priority: 1},
{text: '3\n(priority:3)', priority: 3},
{text: '4\n(priority:1)', priority: 1},
{text: '5\n(priority:2)', priority: 2}
private children: ChildInfo[] = [
{ text: '1\n(priority:2)', priority: 2 },
{ text: '2\n(priority:1)', priority: 1 },
{ text: '3\n(priority:3)', priority: 3 },
{ text: '4\n(priority:1)', priority: 1 },
{ text: '5\n(priority:2)', priority: 2 }
]
@State currentIndex : number = 0
@State currentIndex: number = 0;
build() {
Column({space: 10}) {
Column({ space: 10 }) {
// Switch the size of the parent container.
Button(this.container[this.currentIndex].label).backgroundColor(0x317aff)
.onClick((event: ClickEvent) => {
this.currentIndex = (this.currentIndex + 1) % this.container.length
.onClick(() => {
this.currentIndex = (this.currentIndex + 1) % this.container.length;
})
Flex({justifyContent: FlexAlign.SpaceBetween}) {
ForEach(this.children, (item)=>{
// Set the width for the parent flex container through variables.
Flex({ justifyContent: FlexAlign.SpaceBetween }) {
ForEach(this.children, (item) => {
// Bind the display priority to the child component through displayPriority.
Text(item.text)
.width(120)
.height(60)
......@@ -115,11 +124,11 @@ struct DisplayPriorityExample {
.textAlign(TextAlign.Center)
.backgroundColor(0xbbb2cb)
.displayPriority(item.priority)
}, item=>item.text)
}, item => item.text)
}
.width(this.container[this.currentIndex].size)
.backgroundColor(0xd2cab3)
}.width("100%").margin({top:50})
}.width("100%").margin({ top: 50 })
}
}
......
......@@ -8,10 +8,9 @@ You can set overlay text for a component.
## Attributes
| Name | Type | Description |
| ------- | ----------------------------- | ------------------------- |
| overlay | value: string,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {<br> x?: number,<br> y?: number<br> }<br>} | Overlay added to the component. The overlay has the same layout as the component.<br>Default value:<br>{<br>align: Alignment.Center,<br>offset: {0, 0}<br>} |
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| overlay | value: string,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {x?: number, y?: number}<br>} | {<br>align: Alignment.Center,<br>offset: {0, 0}<br>} | Overlay added to the component.<br> **value**: mask text.<br>**options**: text positioning. **align** indicates the location of the text relative to the component. **[offset](ts-universal-attributes-location.md)** indicates the offset of the text relative to the upper left corner of itself. By default, the text is in the upper left corner of the component.<br>If both **align** and **offset** are set, the text is first positioned relative to the component, and then offset relative to the upper left corner of itself.|
## Example
......@@ -28,7 +27,10 @@ struct OverlayExample {
Column() {
Image($r('app.media.img'))
.width(240).height(240)
.overlay("Winter is a beautiful season, especially when it snows.", { align: Alignment.Bottom, offset: { x: 0, y: -15 } })
.overlay("Winter is a beautiful season, especially when it snows.", {
align: Alignment.Bottom,
offset: { x: 0, y: -15 }
})
}.border({ color: Color.Black, width: 2 })
}.width('100%')
}.padding({ top: 20 })
......
# Size
The size attributes are used to set the width, height, padding, and margin of a component.
The size attributes set the width, height, and margin of a component.
> **NOTE**
>
......@@ -16,9 +16,9 @@ The size attributes are used to set the width, height, padding, and margin of a
| 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. |
| size | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} | Size of the component. |
| 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.|
| 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.|
| 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.|
| 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**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>} |
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>Default value: **0**|
| 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>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.|
## Example
......@@ -31,30 +31,41 @@ struct SizeExample {
build() {
Column({ space: 10 }) {
Text('margin and padding:').fontSize(12).fontColor(0xCCCCCC).width('90%')
// The width is 80, the height is 80, the padding is 20, and the margin is 20.
Row() {
// Width: 80; height: 80; margin: 20 (blue area); padding: 10 (white area)
Row() {
Row().size({ width: '100%', height: '100%' }).backgroundColor(0xAFEEEE)
}.width(80).height(80).padding(20).margin(20).backgroundColor(0xFDF5E6)
}.backgroundColor(0xFFA500)
Row().size({ width: '100%', height: '100%' }).backgroundColor(Color.Yellow)
}
.width(80)
.height(80)
.padding(10)
.margin(20)
.backgroundColor(Color.White)
}.backgroundColor(Color.Blue)
Text('constraintSize').fontSize(12).fontColor(0xCCCCCC).width('90%')
Text('this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text')
.width('90%')
.constraintSize({ maxWidth: 200 })
Text('layoutWeight').fontSize(12).fontColor(0xCCCCCC).width('90%')
// When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored.
// When the container size is determined, the component occupies the space along the main axis based on the layout weight, and the component size setting is ignored.
Row() {
// Weight 1
// Weight 1: The component occupies 1/3 of the remaining space along the main axis.
Text('layoutWeight(1)')
.size({ width: '30%', height: 110 }).backgroundColor(0xFFEFD5).textAlign(TextAlign.Center)
.layoutWeight(1)
// Weight 2
// Weight 2: The component occupies 2/3 of the remaining space along the main axis.
Text('layoutWeight(2)')
.size({ width: '30%', height: 110 }).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.layoutWeight(2)
// The default weight is 0.
// If layoutWeight is not set, the component is rendered based on its own size setting.
Text('no layoutWeight')
.size({ width: '30%', height: 110 }).backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
}.size({ width: '90%', height: 140 }).backgroundColor(0xAFEEEE)
}.width('100%').margin({ top: 5 })
}}
}
}
```
![en-us_image_0000001257138367](figures/en-us_image_0000001257138367.gif)
![size](figures/size.png)
......@@ -10,7 +10,7 @@ The visibility attribute controls whether a component is visible.
| Name | Type | Description |
| ---------- | ---------------------------- | ------------------------------------------ |
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is hidden, it needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../ui/ts-rending-control-syntax-if-else.md) instead under scenarios where consistently high performance is required.<br>Default value: **Visibility.Visible**|
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is invisible, it still needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../quick-start/arkts-rendering-control.md#conditional-rendering) instead under scenarios where consistently high performance is required.<br>Default value: **Visibility.Visible**|
## Example
......@@ -23,20 +23,21 @@ struct VisibilityExample {
build() {
Column() {
Column() {
Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE)
Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC)
// The component is hidden, and no placeholder is used.
Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.None).width('90%').height(80).backgroundColor(0xAFEEEE)
Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC)
// The component is hidden, and a placeholder is used for it in the layout.
Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Hidden).width('90%').height(80).backgroundColor(0xAFEEEE)
// The component is visiable, which is the default display mode.
Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC)
Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE)
}.width('90%').border({ width: 1 })
}.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001257058421](figures/en-us_image_0000001257058421.gif)
![visibility.png](figures/visibility.png)
......@@ -2,8 +2,9 @@
- Access Control
- [Access Control (Permission) Overview](accesstoken-overview.md)
- [Guide for Requesting Permissions from User](accesstoken-guidelines.md)
- [Application Permission List](permission-list.md)
- [Permission Application Guide](accesstoken-guidelines.md)
- [Permission Verification Guide](permission-verify-guidelines.md)
- [App Permission List](permission-list.md)
- User Authentication
- [User Authentication Overview](userauth-overview.md)
- [User Authentication Development](userauth-guidelines.md)
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册