提交 5119bf21 编写于 作者: S shawn_he 提交者: Gitee

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

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
...@@ -132,7 +132,7 @@ zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 ...@@ -132,7 +132,7 @@ zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23
zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/IDL/ @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/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua
zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids
zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee
...@@ -244,7 +244,7 @@ zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease ...@@ -244,7 +244,7 @@ zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease
zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/faqs/ @zengyawen
zh-cn/application-dev/file-management/ @zengyawen zh-cn/application-dev/file-management/ @zengyawen
zh-cn/application-dev/application-test/ @ningningW zh-cn/application-dev/application-test/ @ningningW
zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-ability-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-ability-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
...@@ -275,10 +275,12 @@ zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @little ...@@ -275,10 +275,12 @@ zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @little
zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-application-Want.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-Want.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/application-models/windowextensionability.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids
zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208
...@@ -331,7 +333,7 @@ zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao ...@@ -331,7 +333,7 @@ zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao
zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @zengyawen @JiDong-CS @murphy1984 zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @zengyawen @JiDong-CS @murphy1984
zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids
...@@ -476,8 +478,9 @@ zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih ...@@ -476,8 +478,9 @@ zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih
zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15
...@@ -537,10 +540,10 @@ zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @ze ...@@ -537,10 +540,10 @@ zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @ze
zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-system-capability.md taiyipei taiyipei BlackStone zh-cn/application-dev/reference/apis/js-apis-system-capability.md taiyipei taiyipei BlackStone
zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
- master:最新开发版本。 - master:最新开发版本。
- OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。 - OpenHarmony 3.2 Beta5版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta5.md)了解版本详情。
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
......
...@@ -67,7 +67,7 @@ This topic describes how to use the context in the following scenarios: ...@@ -67,7 +67,7 @@ This topic describes how to use the context in the following scenarios:
- [Obtaining the Application Development Path](#obtaining-the-application-development-path) - [Obtaining the Application Development Path](#obtaining-the-application-development-path)
- [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas) - [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas)
- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module) - [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module)
- [Subscribing to Ability Lifecycle Changes in a Process](#subscribing-to-ability-lifecycle-changes-in-a-process) - [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process)
### Obtaining the Application Development Path ### Obtaining the Application Development Path
...@@ -108,7 +108,7 @@ The capability of obtaining the application development path is provided by the ...@@ -108,7 +108,7 @@ The capability of obtaining the application development path is provided by the
| bundleCodeDir | {Path prefix}/el1/bundle/| | bundleCodeDir | {Path prefix}/el1/bundle/|
| cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/| | cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/|
| filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/| | filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/|
| preferencesDir | {path prefix}/{encryption level}/base/**haps/{moduleName}**/preferences/| | preferencesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/preferences/|
| tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/| | tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/|
| databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/| | databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/|
| distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/| | distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/|
...@@ -133,6 +133,9 @@ export default class EntryAbility extends UIAbility { ...@@ -133,6 +133,9 @@ export default class EntryAbility extends UIAbility {
} }
``` ```
> **NOTE**
>
> The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name <fileName>** command in the hdc shell after file creation or modification.
### Obtaining and Modifying Encrypted Areas ### Obtaining and Modifying Encrypted Areas
...@@ -173,9 +176,9 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -173,9 +176,9 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> To obtain the context of another application: > To obtain the context of another application:
> >
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
> >
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon. For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon.
```ts ```ts
...@@ -189,17 +192,17 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -189,17 +192,17 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
// ... // ...
} }
} }
``` ```
- Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module. - Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module.
> **NOTE** > **NOTE**
> >
> To obtain the context of a specified module of another application: > To obtain the context of a specified module of another application:
> >
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
> >
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -228,11 +231,11 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -228,11 +231,11 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
``` ```
### Subscribing to Ability Lifecycle Changes in a Process ### Subscribing to UIAbility Lifecycle Changes in a Process
In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to ability lifecycle changes. In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to UIAbility lifecycle changes.
When the ability lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered, and a listener ID is returned. The ID is incremented by 1 each time the listener is registered. When the number of listeners exceeds the upper limit (2^63-1), -1 is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example. [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) provides APIs for subscribing to UIAbility lifecycle changes in a process. When the UIAbility lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered, and a listener ID is returned. The ID is incremented by 1 each time the listener is registered. When the number of listeners exceeds the upper limit (2^63-1), -1 is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example.
```ts ```ts
...@@ -246,36 +249,36 @@ export default class EntryAbility extends UIAbility { ...@@ -246,36 +249,36 @@ export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityCreate(ability) { onAbilityCreate(uiability) {
console.info(TAG, "onAbilityCreate ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityCreate uiability:" + JSON.stringify(uiability));
}, },
onWindowStageCreate(ability, windowStage) { onWindowStageCreate(uiability, windowStage) {
console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability)); console.info(TAG, "onWindowStageCreate uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
}, },
onWindowStageActive(ability, windowStage) { onWindowStageActive(uiability, windowStage) {
console.info(TAG, "onWindowStageActive ability:" + JSON.stringify(ability)); console.info(TAG, "onWindowStageActive uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage)); console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage));
}, },
onWindowStageInactive(ability, windowStage) { onWindowStageInactive(uiability, windowStage) {
console.info(TAG, "onWindowStageInactive ability:" + JSON.stringify(ability)); console.info(TAG, "onWindowStageInactive uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
}, },
onWindowStageDestroy(ability, windowStage) { onWindowStageDestroy(uiability, windowStage) {
console.info(TAG, "onWindowStageDestroy ability:" + JSON.stringify(ability)); console.info(TAG, "onWindowStageDestroy uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
}, },
onAbilityDestroy(ability) { onAbilityDestroy(uiability) {
console.info(TAG, "onAbilityDestroy ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityDestroy uiability:" + JSON.stringify(uiability));
}, },
onAbilityForeground(ability) { onAbilityForeground(uiability) {
console.info(TAG, "onAbilityForeground ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityForeground uiability:" + JSON.stringify(uiability));
}, },
onAbilityBackground(ability) { onAbilityBackground(uiability) {
console.info(TAG, "onAbilityBackground ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityBackground uiability:" + JSON.stringify(uiability));
}, },
onAbilityContinue(ability) { onAbilityContinue(uiability) {
console.info(TAG, "onAbilityContinue ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityContinue uiability:" + JSON.stringify(uiability));
} }
} }
// 1. Obtain the application context through the context attribute. // 1. Obtain the application context through the context attribute.
......
...@@ -21,8 +21,7 @@ The following figure shows the basic concepts used in the stage model. ...@@ -21,8 +21,7 @@ The following figure shows the basic concepts used in the stage model.
- [Context](application-context-stage.md) - [Context](application-context-stage.md)
In the stage model, Context and its derived classes provide a variety of capabilities that can be called during the runtime. The UIAbility component and ExtensionAbility derived classes have different Context classes. These classes, which all inherit from the base class Context, provide different capabilities. In the stage model, Context and its derived classes provide a variety of resources and capabilities that can be called during the runtime. The UIAbility component and ExtensionAbility derived classes have different Context classes. These classes, which all inherit from the base class Context, provide different capabilities.
- [AbilityStage](abilitystage.md) - [AbilityStage](abilitystage.md)
Each HAP of the Entry or Feature type has an AbilityStage class instance during the runtime. When the code in the HAP is loaded to the process for the first time, the system creates an AbilityStage class instance first. Each UIAbility class defined in the HAP is associated with this class instance after instantiation. Through this class instance, you can obtain the runtime information of the UIAbility instances in the HAP. Each HAP of the Entry or Feature type has an AbilityStage class instance during the runtime. When the code in the HAP is loaded to the process for the first time, the system creates an AbilityStage class instance first. Each UIAbility class defined in the HAP is associated with this class instance after instantiation. Through this class instance, you can obtain the runtime information of the UIAbility instances in the HAP.
......
...@@ -34,11 +34,9 @@ There are two roles in **DataShare**: ...@@ -34,11 +34,9 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**. - Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below.
### Data Provider Application Development (Only for System Applications) ### Data Provider Application Development (Only for System Applications)
[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override the APIs as required. [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
- **onCreate** - **onCreate**
...@@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
```ts ```ts
import Extension from '@ohos.application.DataShareExtensionAbility'; import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.rdb'; import rdb from '@ohos.data.relationalStore';
import fileIo from '@ohos.fileio'; import fileIo from '@ohos.fileio';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
4. Override the **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. 5. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. 6. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```ts ```ts
const DB_NAME = "DB00.db"; const DB_NAME = "DB00.db";
...@@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
let result; let result;
export default class DataShareExtAbility extends Extension { export default class DataShareExtAbility extends Extension {
private rdbStore_; private rdbStore_;
// Override onCreate(). // Override onCreate().
onCreate(want, callback) { onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt' result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store. // Create an RDB store.
rdb.getRdbStore(this.context, { rdb.getRdbStore(this.context, {
name: DB_NAME name: DB_NAME,
}, 1, function (err, data) { securityLevel: rdb.SecurityLevel.S1
rdbStore = data; }, function (err, data) {
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { rdbStore = data;
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
}); });
callback(); if (callbakc) {
callback();
}
}); });
} }
// Override query(). // Override query().
query(uri, predicates, columns, callback) { query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) { if (predicates == null || predicates == undefined) {
...@@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
}; };
``` ```
7. Define **DataShareExtensionAbility** in **module.json5**.
6. Define **DataShareExtensionAbility** in **module.json5**.
| Field | Description | | Field| Description |
| --------- | ------------------------------------------------------------ | | ------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. | | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.|
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. | | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
| | |
**module.json5 example** **module.json5 example**
...@@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
] ]
``` ```
### Data Consumer Application Development ### Data Consumer Application Development
1. Import dependencies. 1. Import dependencies.
...@@ -212,7 +208,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -212,7 +208,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = new Array("*"); let valArray = ['*'];
// Insert a piece of data. // Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => { dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data); console.log("dsHelper insert result: " + data);
......
...@@ -142,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -142,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description | | Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | Synchronizes data between devices. This API uses a promise to return the result.<br>- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.<br>- **predicates**: specifies the data and devices to synchronize.<br>- **string**: device ID. <br>- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| | RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | Synchronizes data between devices. This API uses a promise to return the result.<br>- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.<br>- **predicates**: specifies the data and devices to synchronize.<br>- **string**: device ID. <br>- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.|
**Registering an RDB Store Observer** **Registering an RDB Store Observer**
...@@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local
### Transaction ### Transaction
Table 15 Transaction APIs **Table 15** Transaction APIs
| Class | API | Description | | Class | API | Description |
| -------- | ----------------------- | --------------------------------- | | -------- | ----------------------- | --------------------------------- |
...@@ -202,44 +202,82 @@ Table 15 Transaction APIs ...@@ -202,44 +202,82 @@ Table 15 Transaction APIs
```js ```js
import data_rdb from '@ohos.data.relationalStore' import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
const STORE_CONFIG = { name: "RdbTest.db", // Assume that the current RDB store version is 3.
securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST) // When an RDB store is created, the default version is 0.
console.info('create table done.') if (rdbStore.version == 0) {
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null)
// Set the RDB store version. The input parameter must be an integer greater than 0.
rdbStore.version = 3
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null)
rdbStore.version = 2
}
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null)
rdbStore.version = 3
}
}) })
``` ```
Stage model: Stage model:
```ts ```ts
import data_rdb from '@ohos.data.relationalStore' import data_rdb from '@ohos.data.relationalStore'
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
context = this.context const STORE_CONFIG = {
name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1
}
// Assume that the current RDB store version is 3.
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
// When an RDB store is created, the default version is 0.
if (rdbStore.version == 0) {
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null)
// Set the RDB store version. The input parameter must be an integer greater than 0.
rdbStore.version = 3
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null)
rdbStore.version = 2
}
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null)
rdbStore.version = 3
}
})
} }
} }
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = { name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
``` ```
2. Insert data. 2. Insert data.
(1) Create a **ValuesBucket** to store the data you need to insert. (1) Create a **ValuesBucket** instance to store the data you need to insert.
(2) Call the **insert()** method to insert data into the RDB store. (2) Call the **insert()** method to insert data into the RDB store.
...@@ -384,14 +422,13 @@ Table 15 Transaction APIs ...@@ -384,14 +422,13 @@ Table 15 Transaction APIs
8. Query data of a remote device. 8. Query data of a remote device.
(1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device. (1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device.
(2) Call the resultSet() API to obtain the result. (2) Call the resultSet() API to obtain the result.
The sample code is as follows: The sample code is as follows:
```js ```js
let rdbPredicate = new data_rdb.RdbPredicates('employee') let rdbPredicate = new data_rdb.RdbPredicates('employee')
predicates.greaterThan("id", 0) predicates.greaterThan("id", 0)
let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate)
...@@ -406,31 +443,32 @@ Table 15 Transaction APIs ...@@ -406,31 +443,32 @@ Table 15 Transaction APIs
}).catch((err) => { }).catch((err) => {
console.info("failed to remoteQuery, err: " + err) console.info("failed to remoteQuery, err: " + err)
}) })
``` ```
9. Back up and restore an RDB store. 9. Back up and restore an RDB store.
(1) Back up the current RDB store. (1) Back up the current RDB store.
The sample code is as follows: The sample code is as follows:
```js ```js
let promiseBackup = rdbStore.backup("dbBackup.db") let promiseBackup = rdbStore.backup("dbBackup.db")
promiseBackup.then(() => { promiseBackup.then(() => {
console.info('Backup success.') console.info('Backup success.')
}).catch((err) => { }).catch((err) => {
console.info('Backup failed, err: ' + err) console.info('Backup failed, err: ' + err)
}) })
``` ```
(2) Restore the RDB store using the backup file.
The sample code is as follows: (2) Restore the RDB store using the backup file.
```js The sample code is as follows:
```js
let promiseRestore = rdbStore.restore("dbBackup.db") let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(() => { promiseRestore.then(() => {
console.info('Restore success.') console.info('Restore success.')
}).catch((err) => { }).catch((err) => {
console.info('Restore failed, err: ' + err) console.info('Restore failed, err: ' + err)
}) })
``` ```
...@@ -83,7 +83,7 @@ export default class MyAbilityStage extends AbilityStage { ...@@ -83,7 +83,7 @@ export default class MyAbilityStage extends AbilityStage {
### Saving and Restoring Data ### Saving and Restoring Data
After enabling **appRecovery**, you can use this function by either actively or passively saving the status and restoring data in the ability. After enabling **appRecovery**, you can use this function by either actively or passively saving the status and restoring data in the ability.
The following is an example of **MainAbility**: The following is an example of **EntryAbility**:
#### Importing the Service Package #### Importing the Service Package
...@@ -109,7 +109,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ...@@ -109,7 +109,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// Main window is created. Set a main page for this ability. // Main window is created. Set a main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate") console.log("[Demo] EntryAbility onWindowStageCreate")
globalThis.registerObserver = (() => { globalThis.registerObserver = (() => {
registerId = errorManager.registerErrorObserver(callback); registerId = errorManager.registerErrorObserver(callback);
...@@ -121,12 +121,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ...@@ -121,12 +121,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
- Save data. - Save data.
After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, wantParams)** of **MainAbility** is triggered. After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, wantParams)** of **EntryAbility** is triggered.
```ts ```ts
onSaveState(state, wantParams) { onSaveState(state, wantParams) {
// Save application data. // Save application data.
console.log("[Demo] MainAbility onSaveState") console.log("[Demo] EntryAbility onSaveState")
wantParams["myData"] = "my1234567"; wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE; return AbilityConstant.onSaveResult.ALL_AGREE;
} }
...@@ -134,12 +134,12 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, ...@@ -134,12 +134,12 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state,
- Restore data. - Restore data.
After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onSaveState(state, wantParams)** of **MainAbility** is called, and the saved data is in **parameters** of **want**. After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onSaveState(state, wantParams)** of **EntryAbility** is called, and the saved data is in **parameters** of **want**.
```ts ```ts
storage: LocalStorage storage: LocalStorage
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate") console.log("[Demo] EntryAbility onCreate")
globalThis.abilityWant = want; globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage(); this.storage = new LocalStorage();
...@@ -155,7 +155,7 @@ onCreate(want, launchParam) { ...@@ -155,7 +155,7 @@ onCreate(want, launchParam) {
```ts ```ts
onWindowStageDestroy() { onWindowStageDestroy() {
// Main window is destroyed to release UI resources. // Main window is destroyed to release UI resources.
console.log("[Demo] MainAbility onWindowStageDestroy") console.log("[Demo] EntryAbility onWindowStageDestroy")
globalThis.unRegisterObserver = (() => { globalThis.unRegisterObserver = (() => {
errorManager.unregisterErrorObserver(registerId, (result) => { errorManager.unregisterErrorObserver(registerId, (result) => {
...@@ -170,10 +170,10 @@ onWindowStageDestroy() { ...@@ -170,10 +170,10 @@ onWindowStageDestroy() {
This is triggered by the recovery framework. You do not need to register **ErrorObserver callback**. You only need to implement **onSaveState** of the ability for status saving and **onCreate** of the ability for data restoration. This is triggered by the recovery framework. You do not need to register **ErrorObserver callback**. You only need to implement **onSaveState** of the ability for status saving and **onCreate** of the ability for data restoration.
```ts ```ts
export default class MainAbility extends Ability { export default class EntryAbility extends Ability {
storage: LocalStorage storage: LocalStorage
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate") console.log("[Demo] EntryAbility onCreate")
globalThis.abilityWant = want; globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage(); this.storage = new LocalStorage();
...@@ -185,7 +185,7 @@ export default class MainAbility extends Ability { ...@@ -185,7 +185,7 @@ export default class MainAbility extends Ability {
onSaveState(state, wantParams) { onSaveState(state, wantParams) {
// Save application data. // Save application data.
console.log("[Demo] MainAbility onSaveState") console.log("[Demo] EntryAbility onSaveState")
wantParams["myData"] = "my1234567"; wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE; return AbilityConstant.onSaveResult.ALL_AGREE;
} }
......
...@@ -45,15 +45,15 @@ var callback = { ...@@ -45,15 +45,15 @@ var callback = {
console.log(errMsg); console.log(errMsg);
} }
} }
export default class MainAbility extends Ability { export default class EntryAbility extends Ability {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate") console.log("[Demo] EntryAbility onCreate")
registerId = errorManager.registerErrorObserver(callback); registerId = errorManager.registerErrorObserver(callback);
globalThis.abilityWant = want; globalThis.abilityWant = want;
} }
onDestroy() { onDestroy() {
console.log("[Demo] MainAbility onDestroy") console.log("[Demo] EntryAbility onDestroy")
errorManager.unregisterErrorObserver(registerId, (result) => { errorManager.unregisterErrorObserver(registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message) console.log("[Demo] result " + result.code + ";" + result.message)
}); });
...@@ -61,7 +61,7 @@ export default class MainAbility extends Ability { ...@@ -61,7 +61,7 @@ export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// Main window is created for this ability. // Main window is created for this ability.
console.log("[Demo] MainAbility onWindowStageCreate") console.log("[Demo] EntryAbility onWindowStageCreate")
windowStage.loadContent("pages/index", (err, data) => { windowStage.loadContent("pages/index", (err, data) => {
if (err.code) { if (err.code) {
...@@ -74,17 +74,17 @@ export default class MainAbility extends Ability { ...@@ -74,17 +74,17 @@ export default class MainAbility extends Ability {
onWindowStageDestroy() { onWindowStageDestroy() {
// Main window is destroyed to release UI resources. // Main window is destroyed to release UI resources.
console.log("[Demo] MainAbility onWindowStageDestroy") console.log("[Demo] EntryAbility onWindowStageDestroy")
} }
onForeground() { onForeground() {
// Ability is brought to the foreground. // Ability is brought to the foreground.
console.log("[Demo] MainAbility onForeground") console.log("[Demo] EntryAbility onForeground")
} }
onBackground() { onBackground() {
// Ability is brought back to the background. // Ability is brought back to the background.
console.log("[Demo] MainAbility onBackground") console.log("[Demo] EntryAbility onBackground")
} }
}; };
``` ```
...@@ -49,11 +49,11 @@ The following example illustrates how to log and subscribe to button click event ...@@ -49,11 +49,11 @@ The following example illustrates how to log and subscribe to button click event
```js ```js
import hilog from '@ohos.hilog'; import hilog from '@ohos.hilog';
import Ability from '@ohos.application.Ability' import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window' import Window from '@ohos.window'
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'
export default class EntryAbility extends Ability { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
......
...@@ -33,7 +33,7 @@ ArkTS sample code: ...@@ -33,7 +33,7 @@ ArkTS sample code:
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility", abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'choose', //choose or save 'startMode': 'choose', //choose or save
} }
...@@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult( ...@@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult(
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility", abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'save', //choose or save 'startMode': 'save', //choose or save
'saveFile': 'test.jpg', 'saveFile': 'test.jpg',
......
此差异已折叠。
此差异已折叠。
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
The **app** tag contains application-wide configuration. The internal structure is as follows: The **app** tag contains application-wide configuration. The internal structure is as follows:
### Internal Structure of the app Tag **Table 1** Internal structure of the app tag
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -14,15 +14,19 @@ The **app** tag contains application-wide configuration. The internal structure ...@@ -14,15 +14,19 @@ The **app** tag contains application-wide configuration. The internal structure
| smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)| | smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)|
| smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)| | smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)|
#### Internal Structure of the version Atttribute ## Internal Structure of the version Atttribute
**Table 2** Internal structure of the version atttribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:<br>For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999.<br>*A* indicates the major version number.<br>*B* indicates the minor version number.<br>*C* indicates the patch version number. For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.<br>*A* indicates the major version number.<br>*B* indicates the minor version number.<br>*C* indicates the feature version number.<br>*D* indicates the patch version number.| Number| No| | name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:<br>For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999. <br>- *A* indicates the major version number.<br>- *B* indicates the minor version number.<br>- *C* indicates the patch version number.<br/>For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.<br>- *A* indicates the major version number.<br>- *B* indicates the minor version number.<br>- *C* indicates the feature version number.<br>- *D* indicates the patch version number. | Number| No|
| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:<br>API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No| | code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:<br>API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No|
| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)| | minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)|
#### Internal Structure of the apiVersion Attribute ## Internal Structure of the apiVersion Attribute
**Table 3** Internal structure of the apiVersion attribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -30,7 +34,7 @@ The **app** tag contains application-wide configuration. The internal structure ...@@ -30,7 +34,7 @@ The **app** tag contains application-wide configuration. The internal structure
| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| | target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
| releaseType | SDK status when the application is running.<br>**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.<br>**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.<br>**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| | releaseType | SDK status when the application is running.<br>**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.<br>**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.<br>**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
### Example of the **app** Tag Example of the **app** tag:
```json ```json
"app": { "app": {
......
...@@ -49,7 +49,7 @@ Example of the **config.json** file: ...@@ -49,7 +49,7 @@ Example of the **config.json** file:
], ],
"commonEvents": [ "commonEvents": [
{ {
"name": ".MainAbility", "name": ".EntryAbility",
"permission": "ohos.permission.GET_BUNDLE_INFO", "permission": "ohos.permission.GET_BUNDLE_INFO",
"data": [ "data": [
"com.example.demo", "com.example.demo",
......
...@@ -46,33 +46,77 @@ struct bindPopupPage { ...@@ -46,33 +46,77 @@ struct bindPopupPage {
## Restrictions on Data Type Declarations of State Variables ## Restrictions on Data Type Declarations of State Variables
The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types. 1. The data types of state variables decorated by state decorators must be explicitly declared. They cannot be declared as **any** or **Date**.
Example: Example:
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct IndexPage { struct DatePickerExample {
// Incorrect: @State message: string | Resource = 'Hello World' // Incorrect: @State isLunar: any = false
@State message: string = 'Hello World' @State isLunar: boolean = false
// Incorrect: @State selectedDate: Date = new Date('2021-08-08')
build() { private selectedDate: Date = new Date('2021-08-08')
Row() {
Column() { build() {
Text(`${this.message}`) Column() {
.fontSize(50) Button('Switch Calendar')
.fontWeight(FontWeight.Bold) .margin({ top: 30 })
.onClick(() => {
this.isLunar = !this.isLunar
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
.lunar(this.isLunar)
.onChange((value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info('select current date is: ' + JSON.stringify(value))
})
}.width('100%')
} }
.width('100%')
} }
.height('100%') ```
}
} ![datePicker](../../application-dev/reference/arkui-ts/figures/datePicker.gif)
```
2. The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types.
The **Length**, **ResourceStr**, and **ResourceColor** types are combinations of primitive data types or reference data types. Therefore, they cannot be used by the aforementioned types of state variables.
For details about the definitions of **Length**, **ResourceStr**, and **ResourceColor**, see [Types](../../application-dev/reference/arkui-ts/ts-types.md).
Example:
```ts
// xxx.ets
@Entry
@Component
struct IndexPage {
// Incorrect: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
// Incorrect: @State message: ResourceStr = $r('app.string.hello')
@State resourceStr: Resource = $r('app.string.hello')
build() {
Row() {
Column() {
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
![hello](figures/hello.PNG) ![hello](figures/hello.PNG)
## Initialization and Restrictions of Custom Components' Member Variables ## Initialization and Restrictions of Custom Components' Member Variables
...@@ -98,6 +142,8 @@ The allowed method depends on the decorator of the state variable, as shown in t ...@@ -98,6 +142,8 @@ The allowed method depends on the decorator of the state variable, as shown in t
| @Link | Forbidden | Mandatory | | @Link | Forbidden | Mandatory |
| @StorageLink | Mandatory | Forbidden | | @StorageLink | Mandatory | Forbidden |
| @StorageProp | Mandatory | Forbidden | | @StorageProp | Mandatory | Forbidden |
| @LocalStorageLink | Mandatory | Forbidden |
| @LocalStorageProp | Mandatory | Forbidden |
| @Provide | Mandatory | Optional | | @Provide | Mandatory | Optional |
| @Consume | Forbidden | Forbidden | | @Consume | Forbidden | Forbidden |
| @ObjectLink | Forbidden | Mandatory | | @ObjectLink | Forbidden | Mandatory |
...@@ -111,25 +157,78 @@ As indicated by the preceding table: ...@@ -111,25 +157,78 @@ As indicated by the preceding table:
Comply with the following rules when using constructors to initialize member variables: Comply with the following rules when using constructors to initialize member variables:
| From the Variable in the Parent Component (Below) to the Variable in the Child Component (Right)| @State | @Link | @Prop | Normal Variable| | **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** |
| -------------------------------------------- | ------ | ------ | ------ | -------- | |---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------|
| @State | Not allowed| Allowed | Allowed | Allowed | | **regular** | Supported | Supported | Supported | Supported | Not supported | Not supported | Supported |
| @Link | Not allowed| Allowed | Not recommended| Allowed | | **@State** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| @Prop | Not allowed| Not allowed| Allowed | Allowed | | **@Link** | Not supported | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
| @StorageLink | Not allowed| Allowed | Not allowed| Not allowed | | **@Prop** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| @StorageProp | Not allowed| Not allowed| Not allowed| Allowed | | **@Provide** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| Normal variable | Allowed | Not allowed| Not allowed| Allowed | | **@Consume** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported |
| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported |
As indicated by the preceding table: | **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** |
|------------------|------------------|------------------|-----------------------|------------------------|
| **regular** | Supported | Not supported | Not supported | Not supported |
| **@State** | Supported | Supported | Supported | Supported |
| **@Link** | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
| **@Prop** | Supported | Supported | Supported | Supported |
| **@Provide** | Supported | Supported | Supported | Supported |
| **@Consume** | Not supported | Not supported | Not supported | Not supported |
| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported |
> **NOTE**
>
> **Supported (1)**: The dollar sign ($) must be used, for example, **this.$varA**.
>
> **regular**: refers to a regular variable that is not decorated by any decorator.
As indicated by the preceding tables:
- The **@ObjectLink** decorated variable cannot be directly initialized from a decorated variable in the parent component. The source of the parent component must be an array item or object attribute decorated by **@State**, **@Link**, **@Provide**, **@Consume**, or **@ObjectLink**.
- The normal variables of the parent component can be used to initialize the **@State** decorated variables of the child component, but not the **@Link** or **@Prop** decorated variables. - The regular variables of the parent component can be used to initialize the **@State** variable of the child component, but cannot be used to initialize the **@Link**, **@Consume**, and **@ObjectLink** variables.
- The **@State** decorated variable of the parent component can be used to initialize the **@Prop**, **@Link** (using **$**), or normal variables of the child component, but not the **@State** decorated variables of the child component. - The **@State** variable of the parent component can be used to initialize the **@Prop**, **@Link** (through **$**), or regular variables of the child component, but cannot be used to initialize the **@Consume** variable.
- The **@Link** decorated variables of the parent component can be used to initialize the **@Link** decorated or normal variables of the child component. However, initializing the **@State** decorated members of the child component can result in a syntax error. In addition, initializing the **@Prop** decorated variables is not recommended. - The **@Link** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component.
- The **@Prop** decorated variables of the parent component can be used to initialize the normal variables or **@Prop** decorated variables of the child component, but not the **@State** or **@Link** decorated variables. - The **@Prop** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component.
- Passing **@StorageLink** and **@StorageProp** from the parent component to the child component is prohibited. - **@StorageLink**, **@StorageProp**, **@LocalStorageLink**, and **@LocalStorageProp** variables cannot be initialized from the parent component.
- In addition to the preceding rules, the TypeScript strong type rules need to be followed. - In addition to the preceding rules, the TypeScript strong type rules need to be followed.
Example:
```ts
@Entry
@Component
struct Parent {
message: string = "Hello World"
build() {
Column() {
Child({
stateMessage: this.message,
/* ArkTS:ERROR The regular property 'message' cannot be assigned
to the @Link property 'linkMessage'.*/
linkMessage: this.$message
})
}
.width('100%')
}
}
@Component
struct Child {
@State stateMessage: string = "Hello World"
@Link linkMessage: string
build() {
Column() {
Text(this.stateMessage)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
}
```
...@@ -30,3 +30,5 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c ...@@ -30,3 +30,5 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c
- **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. - **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**.
- **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key. - **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key.
- **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started. - **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started.
For details about how to use state variables, see [Restrictions on Data Type Declarations of State Variables](arkts-restrictions-and-extensions.md).
# Internal Structure of deviceConfig Tag # Internal structure of deviceConfig Tag
The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type. The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type.
### Table 1 Internal Structure of the deviceConfig Tag ## Internal Structure of the deviceConfig Tag
**Table 1** Internal structure of the deviceConfig tag
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -16,7 +18,9 @@ The **deviceConfig** tag contains device-specific configuration of the applicati ...@@ -16,7 +18,9 @@ The **deviceConfig** tag contains device-specific configuration of the applicati
Table 2 describes the internal structure of the **deviceConfig** attributes. Table 2 describes the internal structure of the **deviceConfig** attributes.
#### Table 2 Internal Structure of the deviceConfig Attributes ## Internal Structure of the deviceConfig Attributes
**Table 2** Internal structure of the deviceConfig attributes
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -26,27 +30,33 @@ Table 2 describes the internal structure of the **deviceConfig** attributes. ...@@ -26,27 +30,33 @@ Table 2 describes the internal structure of the **deviceConfig** attributes.
| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)|
| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)| | network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)|
#### Table 3 Internal Structure of the network Attribute ## Internal Structure of the network Attribute
**Table 3** Internal structure of the network attribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.<br>**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)| | cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.<br>**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)|
| securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)| | securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)|
#### Table 4 Internal Structure of the securityConfig Attribute ## Internal Structure of the securityConfig Attribute
**Table 4** Internal structure of the securityConfig attribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| | domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)|
#### Table 5 Internal Structure of the domainSettings Attribute ## Internal Structure of the domainSettings Attribute
**Table 5** Internal structure of the domainSettings attribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)|
| domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)| | domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)|
### Example of the deviceConfig Tag Example of the **deviceConfig** tag:
```json ```json
"deviceConfig": { "deviceConfig": {
......
...@@ -122,7 +122,7 @@ ...@@ -122,7 +122,7 @@
- continuation - continuation
- [continuationExtraParams](js-apis-continuation-continuationExtraParams.md) - [continuationExtraParams](js-apis-continuation-continuationExtraParams.md)
- [continuationResult](js-apis-continuation-continuationResult.md) - [continuationResult](js-apis-continuation-continuationResult.md)
- Common Event and Notification - Common Event and Notification
- [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md) - [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md)
- [@ohos.events.emitter (Emitter)](js-apis-emitter.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md)
...@@ -203,7 +203,6 @@ ...@@ -203,7 +203,6 @@
- [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md)
- security - security
- [PermissionRequestResult](js-apis-permissionrequestresult.md) - [PermissionRequestResult](js-apis-permissionrequestresult.md)
- Data Management - Data Management
- [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md)
- [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md)
...@@ -215,11 +214,15 @@ ...@@ -215,11 +214,15 @@
- [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md) - [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md)
- [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md)
- data/rdb - data/rdb
- [resultSet](js-apis-data-resultset.md) - [resultSet (Result Set)](js-apis-data-resultset.md)
- File Management - File Management
- [@ohos.environment](js-apis-environment.md) - [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md)
- [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md) - [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md)
- [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md)
- [@ohos.file.fs (File Management)](js-apis-file-fs.md)
- [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md)
- [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md)
- [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md)
- [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md) - [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md)
- [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md) - [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md)
......
...@@ -72,7 +72,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro ...@@ -72,7 +72,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro
| ID | Error Message| | ID | Error Message|
| --------- | ------- | | --------- | ------- |
| 100001 | If no page is found for pageId or fail to get object property list. | | 100001 | if no page is found for pageId or fail to get object property list. |
**Example** **Example**
......
...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re ...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.|
...@@ -69,9 +69,11 @@ Stage model: ...@@ -69,9 +69,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result ...@@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
**Return value** **Return value**
...@@ -139,9 +141,11 @@ Stage model: ...@@ -139,9 +141,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. | | name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -215,9 +219,11 @@ Stage model: ...@@ -215,9 +219,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.| | name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value** **Return value**
...@@ -294,9 +300,11 @@ Stage model: ...@@ -294,9 +300,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. | | name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -358,9 +366,11 @@ Stage model: ...@@ -358,9 +366,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.| | name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value** **Return value**
...@@ -428,9 +438,9 @@ Stage model: ...@@ -428,9 +438,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
......
...@@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { const STORE_CONFIG = {
name: "RdbTest.db", name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1 securityLevel: data_rdb.SecurityLevel.S1
} }
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
if (err) { if (err) {
console.info("Failed to get RdbStore, err: " + err) console.info("Failed to get RdbStore, err: " + err)
return return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
} }
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}) })
...@@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { ...@@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
console.log("Got RdbStore successfully.")
})
} }
} }
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
})
``` ```
## data_rdb.getRdbStore ## data_rdb.getRdbStore
...@@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { const STORE_CONFIG = {
name: "RdbTest.db", name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1 securityLevel: data_rdb.SecurityLevel.S1
} }
let promise = data_rdb.getRdbStore(context, STORE_CONFIG); let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => { promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
console.log("Failed to get RdbStore, err: " + err) console.log("Failed to get RdbStore, err: " + err)
...@@ -170,35 +147,23 @@ promise.then(async (rdbStore) => { ...@@ -170,35 +147,23 @@ promise.then(async (rdbStore) => {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG);
promise.then(async (rdbStore) => {
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
} }
} }
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
``` ```
## data_rdb.deleteRdbStore ## data_rdb.deleteRdbStore
...@@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) { if (err) {
console.info("Failed to delete RdbStore, err: " + err) console.info("Failed to delete RdbStore, err: " + err)
...@@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { ...@@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
} }
} }
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
``` ```
## data_rdb.deleteRdbStore ## data_rdb.deleteRdbStore
...@@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{ promise.then(()=>{
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
...@@ -318,24 +277,18 @@ promise.then(()=>{ ...@@ -318,24 +277,18 @@ promise.then(()=>{
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
} }
} }
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
``` ```
## StoreConfig ## StoreConfig
...@@ -423,17 +376,6 @@ Defines the resolution to use when **insert()** and **update()** conflict. ...@@ -423,17 +376,6 @@ Defines the resolution to use when **insert()** and **update()** conflict.
| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.| | ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.|
| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.| | ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.|
## OpenStatus<sup>10+</sup>
Enumerates the RDB store status.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Value | Description |
| --------- | ---- | --------------------------------------------------- |
| ON_CREATE | 0 | The RDB store is created for the first time. |
| ON_OPEN | 1 | The RDB store is already created. |
## RdbPredicates ## RdbPredicates
Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false.
...@@ -1283,7 +1225,16 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the ...@@ -1283,7 +1225,16 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | ----------- | ---- | -------------------------------- | | ------------ | ----------- | ---- | -------------------------------- |
| openStatus<sup>10+</sup> | number | Yes | RDB store status. The value **0** indicates the **ON_CREATE** state, which means the RDB store is created for the first time. The value **1** indicates the **ON_OPEN** state, which means the RDB store is already created. | | version<sup>10+</sup> | number | Yes | RDB store version, which is an integer greater than 0. |
**Example**
```js
// Set the RDB store version.
rdbStore.version = 3
// Obtain the RDB store version.
console.info("Get RdbStore version is " + rdbStore.version)
```
### insert ### insert
......
# @ohos.environment (Directory Environment Capability) # @ohos.file.environment (Directory Environment Capability)
The **Environment** module provides APIs for obtaining the root directories of the storage and public files. The **Environment** module provides APIs for obtaining the root directories of the storage and public files.
> **NOTE** > **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. > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs and cannot be called by third-party applications. > - The APIs of this module are system APIs and cannot be called by third-party applications.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import ## Modules to Import
```js ```js
import environment from '@ohos.environment'; import environment from '@ohos.file.environment';
``` ```
## environment.getStorageDataDir ## environment.getStorageDataDir
...@@ -30,10 +31,10 @@ Obtains the root directory of the storage. This API uses a promise to return the ...@@ -30,10 +31,10 @@ Obtains the root directory of the storage. This API uses a promise to return the
**Example** **Example**
```js ```js
environment.getStorageDataDir().then(function(path){ environment.getStorageDataDir().then((path) => {
console.info("getStorageDataDir successfully:"+ path); console.info("getStorageDataDir successfully, Path: " + path);
}).catch(function(error){ }).catch((err) => {
console.info("getStorageDataDir failed with error:"+ error); console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code);
}); });
``` ```
...@@ -54,8 +55,12 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac ...@@ -54,8 +55,12 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac
**Example** **Example**
```js ```js
environment.getStorageDataDir(function(error, path){ environment.getStorageDataDir((err, path) => {
// do something if (err) {
console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getStorageDataDir successfully, Path: " + path);
}
}); });
``` ```
...@@ -76,10 +81,10 @@ Obtains the root directory of public files. This API uses a promise to return th ...@@ -76,10 +81,10 @@ Obtains the root directory of public files. This API uses a promise to return th
**Example** **Example**
```js ```js
environment.getUserDataDir().then(function(path){ environment.getUserDataDir().then((path) => {
console.info("getUserDataDir successfully:"+ path); console.info("getUserDataDir successfully, Path: " + path);
}).catch(function(error){ }).catch((err) => {
console.info("getUserDataDir failed with error:"+ error); console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code);
}); });
``` ```
...@@ -100,7 +105,11 @@ Obtains the root directory of public files. This API uses an asynchronous callba ...@@ -100,7 +105,11 @@ Obtains the root directory of public files. This API uses an asynchronous callba
**Example** **Example**
```js ```js
environment.getUserDataDir(function(error, path){ environment.getUserDataDir((err, path) => {
// do something if (err) {
console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getUserDataDir successfully, Path: " + path);
}
}); });
``` ```
此差异已折叠。
# @ohos.file.hash (File Hash Processing)
The **fileHash** module implements hash processing on files.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import Hash from '@ohos.file.hash';
```
## Guidelines
Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the file or directory in the application sandbox as follows:
**Stage Model**
```js
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
let context = this.context;
let pathDir = context.filesDir;
}
}
```
**FA Model**
```js
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
let pathDir = data;
})
```
For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context).
## Hash.hash
hash(path: string, algorithm: string): Promise&lt;string&gt;
Calculates a hash value for a file. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the file in the application sandbox. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
**Return value**
| Type | Description |
| --------------------- | -------------------------- |
| Promise&lt;string&gt; | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
**Example**
```js
let filePath = pathDir + "/test.txt";
Hash.hash(filePath, "sha256").then((str) => {
console.info("calculate file hash succeed:" + str);
}).catch((err) => {
console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
});
```
## Hash.hash
hash(path: string, algorithm: string, callback: AsyncCallback&lt;string&gt;): void
Calculates a hash value for a file. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | --------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the file in the application sandbox. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
**Example**
```js
Hash.hash(filePath, "sha256", (err, str) => {
if (err) {
console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("calculate file hash succeed:" + str);
}
});
```
# @ohos.file.securityLabel (Data Label)
The **securityLabel** module provides APIs for managing data security levels of files, including obtaining and setting file security levels.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>- The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import securityLabel from '@ohos.file.securityLabel';
```
## Guidelines
Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the file or directory in the application sandbox as follows:
**Stage Model**
```js
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
let context = this.context;
let pathDir = context.filesDir;
}
}
```
**FA Model**
```js
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
let pathDir = data;
})
```
For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context).
## securityLabel.setSecurityLabel
setSecurityLabel(path:string, type:dataLevel):Promise&lt;void&gt;
Sets a security label for a file in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
**Return value**
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
securityLabel.setSecurityLabel(path, "s0").then(() => {
console.info("setSecurityLabel successfully");
}).catch((err) => {
console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code);
});
```
## securityLabel.setSecurityLabel
setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback&lt;void&gt;):void
Sets a security label for a file in asynchronous mode. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------- | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Example**
```js
securityLabel.setSecurityLabel(path, "s0", (err) => {
if (err) {
console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("setSecurityLabel successfully.");
}
});
```
## securityLabel.setSecurityLabelSync
setSecurityLabelSync(path:string, type:dataLevel):void
Sets a security label for a file in synchronous mode.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
**Example**
```js
securityLabel.setSecurityLabelSync(path, "s0");
```
## securityLabel.getSecurityLabel
getSecurityLabel(path:string):Promise&lt;string&gt;
Obtains the security label of a file in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------- |
| path | string | Yes | Path of the target file.|
**Return value**
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;string&gt; | Security label obtained.|
**Example**
```js
securityLabel.getSecurityLabel(path).then((type) => {
console.log("getSecurityLabel successfully, Label: " + type);
}).catch((err) => {
console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code);
});
```
## securityLabel.getSecurityLabel
getSecurityLabel(path:string, callback:AsyncCallback&lt;string&gt;): void
Obtains the security label of a file in asynchronous mode. This API uses a callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | -------------------------- |
| path | string | Yes | Path of the target file. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the security label obtained.|
**Example**
```js
securityLabel.getSecurityLabel(path, (err, type) => {
if (err) {
console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.log("getSecurityLabel successfully, Label: " + type);
}
});
```
## securityLabel.getSecurityLabelSync
getSecurityLabelSync(path:string):string
Obtains the security label of a file in synchronous mode.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------- |
| path | string | Yes | Path of the target file.|
**Return value**
| Type | Description |
| ------ | ------------ |
| string | Security label obtained.|
**Example**
```js
let type = securityLabel.getSecurityLabelSync(path);
console.log("getSecurityLabel successfully, Label: " + type);
```
# @ohos.file.statvfs (File System Space Statistics)
The **statfs** module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import statvfs from '@ohos.file.statvfs';
```
## statvfs.getFreeSize
getFreeSize(path:string):Promise&lt;number&gt;
Obtains the number of free bytes of the specified file system in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
**Return value**
| Type | Description |
| --------------------- | -------------- |
| Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.|
**Example**
```js
let path = "/dev";
statfs.getFreeSize(path).then((number) => {
console.info("getFreeSize promise successfully, Size: " + number);
}).catch((err) => {
console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code);
});
```
## statfs.getFreeSize
getFreeSize(path:string, callback:AsyncCallback&lt;number&gt;): void
Obtains the number of free bytes of the specified file system in asynchronous mode. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.|
**Example**
```js
let path = "/dev";
statfs.getFreeSize(path, (err, number) => {
if (err) {
console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getFreeSize callback successfully, Size: " + number);
}
});
```
## statfs.getTotalSize
getTotalSize(path: string): Promise&lt;number&gt;
Obtains the total number of bytes of the specified file system in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
**Return value**
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.|
**Example**
```js
let path = "/dev";
statfs.getTotalSize(path).then((number) => {
console.info("getTotalSize promise successfully, Size: " + number);
}).catch((err) => {
console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code);
});
```
## statfs.getTotalSize
getTotalSize(path: string, callback: AsyncCallback&lt;number&gt;): void
Obtains the total number of bytes of the specified file system in asynchronous mode. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. |
**Example**
```js
let path = "/dev";
statfs.getTotalSize(path, (err, number) => {
if (err) {
console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getTotalSize promise successfully, Size: " + number);
}
});
```
...@@ -84,13 +84,13 @@ Activates an OS account. This API uses an asynchronous callback to return the re ...@@ -84,13 +84,13 @@ Activates an OS account. This API uses an asynchronous callback to return the re
try { try {
accountManager.activateOsAccount(localId, (err)=>{ accountManager.activateOsAccount(localId, (err)=>{
if (err) { if (err) {
console.log("activateOsAccount failed, error:" + JSON.stringify(err)); console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
console.log("activateOsAccount successfully"); console.log("activateOsAccount successfully");
} }
}); });
} catch (err) { } catch (err) {
console.log("activateOsAccount exception:" + JSON.stringify(err)); console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`);
} }
``` ```
...@@ -170,13 +170,13 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous ...@@ -170,13 +170,13 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous
try { try {
accountManager.checkMultiOsAccountEnabled((err, isEnabled) => { accountManager.checkMultiOsAccountEnabled((err, isEnabled) => {
if (err) { if (err) {
console.log("checkMultiOsAccountEnabled failed, error: " + JSON.stringify(err)); console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
console.log("checkMultiOsAccountEnabled successfully, isEnabled: " + isEnabled); console.log("checkMultiOsAccountEnabled successfully, isEnabled: " + isEnabled);
} }
}); });
} catch (err) { } catch (err) {
console.log("checkMultiOsAccountEnabled exception: " + JSON.stringify(err)); console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
} }
``` ```
...@@ -208,10 +208,10 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re ...@@ -208,10 +208,10 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
accountManager.checkMultiOsAccountEnabled().then((isEnabled) => { accountManager.checkMultiOsAccountEnabled().then((isEnabled) => {
console.log('checkMultiOsAccountEnabled successfully, isEnabled: ' + isEnabled); console.log('checkMultiOsAccountEnabled successfully, isEnabled: ' + isEnabled);
}).catch((err) => { }).catch((err) => {
console.log('checkMultiOsAccountEnabled failed, error: ' + JSON.stringify(err)); console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
}); });
} catch (err) { } catch (err) {
console.log('checkMultiOsAccountEnabled exception: ' + JSON.stringify(err)); console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
} }
``` ```
...@@ -3604,7 +3604,7 @@ Obtains the type of the account to which the current process belongs. This API u ...@@ -3604,7 +3604,7 @@ Obtains the type of the account to which the current process belongs. This API u
getDistributedVirtualDeviceId(callback: AsyncCallback&lt;string&gt;): void getDistributedVirtualDeviceId(callback: AsyncCallback&lt;string&gt;): void
Obtains the ID of the distributed virtual device. This API uses an asynchronous callback to return the result. Obtains the ID of this distributed virtual device. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> >
...@@ -3634,7 +3634,7 @@ Obtains the ID of the distributed virtual device. This API uses an asynchronous ...@@ -3634,7 +3634,7 @@ Obtains the ID of the distributed virtual device. This API uses an asynchronous
getDistributedVirtualDeviceId(): Promise&lt;string&gt; getDistributedVirtualDeviceId(): Promise&lt;string&gt;
Obtains the ID of the distributed virtual device. This API uses a promise to return the result. Obtains the ID of this distributed virtual device. This API uses a promise to return the result.
> **NOTE** > **NOTE**
> >
...@@ -4323,13 +4323,13 @@ Unregisters this PIN inputer. ...@@ -4323,13 +4323,13 @@ Unregisters this PIN inputer.
pinAuth.unregisterInputer(); pinAuth.unregisterInputer();
``` ```
### InputerManager <sup>10+</sup> ## InputerManager <sup>9+</sup>
Provides APIs for managing credential inputers. Provides APIs for managing credential inputers.
### registerInputer<sup>10+</sup> ### registerInputer<sup>9+</sup>
registerInputer(authType: AuthType, inputer: IInputer): void; static registerInputer(authType: AuthType, inputer: IInputer): void
Register a credential inputer. Register a credential inputer.
...@@ -4357,11 +4357,10 @@ Register a credential inputer. ...@@ -4357,11 +4357,10 @@ Register a credential inputer.
**Example** **Example**
```js ```js
let inputerMgr = new account_osAccount.InputerManager();
let authType = account_osAccount.AuthType.DOMAIN; let authType = account_osAccount.AuthType.DOMAIN;
let password = new Uint8Array([0, 0, 0, 0, 0]); let password = new Uint8Array([0, 0, 0, 0, 0]);
try { try {
inputerMgr.registerInputer(authType, { account_osAccount.InputerManager.registerInputer(authType, {
onGetData: (authSubType, callback) => { onGetData: (authSubType, callback) => {
callback.onSetData(authSubType, password); callback.onSetData(authSubType, password);
} }
...@@ -4372,9 +4371,9 @@ Register a credential inputer. ...@@ -4372,9 +4371,9 @@ Register a credential inputer.
} }
``` ```
### unregisterInputer<sup>10+</sup> ### unregisterInputer<sup>9+</sup>
unregisterInputer(authType: AuthType): void; static unregisterInputer(authType: AuthType): void
Unregisters this credential inputer. Unregisters this credential inputer.
...@@ -4398,16 +4397,129 @@ Unregisters this credential inputer. ...@@ -4398,16 +4397,129 @@ Unregisters this credential inputer.
**Example** **Example**
```js ```js
let inputerMgr = new account_osAccount.InputerManager();
let authType = account_osAccount.AuthType.DOMAIN; let authType = account_osAccount.AuthType.DOMAIN;
try { try {
inputerMgr.unregisterInputer(authType); account_osAccount.InputerManager.unregisterInputer(authType);
console.log('unregisterInputer success.'); console.log('unregisterInputer success.');
} catch(err) { } catch(err) {
console.log("unregisterInputer err:" + JSON.stringify(err)); console.log("unregisterInputer err:" + JSON.stringify(err));
} }
``` ```
## DomainPlugin<sup>9+</sup>
Provides APIs for domain account authentication.
**System API**: This is a system API.
### auth<sup>9+</sup>
auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUserAuthCallback): void
Authenticates a domain account.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.OsAccount
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | --------------------------------------- | ---- | --------------- |
| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.|
| credential | Uint8Array | Yes | Credentials of the domain account.|
| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result.|
**Example**
```js
let plugin = {
auth: (domainInfo, credential, callback) => {
// mock authentication
callback.onResult(0, {});
}
}
account_osAccount.DomainAccountManager.registerPlugin(plugin);
let userAuth = new account_osAccount.UserAuth();
let challenge = new Uint8Array([0]);
let authType = account_osAccount.AuthType.PIN;
let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1;
try {
userAuth.auth(challenge, authType, authTrustLevel, {
onResult: (resultCode, authResult) => {
console.log('auth resultCode = ' + resultCode);
console.log('auth authResult = ' + JSON.stringify(authResult));
}
});
} catch (err) {
console.log('auth exception = ' + JSON.stringify(err));
}
```
## DomainAccountManager <sup>9+</sup>
Provides APIs for domain account management.
### registerPlugin<sup>9+</sup>
static registerPlugin(plugin: DomainPlugin): void
Registers a domain plug-in.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.OsAccount
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
**Parameters**
| Name | Type | Mandatory| Description |
| ----------| ----------------------- | --- | -------------------------- |
| plugin | [DomainPlugin](#domainplugin9) | Yes | Domain plug-in to register.|
**Error codes**
| ID| Error Message |
| -------- | --------------------------- |
| 12300201 | The domain plugin has been registered. |
**Example**
```js
let plugin = {
auth: (domainInfo, credential, callback) => {
// mock authentication
callback.onResult(0, {});
}
}
try {
account_osAccount.DomainAccountManager.registerPlugin(plugin);
console.log('registerPlugin success.');
} catch(err) {
console.log("registerPlugin err:" + JSON.stringify(err));
}
```
### unregisterPlugin<sup>9+</sup>
static unregisterPlugin(): void
Unregisters this domain plug-in.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.OsAccount
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
**Example**
```js
try {
account_osAccount.DomainAccountManager.unregisterPlugin();
console.log('unregisterPlugin success.');
} catch(err) {
console.log("unregisterPlugin err:" + JSON.stringify(err));
}
```
## UserIdentityManager<sup>8+</sup> ## UserIdentityManager<sup>8+</sup>
Provides APIs for user identity management (IDM). Provides APIs for user identity management (IDM).
......
...@@ -120,9 +120,9 @@ try { ...@@ -120,9 +120,9 @@ try {
} }
``` ```
## privacyManager.getPermissionUsedRecords ## privacyManager.getPermissionUsedRecord
getPermissionUsedRecords(request: PermissionUsedRequest): Promise&lt;PermissionUsedResponse&gt; getPermissionUsedRecord(request: PermissionUsedRequest): Promise&lt;PermissionUsedResponse&gt;
Obtains historical permission usage records. This API uses a promise to return the result. Obtains historical permission usage records. This API uses a promise to return the result.
...@@ -170,19 +170,19 @@ let request = { ...@@ -170,19 +170,19 @@ let request = {
"flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
}; };
try { try {
privacyManager.getPermissionUsedRecords(request).then((data) => { privacyManager.getPermissionUsedRecord(request).then((data) => {
console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
}).catch((err) => { }).catch((err) => {
console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
}); });
} catch(err) { } catch(err) {
console.log(`catch err->${JSON.stringify(err)}`); console.log(`catch err->${JSON.stringify(err)}`);
} }
``` ```
## privacyManager.getPermissionUsedRecords ## privacyManager.getPermissionUsedRecord
getPermissionUsedRecords(request: PermissionUsedRequest, callback: AsyncCallback&lt;PermissionUsedResponse&gt;): void getPermissionUsedRecord(request: PermissionUsedRequest, callback: AsyncCallback&lt;PermissionUsedResponse&gt;): void
Obtains historical permission usage records. This API uses an asynchronous callback to return the result. Obtains historical permission usage records. This API uses an asynchronous callback to return the result.
...@@ -225,11 +225,11 @@ let request = { ...@@ -225,11 +225,11 @@ let request = {
"flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
}; };
try { try {
privacyManager.getPermissionUsedRecords(request, (err, data) => { privacyManager.getPermissionUsedRecord(request, (err, data) => {
if (err) { if (err) {
console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
} else { } else {
console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
} }
}); });
} catch(err) { } catch(err) {
......
...@@ -32,7 +32,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ ...@@ -32,7 +32,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message| | ID | Error Message|
| --------- | ------- | | --------- | ------- |
| 100001 | If UI execution context not found. | | 100001 | if UI execution context not found. |
**Example** **Example**
...@@ -40,7 +40,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ ...@@ -40,7 +40,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
try { try {
promptAction.showToast({ promptAction.showToast({
message: 'Message Info', message: 'Message Info',
duration: 2000, duration: 2000
}); });
} catch (error) { } catch (error) {
console.error(`showToast args error code is ${error.code}, message is ${error.message}`); console.error(`showToast args error code is ${error.code}, message is ${error.message}`);
...@@ -88,7 +88,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ ...@@ -88,7 +88,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message| | ID | Error Message|
| --------- | ------- | | --------- | ------- |
| 100001 | If UI execution context not found. | | 100001 | if UI execution context not found. |
**Example** **Example**
...@@ -100,11 +100,11 @@ try { ...@@ -100,11 +100,11 @@ try {
buttons: [ buttons: [
{ {
text: 'button1', text: 'button1',
color: '#000000', color: '#000000'
}, },
{ {
text: 'button2', text: 'button2',
color: '#000000', color: '#000000'
} }
], ],
}) })
...@@ -142,7 +142,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ ...@@ -142,7 +142,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message| | ID | Error Message|
| --------- | ------- | | --------- | ------- |
| 100001 | If UI execution context not found. | | 100001 | if UI execution context not found. |
**Example** **Example**
...@@ -154,11 +154,11 @@ try { ...@@ -154,11 +154,11 @@ try {
buttons: [ buttons: [
{ {
text: 'button1', text: 'button1',
color: '#000000', color: '#000000'
}, },
{ {
text: 'button2', text: 'button2',
color: '#000000', color: '#000000'
} }
] ]
}, (err, data) => { }, (err, data) => {
...@@ -218,7 +218,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ ...@@ -218,7 +218,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message| | ID | Error Message|
| --------- | ------- | | --------- | ------- |
| 100001 | If UI execution context not found. | | 100001 | if UI execution context not found. |
**Example** **Example**
...@@ -229,11 +229,11 @@ try { ...@@ -229,11 +229,11 @@ try {
buttons: [ buttons: [
{ {
text: 'item1', text: 'item1',
color: '#666666', color: '#666666'
}, },
{ {
text: 'item2', text: 'item2',
color: '#000000', color: '#000000'
}, },
] ]
}, (err, data) => { }, (err, data) => {
...@@ -276,7 +276,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ ...@@ -276,7 +276,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message| | ID | Error Message|
| --------- | ------- | | --------- | ------- |
| 100001 | If UI execution context not found. | | 100001 | if UI execution context not found. |
**Example** **Example**
...@@ -287,11 +287,11 @@ try { ...@@ -287,11 +287,11 @@ try {
buttons: [ buttons: [
{ {
text: 'item1', text: 'item1',
color: '#666666', color: '#666666'
}, },
{ {
text: 'item2', text: 'item2',
color: '#000000', color: '#000000'
}, },
] ]
}) })
......
...@@ -563,6 +563,7 @@ Describes the page routing options. ...@@ -563,6 +563,7 @@ Describes the page routing options.
> **NOTE** > **NOTE**
>
> The page routing stack supports a maximum of 32 pages. > The page routing stack supports a maximum of 32 pages.
## RouterMode<sup>9+</sup> ## RouterMode<sup>9+</sup>
......
...@@ -4,7 +4,9 @@ The **statfs** module provides APIs for obtaining file system information, inclu ...@@ -4,7 +4,9 @@ The **statfs** module provides APIs for obtaining file system information, inclu
> **NOTE** > **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. > - 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.
>
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [@ohos.file.statvfs](js-apis-file-statvfs.md).
## Modules to Import ## Modules to Import
...@@ -21,15 +23,15 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ...@@ -21,15 +23,15 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- | | ------ | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------------- | | --------------------- | -------------- |
| Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.| | Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.|
**Example** **Example**
...@@ -52,10 +54,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ...@@ -52,10 +54,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.|
**Example** **Example**
...@@ -79,15 +81,15 @@ Obtains the total number of bytes of the specified file system in asynchronous m ...@@ -79,15 +81,15 @@ Obtains the total number of bytes of the specified file system in asynchronous m
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- | | ---- | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------ | | --------------------- | ------------ |
| Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.| | Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.|
**Example** **Example**
...@@ -110,10 +112,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m ...@@ -110,10 +112,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. |
**Example** **Example**
......
...@@ -38,7 +38,7 @@ export default { ...@@ -38,7 +38,7 @@ export default {
showToast() { showToast() {
prompt.showToast({ prompt.showToast({
message: 'Message Info', message: 'Message Info',
duration: 2000, duration: 2000
}); });
} }
} }
...@@ -67,11 +67,11 @@ export default { ...@@ -67,11 +67,11 @@ export default {
showDialog() { showDialog() {
prompt.showDialog({ prompt.showDialog({
title: 'Title Info', title: 'Title Info',
message: 'Message Info', message: 'Message Info',
buttons: [ buttons: [
{ {
text: 'button', text: 'button',
color: '#666666', color: '#666666'
}, },
], ],
success: function(data) { success: function(data) {
...@@ -110,12 +110,12 @@ export default { ...@@ -110,12 +110,12 @@ export default {
buttons: [ buttons: [
{ {
text: 'item1', text: 'item1',
color: '#666666', color: '#666666'
}, },
{ {
text: 'item2', text: 'item2',
color: '#000000', color: '#000000'
}, },
], ],
success: function(tapIndex) { success: function(tapIndex) {
console.log('dialog success callback, click button : ' + data.tapIndex); console.log('dialog success callback, click button : ' + data.tapIndex);
......
...@@ -31,7 +31,7 @@ Enumerates the match patterns supported for component attributes. ...@@ -31,7 +31,7 @@ Enumerates the match patterns supported for component attributes.
| Name | Value | Description | | Name | Value | Description |
| ----------- | ---- | -------------- | | ----------- | ---- | -------------- |
| EQUALS | 0 | Equal to the given value. | | EQUALS | 0 | Equals the given value. |
| CONTAINS | 1 | Contains the given value. | | CONTAINS | 1 | Contains the given value. |
| STARTS_WITH | 2 | Starts with the given value.| | STARTS_WITH | 2 | Starts with the given value.|
| ENDS_WITH | 3 | Ends with the given value.| | ENDS_WITH | 3 | Ends with the given value.|
...@@ -70,12 +70,12 @@ Provides bounds information of a component. ...@@ -70,12 +70,12 @@ Provides bounds information of a component.
**System capability**: SystemCapability.Test.UiTest **System capability**: SystemCapability.Test.UiTest
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ------------------------- | | ------ | ------ | ---- | ---- | ------------------------- |
| leftX | number | Yes | No | X-coordinate of the upper left corner of the component bounds.| | left | number | Yes | No | X-coordinate of the upper left corner of the component bounds.|
| topY | number | Yes | No | Y-coordinate of the upper left corner of the component bounds.| | top | number | Yes | No | Y-coordinate of the upper left corner of the component bounds.|
| rightX | number | Yes | No | X-coordinate of the lower right corner of the component bounds.| | right | number | Yes | No | X-coordinate of the lower right corner of the component bounds.|
| bottomY | number | Yes | No | Y-coordinate of the lower right corner of the component bounds.| | bottom | number | Yes | No | Y-coordinate of the lower right corner of the component bounds.|
## WindowMode<sup>9+</sup> ## WindowMode<sup>9+</sup>
...@@ -219,7 +219,7 @@ Specifies the clickable status attribute of the target component. ...@@ -219,7 +219,7 @@ Specifies the clickable status attribute of the target component.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Clickable status of the target component.<br>**true**: clickable.<br>**false**: not clickable.<br> Default value: **true**| | b | boolean | No | Clickable status of the target component.<br>**true**: clickable.<br>**false**: not clickable.<br>Default value: **true** |
**Return value** **Return value**
...@@ -245,7 +245,7 @@ Specifies the long-clickable status attribute of the target component. ...@@ -245,7 +245,7 @@ Specifies the long-clickable status attribute of the target component.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Long-clickable status of the target component.<br>**true**: long-clickable.<br>**false**: not long-clickable.<br> Default value: **true**| | b | boolean | No | Long-clickable status of the target component.<br>**true**: long-clickable.<br>**false**: not long-clickable.<br>Default value: **true** |
**Return value** **Return value**
...@@ -272,7 +272,7 @@ Specifies the scrollable status attribute of the target component. ...@@ -272,7 +272,7 @@ Specifies the scrollable status attribute of the target component.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------------------------------- | | ------ | ------- | ---- | ----------------------------------------------------------- |
| b | boolean | No | Scrollable status of the target component.<br>**true**: scrollable.<br>**false**: not scrollable.<br> Default value: **true**| | b | boolean | No | Scrollable status of the target component.<br>**true**: scrollable.<br>**false**: not scrollable.<br>Default value: **true** |
**Return value** **Return value**
...@@ -298,7 +298,7 @@ Specifies the enabled status attribute of the target component. ...@@ -298,7 +298,7 @@ Specifies the enabled status attribute of the target component.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | --------------------------------------------------------- | | ------ | ------- | ---- | --------------------------------------------------------- |
| b | boolean | No | Enabled status of the target component.<br>**true**: enabled.<br>**false**: disabled.<br> Default value: **true**| | b | boolean | No | Enabled status of the target component.<br>**true**: enabled.<br>**false**: not enabled.<br>Default value: **true** |
**Return value** **Return value**
...@@ -324,7 +324,7 @@ Specifies the focused status attribute of the target component. ...@@ -324,7 +324,7 @@ Specifies the focused status attribute of the target component.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------------------------- | | ------ | ------- | ---- | ----------------------------------------------------- |
| b | boolean | No | Focused status of the target component.<br>**true**: focused.<br>**false**: not focused.<br> Default value: **true**| | b | boolean | No | Focused status of the target component.<br>**true**: focused.<br>**false**: not focused.<br>Default value: **true** |
**Return value** **Return value**
...@@ -350,7 +350,7 @@ Specifies the selected status attribute of the target component. ...@@ -350,7 +350,7 @@ Specifies the selected status attribute of the target component.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Selected status of the target component.<br>**true**: selected.<br>**false**: not selected.<br> Default value: **true**| | b | boolean | No | Selected status of the target component.<br>**true**: selected.<br>**false**: not selected.<br>Default value: **true** |
**Return value** **Return value**
...@@ -376,7 +376,7 @@ Specifies the checked status attribute of the target component. ...@@ -376,7 +376,7 @@ Specifies the checked status attribute of the target component.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Checked status of the target component.<br>**true**: checked.<br>**false**: not checked.<br> Default value: **false**| | b | boolean | No | Checked status of the target component.<br>**true**: checked.<br>**false**: not checked.<br>Default value: **false** |
**Return value** **Return value**
...@@ -402,7 +402,7 @@ Specifies the checkable status attribute of the target component. ...@@ -402,7 +402,7 @@ Specifies the checkable status attribute of the target component.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Checkable status of the target component.<br>**true**: checkable.<br>**false**: not checkable.<br> Default value: **false**| | b | boolean | No | Checkable status of the target component.<br>**true**: checkable.<br>**false**: not checkable.<br>Default value: **false** |
**Return value** **Return value**
...@@ -2788,7 +2788,7 @@ This API is deprecated since API version 9. You are advised to use [clickable<su ...@@ -2788,7 +2788,7 @@ This API is deprecated since API version 9. You are advised to use [clickable<su
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Clickable status of the target component.<br>**true**: clickable.<br>**false**: not clickable.<br> Default value: **true**| | b | boolean | No | Clickable status of the target component.<br>**true**: clickable.<br>**false**: not clickable.<br>Default value: **true** |
**Return value** **Return value**
...@@ -2817,7 +2817,7 @@ This API is deprecated since API version 9. You are advised to use [scrollable<s ...@@ -2817,7 +2817,7 @@ This API is deprecated since API version 9. You are advised to use [scrollable<s
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------------------------------- | | ------ | ------- | ---- | ----------------------------------------------------------- |
| b | boolean | No | Scrollable status of the target component.<br>**true**: scrollable.<br>**false**: not scrollable.<br> Default value: **true**| | b | boolean | No | Scrollable status of the target component.<br>**true**: scrollable.<br>**false**: not scrollable.<br>Default value: **true** |
**Return value** **Return value**
...@@ -2845,7 +2845,7 @@ This API is deprecated since API version 9. You are advised to use [enabled<sup> ...@@ -2845,7 +2845,7 @@ This API is deprecated since API version 9. You are advised to use [enabled<sup>
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | --------------------------------------------------------- | | ------ | ------- | ---- | --------------------------------------------------------- |
| b | boolean | No | Enabled status of the target component.<br>**true**: enabled.<br>**false**: not disabled.<br> Default value: **true**| | b | boolean | No | Enabled status of the target component.<br>**true**: enabled.<br>**false**: not enabled.<br>Default value: **true** |
**Return value** **Return value**
...@@ -2873,7 +2873,7 @@ This API is deprecated since API version 9. You are advised to use [focused<sup> ...@@ -2873,7 +2873,7 @@ This API is deprecated since API version 9. You are advised to use [focused<sup>
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------------------------- | | ------ | ------- | ---- | ----------------------------------------------------- |
| b | boolean | No | Focused status of the target component.<br>**true**: focused.<br>**false**: not focused.<br> Default value: **true**| | b | boolean | No | Focused status of the target component.<br>**true**: focused.<br>**false**: not focused.<br>Default value: **true** |
**Return value** **Return value**
...@@ -2901,7 +2901,7 @@ This API is deprecated since API version 9. You are advised to use [selected<sup ...@@ -2901,7 +2901,7 @@ This API is deprecated since API version 9. You are advised to use [selected<sup
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ | | ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Selected status of the target component.<br>**true**: selected.<br>**false**: not selected.<br> Default value: **true**| | b | boolean | No | Selected status of the target component.<br>**true**: selected.<br>**false**: not selected.<br>Default value: **true** |
**Return value** **Return value**
......
# File Management Error Codes # File Management Error Codes
The error codes of the file management subsystem consist of the following: The error codes of the file management subsystem consist of the following:<br>- Basic file I/O error codes<br>- User data management error codes<br>- User file access error codes<br>- Spatial statistics error codes
- Basic file I/O error codes
- User data management error codes
- User file access error codes
- Spatial statistics error codes
## Basic File I/O Error Codes ## Basic File I/O Error Codes
...@@ -719,3 +714,41 @@ Fail to notify agent ...@@ -719,3 +714,41 @@ Fail to notify agent
**Solution** **Solution**
Check whether the client is normal. Check whether the client is normal.
## Error Code Adaptation
The APIs provided by the file management subsystem support exception handling.
Sample code for exception handling in a synchronous API:
```js
import fs from '@ohos.file.fs'
try {
let file = fs.openSync(path, fs.OpenMode.READ_ONLY);
} catch (err) {
console.error("openSync errCode:" + err.code + ", errMessage:" + err.message);
}
```
Sample code for exception handling in an asynchronous API (promise):
```js
import fs from '@ohos.file.fs'
try {
let file = await fs.open(path, fs.OpenMode.READ_ONLY);
} catch (err) {
console.error("open promise errCode:" + err.code + ", errMessage:" + err.message);
}
```
Sample code for exception handling in an asynchronous API (callback):
```js
import fs from '@ohos.file.fs'
try {
fs.open(path, fs.OpenMode.READ_ONLY, function(e, file){ // Asynchronous thread (such as the system call) errors are obtained via a callback.
if (e) {
console.error("open in async errCode:" + e.code + ", errMessage:" + e.message);
}
});
} catch (err) {// Main thread errors (such as invalid parameters) are obtained by try catch.
console.error("open callback errCode:" + err.code + ", errMessage:" + err.message);
}
```
...@@ -534,9 +534,9 @@ Allows an application to change the telephone state. ...@@ -534,9 +534,9 @@ Allows an application to change the telephone state.
**Enable ACL**: TRUE **Enable ACL**: TRUE
## ohos.permission.START_ABILIIES_FROM_BACKGROUND ## ohos.permission.START_ABILITIES_FROM_BACKGROUND
Allows an application to start Feature abilities in the background. Allows an application to start or access other components from the background.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1594,6 +1594,16 @@ Allows a system application to obtain the authentication and networking capabili ...@@ -1594,6 +1594,16 @@ Allows a system application to obtain the authentication and networking capabili
**Enable ACL**: TRUE **Enable ACL**: TRUE
## ohos.permission.APP_TRACKING_CONSENT
Allows an application to read advertisement identifiers.
**Permission level**: normal
**Authorization mode**: user_grant
**Enable ACL**: TRUE
## ohos.permission.RUN_ANY_CODE ## ohos.permission.RUN_ANY_CODE
Allows an application to run unsigned code. Allows an application to run unsigned code.
......
此差异已折叠。
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
- [Exception Debugging](kernel-mini-memory-exception.md) - [Exception Debugging](kernel-mini-memory-exception.md)
- [Trace](kernel-mini-memory-trace.md) - [Trace](kernel-mini-memory-trace.md)
- [LMS](kernel-mini-memory-lms.md) - [LMS](kernel-mini-memory-lms.md)
- [Shell](kernel-mini-debug-shell.md)
- Appendix - Appendix
- [Kernel Coding Specification](kernel-mini-appx-code.md) - [Kernel Coding Specification](kernel-mini-appx-code.md)
- [Standard Libraries](kernel-mini-appx-lib.md) - [Standard Libraries](kernel-mini-appx-lib.md)
......
# Events # Event
## Basic Concepts ## Basic Concepts
An event is a mechanism for communication between tasks. It can be used to synchronize tasks. The events have the following features: An event is a communication mechanism used to synchronize tasks. Events have the following features:
- Events can be synchronized in one-to-many or many-to-many mode. In one-to-many mode, a task can wait for multiple events. In many-to-many mode, multiple tasks can wait for multiple events. However, a write event wakes up only one task from the block. - Events can be synchronized in one-to-many or many-to-many mode. In one-to-many mode, a task can wait for multiple events. In many-to-many mode, multiple tasks can wait for multiple events. However, a write event wakes up only one task from the block.
- Event read timeout mechanism is used. - Event read timeout mechanism is used.
- Events are used only for task synchronization, but not for data transmission. - Events are used for task synchronization, but not for data transmission.
APIs are provided to initialize, read/write, clear, and destroy events. APIs are provided to initialize, read/write, clear, and destroy events.
...@@ -18,7 +18,7 @@ APIs are provided to initialize, read/write, clear, and destroy events. ...@@ -18,7 +18,7 @@ APIs are provided to initialize, read/write, clear, and destroy events.
### Event Control Block ### Event Control Block
The event control block is a struct configured in the event initialization function. It is passed in as an input parameter to identify the event for operations such as event read and write. The data structure of the event control block is as follows: The event control block is a structure in the event initialization function. It passes in event identifies for operations such as event read and write. The data structure of the event control block is as follows:
``` ```
...@@ -31,23 +31,33 @@ typedef struct tagEvent { ...@@ -31,23 +31,33 @@ typedef struct tagEvent {
### Working Principles ### Working Principles
**Initializing an event**: An event control block is created to maintain a collection of processed events and a linked list of tasks waiting for specific events. **Initializing an Event**
**Writing an event**: When a specified event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related task based on the task conditions. An event control block is created to maintain a set of processed events and a linked list of tasks waiting for specific events.
**Reading an event**: If the read event already exists, it is returned synchronously. In other cases, the return time is determined based on the timeout period and event triggering status. If the wait event condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired. **Writing an Event**
The input parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** indicates the mask of the event. **mode** indicates the handling mode, which can be any of the following: When an event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related tasks based on the task conditions.
- **LOS_WAITMODE_AND**: Event reading is successful only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. **Reading an Event**
- **LOS_WAITMODE_OR**: Event reading is successful when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned. If the event to read already exists, it is returned synchronously. In other cases, the event is returned based on the timeout period and event triggering conditions. If the wait condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired.
The parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** specifies the event mask. **mode** specifies the handling mode, which can be any of the following:
- **LOS_WAITMODE_AND**: Read the event only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
- **LOS_WAITMODE_OR**: Read the event only when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
- **LOS_WAITMODE_CLR**: This mode must be used with one or all of the event modes (LOS_WAITMODE_AND | LOS_WAITMODE_CLR or LOS_WAITMODE_OR | LOS_WAITMODE_CLR). In this mode, if all event modes or any event mode is successful, the corresponding event type bit in the event control block will be automatically cleared. - **LOS_WAITMODE_CLR**: This mode must be used with one or all of the event modes (LOS_WAITMODE_AND | LOS_WAITMODE_CLR or LOS_WAITMODE_OR | LOS_WAITMODE_CLR). In this mode, if all event modes or any event mode is successful, the corresponding event type bit in the event control block will be automatically cleared.
**Clearing events**: Clear the event set of the event control block based on the specified mask. If the mask is **0**, the event set will be cleared. If the mask is **0xffff**, no event will be cleared, and the event set remains unchanged. **Clearing Events**
The events in the event set of the event control block can be cleared based on the specified mask. The mask **0** means to clear the event set; the mask **0xffff** means the opposite.
**Destroying Events**
**Destroying an event**: Destroy the specified event control block. The event control block can be destroyed to release resources.
**Figure 1** Event working mechanism for a mini system **Figure 1** Event working mechanism for a mini system
...@@ -58,12 +68,12 @@ The input parameters **eventMask** and **mode** determine whether the condition ...@@ -58,12 +68,12 @@ The input parameters **eventMask** and **mode** determine whether the condition
| Category| API| Description| | Category| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| Event check| LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.<br>**NOTICE**<br><br>If **mode** contains **LOS_WAITMODE_CLR** and the expected event occurs, the event that meets the requirements in **eventID** will be cleared. In this case, **eventID** is an input parameter and an output parameter. In other cases, **eventID** is used only as an input parameter.| | Checking an event | LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.<br>**NOTE**<br>If **mode** contains **LOS_WAITMODE_CLR** and the expected event occurs, the event that meets the requirements in **eventID** will be cleared. In this case, **eventID** is an input parameter and an output parameter. In other cases, **eventID** is used only as an input parameter. |
| Initialization| LOS_EventInit | Initializes an event control block.| | Initializing an event control block | LOS_EventInit | Initializes an event control block.|
| Event read| LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).<br>If no event is read, **0** is returned.<br>If an event is successfully read, a positive value (event set) is returned.<br>In other cases, an error code is returned.| | Reading an event | LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).<br>If no event is read, **0** is returned.<br>If an event is successfully read, a positive value (event set) is returned.<br>In other cases, an error code is returned.|
| Event write| LOS_EventWrite | Writes an event to the event control block.| | Writing an event | LOS_EventWrite | Writes an event to the event control block.|
| Event clearance| LOS_EventClear | Clears an event in the event control block based on the event mask.| | Clearing events | LOS_EventClear | Clears events in the event control block based on the event mask. |
| Event destruction| LOS_EventDestroy | Destroys an event control block.| | Destroying events | LOS_EventDestroy | Destroys an event control block.|
## How to Develop ## How to Develop
...@@ -72,11 +82,11 @@ The typical event development process is as follows: ...@@ -72,11 +82,11 @@ The typical event development process is as follows:
1. Initialize an event control block. 1. Initialize an event control block.
2. Block a read event control block. 2. Block a read event.
3. Write related events. 3. Write events.
4. Wake up a blocked task, read the event, and check whether the event meets conditions. 4. Wake up the blocked task, read the event, and check whether the event meets conditions.
5. Handle the event control block. 5. Handle the event control block.
...@@ -84,7 +94,7 @@ The typical event development process is as follows: ...@@ -84,7 +94,7 @@ The typical event development process is as follows:
> **NOTE** > **NOTE**
> - When an event is read or written, the 25th bit of the event is reserved and cannot be set. > - For event read and write operations, the 25th bit (`0x02U << 24`) of the event is reserved and cannot be set.
> >
> - Repeated writes of the same event are treated as one write. > - Repeated writes of the same event are treated as one write.
...@@ -111,7 +121,7 @@ In the **ExampleEvent** task, create an **EventReadTask** task with a timout per ...@@ -111,7 +121,7 @@ In the **ExampleEvent** task, create an **EventReadTask** task with a timout per
The sample code is as follows: The sample code is as follows:
The sample code is compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleEvent()** in **TestTaskEntry**. The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleEvent()** function is called in **TestTaskEntry**.
``` ```
......
...@@ -77,7 +77,7 @@ The preceding figure illustrates how to write data to the tail node only. Writin ...@@ -77,7 +77,7 @@ The preceding figure illustrates how to write data to the tail node only. Writin
## Available APIs ## Available APIs
| Category| Description| | Category| API Description |
| -------- | -------- | | -------- | -------- |
| Creating or deleting a message queue| **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.<br>**LOS_QueueCreateStatic**: creates a static message queue. You need to pass in the queue space.<br>**LOS_QueueDelete**: deletes a message queue. After a static message queue is deleted, you need to release the queue space.| | Creating or deleting a message queue| **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.<br>**LOS_QueueCreateStatic**: creates a static message queue. You need to pass in the queue space.<br>**LOS_QueueDelete**: deletes a message queue. After a static message queue is deleted, you need to release the queue space.|
| Reading or writing data (address without the content) in a queue| **LOS_QueueRead**: reads data in the head node of the specified queue. The data in the queue node is an address.<br>**LOS_QueueWrite**: writes the **bufferAddr** (buffer address) to the tail node of the specified queue.<br>**LOS_QueueWriteHead**: writes the **bufferAddr** (buffer address) to the head node of the specified queue.| | Reading or writing data (address without the content) in a queue| **LOS_QueueRead**: reads data in the head node of the specified queue. The data in the queue node is an address.<br>**LOS_QueueWrite**: writes the **bufferAddr** (buffer address) to the tail node of the specified queue.<br>**LOS_QueueWriteHead**: writes the **bufferAddr** (buffer address) to the head node of the specified queue.|
...@@ -136,7 +136,7 @@ Create a queue and two tasks. Enable task 1 to write data to the queue, and task ...@@ -136,7 +136,7 @@ Create a queue and two tasks. Enable task 1 to write data to the queue, and task
The sample code is as follows: The sample code is as follows:
The sample code is compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleQueue** in **TestTaskEntry**. The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleQueue** function is called in **TestTaskEntry**.
``` ```
......
此差异已折叠。
...@@ -36,7 +36,7 @@ base/telephony/ ...@@ -36,7 +36,7 @@ base/telephony/
## Constraints ## Constraints
1. The open-source version currently provides the cellular call (CS call only), SMS & MMS, and cellular data services and supports the dual-SIM framework. 1. The open-source version currently provides the cellular call (CS call only), SMS & MMS, and cellular data services and supports the dual-SIM framework.
2. The Hardware Device Interface (HDI) support is subject to the chip vendors' adaptation capability. For details, see [Telephony Development](../device-dev/subsystems/subsys-tel-guide). 2. The Hardware Device Interface (HDI) support is subject to the chip vendors' adaptation capability. For details, see [Telephony Development](../device-dev/subsystems/subsys-tel-overview.md).
## Usage Guidelines ## Usage Guidelines
......
...@@ -79,8 +79,8 @@ function getRdbStoreV9(context: Context, config: StoreConfigV9, version: number) ...@@ -79,8 +79,8 @@ function getRdbStoreV9(context: Context, config: StoreConfigV9, version: number)
``` ```
The APIs are migrated from **@ohos.data.rdb.d.ts** to **@ohos.data.relationalStore.d.ts**. The APIs are migrated from **@ohos.data.rdb.d.ts** to **@ohos.data.relationalStore.d.ts**.
``` ```
function getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void; function getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void;
function getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore>; function getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore>;
``` ```
**Adaptation Guide** **Adaptation Guide**
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册