提交 fabae0b8 编写于 作者: L liyan 提交者: Gitee

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

Signed-off-by: Nliyan <liyan339@h-partners.com>
......@@ -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/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/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids
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
zh-cn/application-dev/faqs/ @zengyawen
zh-cn/application-dev/file-management/ @zengyawen
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-errorCode.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
......@@ -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-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/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-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-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-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125
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
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-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-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
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
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-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-WorkSchedulerExtensionAbility.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-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-zlib.md @shuaytao @RayShih @wangzhen107 @inter515
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
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-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-resourceschedule-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen
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-workScheduler.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 @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
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 @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-system-capability.md taiyipei taiyipei BlackStone
zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen
......
......@@ -18,7 +18,7 @@
- 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)了解版本详情。
......
......@@ -69,7 +69,7 @@ This topic describes how to use the context in the following scenarios:
- [Obtaining the Application Development Path](#obtaining-the-application-development-path)
- [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas)
- [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
......@@ -111,7 +111,7 @@ The capability of obtaining the application development path is provided by the
| bundleCodeDir | {Path prefix}/el1/bundle/|
| cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/|
| 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/|
| databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/|
| distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/|
......@@ -136,6 +136,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
......@@ -177,8 +180,10 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
>
> - 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.
```ts
......@@ -194,6 +199,7 @@ 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.
> **NOTE**
>
......@@ -202,7 +208,9 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> - 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
import UIAbility from '@ohos.app.ability.UIAbility';
......@@ -231,11 +239,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
......@@ -249,36 +257,36 @@ export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
let abilityLifecycleCallback = {
onAbilityCreate(ability) {
console.info(TAG, "onAbilityCreate ability:" + JSON.stringify(ability));
onAbilityCreate(uiability) {
console.info(TAG, "onAbilityCreate uiability:" + JSON.stringify(uiability));
},
onWindowStageCreate(ability, windowStage) {
console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability));
onWindowStageCreate(uiability, windowStage) {
console.info(TAG, "onWindowStageCreate uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
},
onWindowStageActive(ability, windowStage) {
console.info(TAG, "onWindowStageActive ability:" + JSON.stringify(ability));
onWindowStageActive(uiability, windowStage) {
console.info(TAG, "onWindowStageActive uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageInactive(ability, windowStage) {
console.info(TAG, "onWindowStageInactive ability:" + JSON.stringify(ability));
onWindowStageInactive(uiability, windowStage) {
console.info(TAG, "onWindowStageInactive uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageDestroy(ability, windowStage) {
console.info(TAG, "onWindowStageDestroy ability:" + JSON.stringify(ability));
onWindowStageDestroy(uiability, windowStage) {
console.info(TAG, "onWindowStageDestroy uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
},
onAbilityDestroy(ability) {
console.info(TAG, "onAbilityDestroy ability:" + JSON.stringify(ability));
onAbilityDestroy(uiability) {
console.info(TAG, "onAbilityDestroy uiability:" + JSON.stringify(uiability));
},
onAbilityForeground(ability) {
console.info(TAG, "onAbilityForeground ability:" + JSON.stringify(ability));
onAbilityForeground(uiability) {
console.info(TAG, "onAbilityForeground uiability:" + JSON.stringify(uiability));
},
onAbilityBackground(ability) {
console.info(TAG, "onAbilityBackground ability:" + JSON.stringify(ability));
onAbilityBackground(uiability) {
console.info(TAG, "onAbilityBackground uiability:" + JSON.stringify(uiability));
},
onAbilityContinue(ability) {
console.info(TAG, "onAbilityContinue ability:" + JSON.stringify(ability));
onAbilityContinue(uiability) {
console.info(TAG, "onAbilityContinue uiability:" + JSON.stringify(uiability));
}
}
// 1. Obtain the application context through the context attribute.
......
......@@ -9,7 +9,7 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md): ExtensionAbility component of the form type, which provides APIs related to widgets.
- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md): ExtensionAbility component of the work_scheduler type, which provides APIs for registering, canceling, and querying Work Scheduler tasks.
- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md): ExtensionAbility component of the work_scheduler type, which provides callbacks for Work Scheduler tasks.
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md): ExtensionAbility component of the input_method type, which provides an input method framework that can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more.
......@@ -33,6 +33,7 @@ All types of ExtensionAbility components are started by the corresponding system
The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md) as an example. As shown in the figure below, when an application calls the InputMethodExtensionAbility component, the input method management service is called first. The input method management service starts the InputMethodExtensionAbility component, returns the component to the application, and starts to manage its lifecycle.
**Figure 1** Using the InputMethodExtensionAbility component
![ExtensionAbility-start](figures/ExtensionAbility-start.png)
......@@ -48,11 +49,11 @@ You do not need to care when to add or delete a widget. The lifecycle of the For
> **NOTE**
>
> For an application, all ExtensionAbility components of the same type run in an independent process, whereas UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in another independent process. For details, see [Process Model (Stage Model)](process-model-stage.md).
>
>
> For example, an application has one UIAbility component, one ServiceExtensionAbility, one DataShareExtensionAbility, two FormExtensionAbility, and one ImeExtensionAbility. When the application is running, there are three processes:
>
>
> - UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility run in an independent process.
>
>
> - The two FormExtensionAbility components run in an independent process.
>
>
> - The two ImeExtensionAbility components run in an independent process.
......@@ -21,8 +21,7 @@ The following figure shows the basic concepts used in the stage model.
- [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)
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**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below.
### 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**
......@@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
```ts
import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.rdb';
import rdb from '@ohos.data.relationalStore';
import fileIo from '@ohos.fileio';
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
const DB_NAME = "DB00.db";
......@@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
let rdbStore;
let result;
export default class DataShareExtAbility extends Extension {
private rdbStore_;
// Override onCreate().
onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt'
result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store.
rdb.getRdbStore(this.context, {
name: DB_NAME
}, 1, function (err, data) {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
}, function (err, data) {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
});
callback();
if (callbakc) {
callback();
}
});
}
// Override query().
query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) {
......@@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
};
```
6. Define **DataShareExtensionAbility** in **module.json5**.
7. Define **DataShareExtensionAbility** in **module.json5**.
| Field | Description |
| --------- | ------------------------------------------------------------ |
| "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. |
| "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**. |
| | |
| Field| Description |
| ------------ | ------------------------------------------------------------ |
| "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.|
| "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**.|
**module.json5 example**
......@@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
]
```
### Data Consumer Application Development
1. Import dependencies.
......@@ -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 updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = new Array("*");
let valArray = ['*'];
// Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, 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
| 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**
......@@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local
### Transaction
Table 15 Transaction APIs
**Table 15** Transaction APIs
| Class | API | Description |
| -------- | ----------------------- | --------------------------------- |
......@@ -202,44 +202,82 @@ Table 15 Transaction APIs
```js
import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
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",
securityLevel: data_rdb.SecurityLevel.S1}
// Assume that the current RDB store version is 3.
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
// 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
}
})
```
Stage model:
```ts
import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
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.
(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.
......@@ -384,14 +422,13 @@ Table 15 Transaction APIs
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.
(2) Call the resultSet() API to obtain the result.
The sample code is as follows:
```js
```js
let rdbPredicate = new data_rdb.RdbPredicates('employee')
predicates.greaterThan("id", 0)
let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate)
......@@ -406,31 +443,32 @@ Table 15 Transaction APIs
}).catch((err) => {
console.info("failed to remoteQuery, err: " + err)
})
```
```
9. Back up and restore an 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")
promiseBackup.then(() => {
console.info('Backup success.')
console.info('Backup success.')
}).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")
promiseRestore.then(() => {
console.info('Restore success.')
console.info('Restore success.')
}).catch((err) => {
console.info('Restore failed, err: ' + err)
console.info('Restore failed, err: ' + err)
})
```
```
......@@ -83,7 +83,7 @@ export default class MyAbilityStage extends AbilityStage {
### 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.
The following is an example of **MainAbility**:
The following is an example of **EntryAbility**:
#### Importing the Service Package
......@@ -109,7 +109,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
onWindowStageCreate(windowStage) {
// Main window is created. Set a main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
console.log("[Demo] EntryAbility onWindowStageCreate")
globalThis.registerObserver = (() => {
registerId = errorManager.registerErrorObserver(callback);
......@@ -121,12 +121,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
- 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
onSaveState(state, wantParams) {
// Save application data.
console.log("[Demo] MainAbility onSaveState")
console.log("[Demo] EntryAbility onSaveState")
wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE;
}
......@@ -134,12 +134,12 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state,
- 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
storage: LocalStorage
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
console.log("[Demo] EntryAbility onCreate")
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage();
......@@ -155,7 +155,7 @@ onCreate(want, launchParam) {
```ts
onWindowStageDestroy() {
// Main window is destroyed to release UI resources.
console.log("[Demo] MainAbility onWindowStageDestroy")
console.log("[Demo] EntryAbility onWindowStageDestroy")
globalThis.unRegisterObserver = (() => {
errorManager.unregisterErrorObserver(registerId, (result) => {
......@@ -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.
```ts
export default class MainAbility extends Ability {
export default class EntryAbility extends Ability {
storage: LocalStorage
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
console.log("[Demo] EntryAbility onCreate")
globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage();
......@@ -185,7 +185,7 @@ export default class MainAbility extends Ability {
onSaveState(state, wantParams) {
// Save application data.
console.log("[Demo] MainAbility onSaveState")
console.log("[Demo] EntryAbility onSaveState")
wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE;
}
......
......@@ -36,8 +36,8 @@ When an asynchronous callback is used, the return value can be processed directl
## Development Example
```ts
import Ability from '@ohos.application.Ability'
import errorManager from '@ohos.application.errorManager'
import UIAbility from '@ohos.app.ability.UIAbility';
import errorManager from '@ohos.application.errorManager';
var registerId = -1;
var callback = {
......@@ -45,15 +45,15 @@ var callback = {
console.log(errMsg);
}
}
export default class MainAbility extends Ability {
export default class EntryAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
console.log("[Demo] EntryAbility onCreate")
registerId = errorManager.registerErrorObserver(callback);
globalThis.abilityWant = want;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy")
console.log("[Demo] EntryAbility onDestroy")
errorManager.unregisterErrorObserver(registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message)
});
......@@ -61,7 +61,7 @@ export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
// Main window is created for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
console.log("[Demo] EntryAbility onWindowStageCreate")
windowStage.loadContent("pages/index", (err, data) => {
if (err.code) {
......@@ -74,17 +74,17 @@ export default class MainAbility extends Ability {
onWindowStageDestroy() {
// Main window is destroyed to release UI resources.
console.log("[Demo] MainAbility onWindowStageDestroy")
console.log("[Demo] EntryAbility onWindowStageDestroy")
}
onForeground() {
// Ability is brought to the foreground.
console.log("[Demo] MainAbility onForeground")
console.log("[Demo] EntryAbility onForeground")
}
onBackground() {
// 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
```js
import hilog from '@ohos.hilog';
import Ability from '@ohos.application.Ability'
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window'
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'
export default class EntryAbility extends Ability {
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
......
......@@ -33,7 +33,7 @@ ArkTS sample code:
globalThis.context.startAbilityForResult(
{
bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility",
abilityName: "MainAbility",
parameters: {
'startMode': 'choose', //choose or save
}
......@@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult(
globalThis.context.startAbilityForResult(
{
bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility",
abilityName: "MainAbility",
parameters: {
'startMode': 'save', //choose or save
'saveFile': 'test.jpg',
......
此差异已折叠。
此差异已折叠。
......@@ -2,13 +2,13 @@
## When to Use
With the APIs provided by the **Camera** module, you can access and operate camera devices and develop new functions. Common operations include preview, photographing, and video recording. You can also implement flash control, exposure time control, focus mode control, zooming control, and many others.
With the APIs provided by the **Camera** module, you can access and operate camera devices and develop new functions. Common operations include preview, photographing, and video recording. You can also implement flash control, exposure time control, focus mode control, zoom control, and much more.
Before calling camera APIs, be familiar with the following concepts:
- **Static camera capabilities**: A series of parameters used to describe inherent capabilities of a camera, such as orientation and supported resolution.
- **Physical camera**: An independent camera device. The physical camera ID is a string that uniquely identifies a physical camera.
- **Asynchronous operation**: To prevent the UI thread from being blocked, most **Camera** calls are asynchronous. Each API provides the callback and promise functions.
- **Asynchronous operation**: A non-blocking operation that allows other operations to execute before it completes. To prevent the UI thread from being blocked, some **Camera** calls are asynchronous. Each asynchronous API provides the callback and promise functions.
## How to Develop
......@@ -22,7 +22,7 @@ The full process includes applying for permissions, creating an instance, settin
#### Applying for Permissions
You must apply for the permission for your application to access the camera device and other functions. The following table lists camera-related permissions.
You must apply for the permissions for your application to access the camera device and other functions. The following table lists camera-related permissions.
| Permission| Attribute Value |
| -------- | ------------------------------ |
......@@ -51,82 +51,108 @@ function applyPermission() {
#### Creating an Instance
You must create an independent **CameraManager** instance before performing camera operations. If this operation fails, the camera may be occupied or unusable. If the camera is occupied, wait until it is released. You can call **getSupportedCameras()** to obtain the list of cameras supported by the current device. The list stores all camera IDs of the current device. If the list is not empty, each ID in the list can be used to create an independent camera instance. If the list is empty, no camera is available for the current device and subsequent operations cannot be performed. The camera has preview, shooting, video recording, and metadata streams. You can use **getSupportedOutputCapability()** to obtain the output stream capabilities of the camera and configure them in the **profile** field in **CameraOutputCapability**. The procedure for creating a **CameraManager** instance is as follows:
You must create an independent **CameraManager** instance before performing camera operations. If this operation fails, the camera may be occupied or unusable. If the camera is occupied, wait until it is released. You can call **getSupportedCameras()** to obtain the list of cameras supported by the current device. The list stores all camera IDs of the current device. Each of these IDs can be used to create an independent **CameraManager** instance. If the list is empty, no camera is available for the current device and subsequent operations cannot be performed. The camera has preview, shooting, video recording, and metadata output streams. You can use **getSupportedOutputCapability()** to obtain the output stream capabilities of the camera and configure them in the **profile** field in **CameraOutputCapability**. The procedure for creating a **CameraManager** instance is as follows:
```typescript
import camera from '@ohos.multimedia.camera'
import image from '@ohos.multimedia.image'
import media from '@ohos.multimedia.media'
// Create a CameraManager object.
// Create a CameraManager instance.
context: any = getContext(this)
let cameraManager = await camera.getCameraManager(this.context)
let cameraManager = camera.getCameraManager(this.context)
if (!cameraManager) {
console.error('Failed to get the CameraManager instance');
}
console.error("camera.getCameraManager error")
return;
}
// Listen for camera state changes.
cameraManager.on('cameraStatus', (cameraStatusInfo) => {
console.log(`camera : ${cameraStatusInfo.camera.cameraId}`);
console.log(`status: ${cameraStatusInfo.status}`);
})
// Obtain the camera list.
let cameraArray = await cameraManager.getSupportedCameras()
if (!cameraArray) {
console.error('Failed to get the cameras');
}
let cameraArray = cameraManager.getSupportedCameras();
if (cameraArray.length <= 0) {
console.error("cameraManager.getSupportedCameras error")
return;
}
for (let index = 0; index < cameraArray.length; index++) {
console.log('cameraId : ' + cameraArray[index].cameraId) // Obtain the camera ID.
console.log('cameraPosition : ' + cameraArray[index].cameraPosition) // Obtain the camera position.
console.log('cameraType : ' + cameraArray[index].cameraType) // Obtain the camera type.
console.log('connectionType : ' + cameraArray[index].connectionType) // Obtain the camera connection type.
console.log('cameraId : ' + cameraArray[index].cameraId); // Obtain the camera ID.
console.log('cameraPosition : ' + cameraArray[index].cameraPosition); // Obtain the camera position.
console.log('cameraType : ' + cameraArray[index].cameraType); // Obtain the camera type.
console.log('connectionType : ' + cameraArray[index].connectionType); // Obtain the camera connection type.
}
// Create a camera input stream.
let cameraInput = await cameraManager.createCameraInput(cameraArray[0])
let cameraInput
try {
cameraInput = cameraManager.createCameraInput(cameraArray[0]);
} catch () {
console.error('Failed to createCameraInput errorCode = ' + error.code);
}
// Listen for CameraInput errors.
let cameraDevice = cameraArray[0];
cameraInput.on('error', cameraDevice, (error) => {
console.log(`Camera input error code: ${error.code}`);
})
// Open camera
// Open the camera.
await cameraInput.open();
// Obtain the output stream capabilities supported by the camera.
let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]);
let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]);
if (!cameraOutputCap) {
console.error("outputCapability outputCapability == null || undefined")
} else {
console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
console.error("cameraManager.getSupportedOutputCapability error")
return;
}
console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
let previewProfilesArray = cameraOutputCap.GetPreviewProfiles();
let previewProfilesArray = cameraOutputCap.previewProfiles;
if (!previewProfilesArray) {
console.error("createOutput previewProfilesArray == null || undefined")
}
let photoProfilesArray = cameraOutputCap.GetPhotoProfiles();
let photoProfilesArray = cameraOutputCap.photoProfiles;
if (!photoProfilesArray) {
console.error("createOutput photoProfilesArray == null || undefined")
}
let videoProfilesArray = cameraOutputCap.GetVideoProfiles();
let videoProfilesArray = cameraOutputCap.videoProfiles;
if (!videoProfilesArray) {
console.error("createOutput videoProfilesArray == null || undefined")
}
let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType();
let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes;
if (!metadataObjectTypesArray) {
console.error("createOutput metadataObjectTypesArray == null || undefined")
}
// Create a preview stream. For details about the surfaceId parameter, see the XComponent section. The preview stream is the surface provided by the XComponent.
let previewOutput = await cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
if (!previewOutput) {
let previewOutput
try {
previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
} catch (error) {
console.error("Failed to create the PreviewOutput instance.")
}
// Create an ImageReceiver object and set photo parameters. The resolution is set based on the photographing resolutions supported by the current device, which are obtained by photoProfilesArray.
// Listen for PreviewOutput errors.
previewOutput.on('error', (error) => {
console.log(`Preview output error code: ${error.code}`);
})
// Create an ImageReceiver instance and set photo parameters. Wherein, the resolution must be one of the photographing resolutions supported by the current device, which are obtained by photoProfilesArray.
let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8)
// Obtain the surface ID for displaying the photos.
let photoSurfaceId = await imageReceiver.getReceivingSurfaceId()
// Create a photographing output stream.
let photoOutput = await cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
if (!photoOutput) {
console.error('Failed to create the PhotoOutput instance.');
return;
let photoOutput
try {
photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
} catch (error) {
console.error('Failed to createPhotoOutput errorCode = ' + error.code);
}
// Define video recording parameters.
......@@ -168,12 +194,18 @@ videoRecorder.getInputSurface().then((id) => {
videoSurfaceId = id
})
// Create a VideoOutput object.
let videoOutput = await cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId)
if (!videoOutput) {
console.error('Failed to create the videoOutput instance.');
return;
// Create a VideoOutput instance.
let videoOutput
try {
videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId)
} catch (error) {
console.error('Failed to create the videoOutput instance. errorCode = ' + error.code);
}
// Listen for VideoOutput errors.
videoOutput.on('error', (error) => {
console.log(`Preview output error code: ${error.code}`);
})
```
Surfaces must be created in advance for the preview, shooting, and video recording stream. The preview stream is the surface provided by the **XComponent**, the shooting stream is the surface provided by **ImageReceiver**, and the video recording stream is the surface provided by **VideoRecorder**.
......@@ -247,24 +279,45 @@ function getVideoRecorderSurface() {
```typescript
// Create a session.
let captureSession = await camera.createCaptureSession()
if (!captureSession) {
console.error('Failed to create the CaptureSession instance.');
return;
let captureSession
try {
captureSession = cameraManager.createCaptureSession()
} catch (error) {
console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code);
}
console.log('Callback returned with the CaptureSession instance.' + session);
// Listen for session errors.
captureSession.on('error', (error) => {
console.log(`Capture session error code: ${error.code}`);
})
// Start configuration for the session.
await captureSession.beginConfig()
try {
captureSession.beginConfig()
} catch (error) {
console.error('Failed to beginConfig. errorCode = ' + error.code);
}
// Add the camera input stream to the session.
await captureSession.addInput(cameraInput)
try {
captureSession.addInput(cameraInput)
} catch (error) {
console.error('Failed to addInput. errorCode = ' + error.code);
}
// Add the preview input stream to the session.
await captureSession.addOutput(previewOutput)
try {
captureSession.addOutput(previewOutput)
} catch (error) {
console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code);
}
// Add the photographing output stream to the session.
await captureSession.addOutput(photoOutput)
try {
captureSession.addOutput(photoOutput)
} catch (error) {
console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code);
}
// Commit the session configuration.
await captureSession.commitConfig()
......@@ -282,13 +335,25 @@ await captureSession.start().then(() => {
await captureSession.stop()
// Start configuration for the session.
await captureSession.beginConfig()
try {
captureSession.beginConfig()
} catch (error) {
console.error('Failed to beginConfig. errorCode = ' + error.code);
}
// Remove the photographing output stream from the session.
await captureSession.removeOutput(photoOutput)
try {
captureSession.removeOutput(photoOutput)
} catch (error) {
console.error('Failed to removeOutput(photoOutput). errorCode = ' + error.code);
}
// Add a video recording output stream to the session.
await captureSession.addOutput(videoOutput)
try {
captureSession.addOutput(videoOutput)
} catch (error) {
console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code);
}
// Commit the session configuration.
await captureSession.commitConfig()
......@@ -303,71 +368,65 @@ await captureSession.start().then(() => {
```typescript
// Check whether the camera has flash.
let flashStatus = await captureSession.hasFlash()
if (!flashStatus) {
console.error('Failed to check whether the device has the flash mode.');
let flashStatus
try {
flashStatus = captureSession.hasFlash()
} catch (error) {
console.error('Failed to hasFlash. errorCode = ' + error.code);
}
console.log('Promise returned with the flash light support status:' + flashStatus);
if (flashStatus) {
// Check whether the auto flash mode is supported.
let flashModeStatus
captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, async (err, status) => {
if (err) {
console.error('Failed to check whether the flash mode is supported. ${err.message}');
return;
}
console.log('Callback returned with the flash mode support status: ' + status);
try {
let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO)
flashModeStatus = status
})
} catch (error) {
console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code);
}
if(flashModeStatus) {
// Set the flash mode to auto.
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, async (err) => {
if (err) {
console.error('Failed to set the flash mode ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setFlashMode.');
})
try {
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO)
} catch (error) {
console.error('Failed to set the flash mode. errorCode = ' + error.code);
}
}
}
// Check whether the continuous auto focus is supported.
let focusModeStatus
captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err, status) => {
if (err) {
console.error('Failed to check whether the focus mode is supported. ${err.message}');
return;
}
console.log('Callback returned with the focus mode support status: ' + status);
try {
let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
focusModeStatus = status
})
} catch (error) {
console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code);
}
if (focusModeStatus) {
// Set the focus mode to continuous auto focus.
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err) => {
if (err) {
console.error('Failed to set the focus mode ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setFocusMode.');
})
try {
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
} catch (error) {
console.error('Failed to set the focus mode. errorCode = ' + error.code);
}
}
// Obtain the zoom ratio range supported by the camera.
let zoomRatioRange = await captureSession.getZoomRatioRange()
if (!zoomRatioRange) {
console.error('Failed to get the zoom ratio range.');
return;
let zoomRatioRange
try {
zoomRatioRange = captureSession.getZoomRatioRange()
} catch (error) {
console.error('Failed to get the zoom ratio range. errorCode = ' + error.code);
}
// Set a zoom ratio.
captureSession.setZoomRatio(zoomRatioRange[0], async (err) => {
if (err) {
console.error('Failed to set the zoom ratio value ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setZoomRatio.');
})
try {
captureSession.setZoomRatio(zoomRatioRange[0])
} catch (error) {
console.error('Failed to set the zoom ratio value. errorCode = ' + error.code);
}
```
#### Taking Photos
......@@ -428,7 +487,7 @@ For details about the APIs used for saving photos, see [Image Processing](image.
captureSession.stop()
// Release the camera input stream.
cameraInput.release()
cameraInput.close()
// Release the preview output stream.
previewOutput.release()
......@@ -449,4 +508,4 @@ captureSession = null
## Process Flowchart
The following figure shows the process of using the camera.
![camera_framework process](figures/camera_framework_process.jpg)
![camera_framework process](figures/camera_framework_process.png)
......@@ -3,7 +3,7 @@
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|
| -------- | -------- | -------- | -------- |
......@@ -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)|
| 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 | 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|
| 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|
| -------- | -------- | -------- | -------- |
......@@ -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)|
| 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
"app": {
......
......@@ -49,7 +49,7 @@ Example of the **config.json** file:
],
"commonEvents": [
{
"name": ".MainAbility",
"name": ".EntryAbility",
"permission": "ohos.permission.GET_BUNDLE_INFO",
"data": [
"com.example.demo",
......
......@@ -46,33 +46,77 @@ struct bindPopupPage {
## 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.
Example:
```ts
// xxx.ets
@Entry
@Component
struct IndexPage {
// Incorrect: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
1. The data types of state variables decorated by state decorators must be explicitly declared. They cannot be declared as **any** or **Date**.
Example:
```ts
// xxx.ets
@Entry
@Component
struct DatePickerExample {
// Incorrect: @State isLunar: any = false
@State isLunar: boolean = false
// Incorrect: @State selectedDate: Date = new Date('2021-08-08')
private selectedDate: Date = new Date('2021-08-08')
build() {
Column() {
Button('Switch Calendar')
.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
......@@ -98,6 +142,8 @@ The allowed method depends on the decorator of the state variable, as shown in t
| @Link | Forbidden | Mandatory |
| @StorageLink | Mandatory | Forbidden |
| @StorageProp | Mandatory | Forbidden |
| @LocalStorageLink | Mandatory | Forbidden |
| @LocalStorageProp | Mandatory | Forbidden |
| @Provide | Mandatory | Optional |
| @Consume | Forbidden | Forbidden |
| @ObjectLink | Forbidden | Mandatory |
......@@ -111,25 +157,78 @@ As indicated by the preceding table:
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|
| -------------------------------------------- | ------ | ------ | ------ | -------- |
| @State | Not allowed| Allowed | Allowed | Allowed |
| @Link | Not allowed| Allowed | Not recommended| Allowed |
| @Prop | Not allowed| Not allowed| Allowed | Allowed |
| @StorageLink | Not allowed| Allowed | Not allowed| Not allowed |
| @StorageProp | Not allowed| Not allowed| Not allowed| Allowed |
| Normal variable | Allowed | Not allowed| Not allowed| Allowed |
| **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** |
|---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------|
| **regular** | Supported | Supported | Supported | Supported | Not supported | Not supported | Supported |
| **@State** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| **@Link** | Not supported | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
| **@Prop** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| **@Provide** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| **@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.
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
- **@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.
- **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.
### 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|
| -------- | -------- | -------- | -------- |
......@@ -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 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|
| -------- | -------- | -------- | -------- |
......@@ -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**)|
| 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|
| -------- | -------- | -------- | -------- |
| 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)|
#### 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|
| -------- | -------- | -------- | -------- |
| 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|
| -------- | -------- | -------- | -------- |
| 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)|
### Example of the deviceConfig Tag
Example of the **deviceConfig** tag:
```json
"deviceConfig": {
......
......@@ -122,7 +122,7 @@
- continuation
- [continuationExtraParams](js-apis-continuation-continuationExtraParams.md)
- [continuationResult](js-apis-continuation-continuationResult.md)
- Common Event and Notification
- [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md)
- [@ohos.events.emitter (Emitter)](js-apis-emitter.md)
......@@ -203,7 +203,6 @@
- [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md)
- security
- [PermissionRequestResult](js-apis-permissionrequestresult.md)
- Data Management
- [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md)
- [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md)
......@@ -215,11 +214,15 @@
- [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md)
- [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md)
- data/rdb
- [resultSet](js-apis-data-resultset.md)
- [resultSet (Result Set)](js-apis-data-resultset.md)
- 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.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.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.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
| 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**
......
......@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| 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.|
| 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:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| 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.|
**Return value**
......@@ -139,9 +141,11 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| 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. |
| 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:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| 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.|
**Return value**
......@@ -294,9 +300,11 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| 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. |
| 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:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| 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.|
**Return value**
......@@ -428,9 +438,9 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......
......@@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
// 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.")
})
......@@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
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
......@@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
// 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)
......@@ -170,35 +147,23 @@ promise.then(async (rdbStore) => {
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
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
......@@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
......@@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
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
......@@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
......@@ -318,24 +277,18 @@ promise.then(()=>{
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
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
......@@ -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_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
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
| 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
......
# @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.
> **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 support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import environment from '@ohos.environment';
import environment from '@ohos.file.environment';
```
## environment.getStorageDataDir
......@@ -30,10 +31,10 @@ Obtains the root directory of the storage. This API uses a promise to return the
**Example**
```js
environment.getStorageDataDir().then(function(path){
console.info("getStorageDataDir successfully:"+ path);
}).catch(function(error){
console.info("getStorageDataDir failed with error:"+ error);
environment.getStorageDataDir().then((path) => {
console.info("getStorageDataDir successfully, Path: " + path);
}).catch((err) => {
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
**Example**
```js
environment.getStorageDataDir(function(error, path){
// do something
environment.getStorageDataDir((err, path) => {
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
**Example**
```js
environment.getUserDataDir().then(function(path){
console.info("getUserDataDir successfully:"+ path);
}).catch(function(error){
console.info("getUserDataDir failed with error:"+ error);
environment.getUserDataDir().then((path) => {
console.info("getUserDataDir successfully, Path: " + path);
}).catch((err) => {
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
**Example**
```js
environment.getUserDataDir(function(error, path){
// do something
environment.getUserDataDir((err, path) => {
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
try {
accountManager.activateOsAccount(localId, (err)=>{
if (err) {
console.log("activateOsAccount failed, error:" + JSON.stringify(err));
console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`);
} else {
console.log("activateOsAccount successfully");
}
});
} 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
try {
accountManager.checkMultiOsAccountEnabled((err, isEnabled) => {
if (err) {
console.log("checkMultiOsAccountEnabled failed, error: " + JSON.stringify(err));
console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
} else {
console.log("checkMultiOsAccountEnabled successfully, isEnabled: " + isEnabled);
}
});
} 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
accountManager.checkMultiOsAccountEnabled().then((isEnabled) => {
console.log('checkMultiOsAccountEnabled successfully, isEnabled: ' + isEnabled);
}).catch((err) => {
console.log('checkMultiOsAccountEnabled failed, error: ' + JSON.stringify(err));
console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
});
} 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
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**
>
......@@ -3634,7 +3634,7 @@ Obtains the ID of the distributed virtual device. This API uses an asynchronous
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**
>
......@@ -4323,13 +4323,13 @@ Unregisters this PIN inputer.
pinAuth.unregisterInputer();
```
### InputerManager <sup>10+</sup>
## InputerManager <sup>9+</sup>
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.
......@@ -4357,11 +4357,10 @@ Register a credential inputer.
**Example**
```js
let inputerMgr = new account_osAccount.InputerManager();
let authType = account_osAccount.AuthType.DOMAIN;
let password = new Uint8Array([0, 0, 0, 0, 0]);
try {
inputerMgr.registerInputer(authType, {
account_osAccount.InputerManager.registerInputer(authType, {
onGetData: (authSubType, callback) => {
callback.onSetData(authSubType, password);
}
......@@ -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.
......@@ -4398,16 +4397,129 @@ Unregisters this credential inputer.
**Example**
```js
let inputerMgr = new account_osAccount.InputerManager();
let authType = account_osAccount.AuthType.DOMAIN;
try {
inputerMgr.unregisterInputer(authType);
account_osAccount.InputerManager.unregisterInputer(authType);
console.log('unregisterInputer success.');
} catch(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>
Provides APIs for user identity management (IDM).
......
......@@ -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.
......@@ -170,19 +170,19 @@ let request = {
"flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
};
try {
privacyManager.getPermissionUsedRecords(request).then((data) => {
console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`);
privacyManager.getPermissionUsedRecord(request).then((data) => {
console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
}).catch((err) => {
console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`);
console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
});
} catch(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.
......@@ -225,11 +225,11 @@ let request = {
"flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
};
try {
privacyManager.getPermissionUsedRecords(request, (err, data) => {
privacyManager.getPermissionUsedRecord(request, (err, data) => {
if (err) {
console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`);
console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
} else {
console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`);
console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
}
});
} catch(err) {
......
......@@ -32,7 +32,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -40,7 +40,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
try {
promptAction.showToast({
message: 'Message Info',
duration: 2000,
duration: 2000
});
} catch (error) {
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/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -100,11 +100,11 @@ try {
buttons: [
{
text: 'button1',
color: '#000000',
color: '#000000'
},
{
text: 'button2',
color: '#000000',
color: '#000000'
}
],
})
......@@ -142,7 +142,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -154,11 +154,11 @@ try {
buttons: [
{
text: 'button1',
color: '#000000',
color: '#000000'
},
{
text: 'button2',
color: '#000000',
color: '#000000'
}
]
}, (err, data) => {
......@@ -218,7 +218,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -229,11 +229,11 @@ try {
buttons: [
{
text: 'item1',
color: '#666666',
color: '#666666'
},
{
text: 'item2',
color: '#000000',
color: '#000000'
},
]
}, (err, data) => {
......@@ -276,7 +276,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -287,11 +287,11 @@ try {
buttons: [
{
text: 'item1',
color: '#666666',
color: '#666666'
},
{
text: 'item2',
color: '#000000',
color: '#000000'
},
]
})
......
......@@ -11,8 +11,7 @@ If an application has a service that can be intuitively perceived by users and n
If a privileged system application needs to use certain system resources (for example, it wants to receive common events when suspended), it can request efficiency resources.
> **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 initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......
......@@ -563,6 +563,7 @@ Describes the page routing options.
> **NOTE**
>
> The page routing stack supports a maximum of 32 pages.
## RouterMode<sup>9+</sup>
......
......@@ -38,7 +38,7 @@ export default {
showToast() {
prompt.showToast({
message: 'Message Info',
duration: 2000,
duration: 2000
});
}
}
......@@ -67,11 +67,11 @@ export default {
showDialog() {
prompt.showDialog({
title: 'Title Info',
message: 'Message Info',
message: 'Message Info',
buttons: [
{
text: 'button',
color: '#666666',
color: '#666666'
},
],
success: function(data) {
......@@ -110,12 +110,12 @@ export default {
buttons: [
{
text: 'item1',
color: '#666666',
color: '#666666'
},
{
text: 'item2',
color: '#000000',
},
color: '#000000'
},
],
success: function(tapIndex) {
console.log('dialog success callback, click button : ' + data.tapIndex);
......
此差异已折叠。
......@@ -26,6 +26,7 @@
- [Exception Debugging](kernel-mini-memory-exception.md)
- [Trace](kernel-mini-memory-trace.md)
- [LMS](kernel-mini-memory-lms.md)
- [Shell](kernel-mini-debug-shell.md)
- Appendix
- [Kernel Coding Specification](kernel-mini-appx-code.md)
- [Standard Libraries](kernel-mini-appx-lib.md)
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册