提交 79eeef60 编写于 作者: 张海丰 提交者: Gitee

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

Signed-off-by: N张海丰 <zhanghaifeng11@huawei.com>
...@@ -132,7 +132,7 @@ zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 ...@@ -132,7 +132,7 @@ zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23
zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen
zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua
zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids
zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee
...@@ -244,7 +244,7 @@ zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease ...@@ -244,7 +244,7 @@ zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease
zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/faqs/ @zengyawen
zh-cn/application-dev/file-management/ @zengyawen zh-cn/application-dev/file-management/ @zengyawen
zh-cn/application-dev/application-test/ @ningningW zh-cn/application-dev/application-test/ @ningningW
zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-ability-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-ability-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
...@@ -275,10 +275,12 @@ zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @little ...@@ -275,10 +275,12 @@ zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @little
zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-application-Want.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-Want.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/application-models/windowextensionability.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-appmanager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen
zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-arraylist.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids zh-cn/application-dev/reference/apis/js-apis-audio.md @liuyuehua1 @zengyawen @magekkkk @currydavids
zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-battery-info.md @aqxyjay @zengyawen @aqxyjay @alien0208
zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208
...@@ -331,7 +333,7 @@ zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao ...@@ -331,7 +333,7 @@ zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @shuaytao
zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-display.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @zengyawen @JiDong-CS @murphy1984 zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @nianCode @zengyawen @JiDong-CS @murphy1984
zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-document.md @panqinxu @zengyawen @bubble_mao @jinhaihw
zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-effectKit.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-emitter.md @jayleehw @RayShih @li-weifeng2 @currydavids
...@@ -476,8 +478,9 @@ zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih ...@@ -476,8 +478,9 @@ zh-cn/application-dev/reference/apis/js-apis-wifiext.md @cheng_guohong @RayShih
zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-window.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @zhangqiang183 @ge-yafang @wind_zj @zxg-gitee
zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-worker.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-taskpool.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-xml.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-zlib.md @shuaytao @RayShih @wangzhen107 @inter515
zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 zh-cn/application-dev/reference/apis/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15
...@@ -537,10 +540,10 @@ zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @ze ...@@ -537,10 +540,10 @@ zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @ze
zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125
zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @wangwenli_wolf @ningningW @tangtiantian2021 @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001
zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-stationary.md @mayunteng_1 @ningningW @cococoler @alien0208
zh-cn/application-dev/reference/apis/js-apis-system-capability.md taiyipei taiyipei BlackStone zh-cn/application-dev/reference/apis/js-apis-system-capability.md taiyipei taiyipei BlackStone
zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zengyawen @handyohos @nan-xiansen
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
- master:最新开发版本。 - master:最新开发版本。
- OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。 - OpenHarmony 3.2 Beta5版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta5.md)了解版本详情。
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
......
...@@ -65,12 +65,13 @@ ...@@ -65,12 +65,13 @@
- [Internationalization](internationalization/Readme-EN.md) - [Internationalization](internationalization/Readme-EN.md)
- [Application Test](application-test/Readme-EN.md) - [Application Test](application-test/Readme-EN.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md) - [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md) - [Native APIs](napi/Readme-EN.md)
- Tools - Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- [Debugging Tools](tools/Readme-EN.md)
- Hands-On Tutorials - Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md)
- [Codelabs](https://gitee.com/openharmony/codelabs) - [Codelabs](https://gitee.com/openharmony/codelabs)
- API References - API References
- [SystemCapability](reference/syscap.md) - [SystemCapability](reference/syscap.md)
- [SystemCapability List](reference/syscap-list.md) - [SystemCapability List](reference/syscap-list.md)
......
...@@ -60,13 +60,7 @@ The **module.json5** of a browser application is as follows: ...@@ -60,13 +60,7 @@ The **module.json5** of a browser application is as follows:
} catch (error) { } catch (error) {
console.info(`explicit start ability failed with ${error.code}`) console.info(`explicit start ability failed with ${error.code}`)
} }
let context = getContext(this) as common.UIAbilityContext; }
await context.startAbility(want)
console.info(`explicit start ability succeed`)
} catch (error) {
console.info(`explicit start ability failed with ${error.code}`)
}
}
``` ```
The matching process is as follows: The matching process is as follows:
......
...@@ -34,11 +34,9 @@ There are two roles in **DataShare**: ...@@ -34,11 +34,9 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**. - Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below.
### Data Provider Application Development (Only for System Applications) ### Data Provider Application Development (Only for System Applications)
[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override the APIs as required. [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
- **onCreate** - **onCreate**
...@@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
```ts ```ts
import Extension from '@ohos.application.DataShareExtensionAbility'; import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.rdb'; import rdb from '@ohos.data.relationalStore';
import fileIo from '@ohos.fileio'; import fileIo from '@ohos.fileio';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
4. Override the **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. 5. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. 6. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```ts ```ts
const DB_NAME = "DB00.db"; const DB_NAME = "DB00.db";
...@@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
let result; let result;
export default class DataShareExtAbility extends Extension { export default class DataShareExtAbility extends Extension {
private rdbStore_; private rdbStore_;
// Override onCreate(). // Override onCreate().
onCreate(want, callback) { onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt' result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store. // Create an RDB store.
rdb.getRdbStore(this.context, { rdb.getRdbStore(this.context, {
name: DB_NAME name: DB_NAME,
}, 1, function (err, data) { securityLevel: rdb.SecurityLevel.S1
rdbStore = data; }, function (err, data) {
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { rdbStore = data;
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
}); });
callback(); if (callbakc) {
callback();
}
}); });
} }
// Override query(). // Override query().
query(uri, predicates, columns, callback) { query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) { if (predicates == null || predicates == undefined) {
...@@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
}; };
``` ```
7. Define **DataShareExtensionAbility** in **module.json5**.
6. Define **DataShareExtensionAbility** in **module.json5**.
| Field | Description | | Field| Description |
| --------- | ------------------------------------------------------------ | | ------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. | | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.|
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. | | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
| | |
**module.json5 example** **module.json5 example**
...@@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
] ]
``` ```
### Data Consumer Application Development ### Data Consumer Application Development
1. Import dependencies. 1. Import dependencies.
...@@ -212,7 +208,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -212,7 +208,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = new Array("*"); let valArray = ['*'];
// Insert a piece of data. // Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => { dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data); console.log("dsHelper insert result: " + data);
......
...@@ -142,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -142,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description | | Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | Synchronizes data between devices. This API uses a promise to return the result.<br>- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.<br>- **predicates**: specifies the data and devices to synchronize.<br>- **string**: device ID. <br>- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| | RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | Synchronizes data between devices. This API uses a promise to return the result.<br>- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.<br>- **predicates**: specifies the data and devices to synchronize.<br>- **string**: device ID. <br>- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.|
**Registering an RDB Store Observer** **Registering an RDB Store Observer**
...@@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local
### Transaction ### Transaction
Table 15 Transaction APIs **Table 15** Transaction APIs
| Class | API | Description | | Class | API | Description |
| -------- | ----------------------- | --------------------------------- | | -------- | ----------------------- | --------------------------------- |
...@@ -202,44 +202,82 @@ Table 15 Transaction APIs ...@@ -202,44 +202,82 @@ Table 15 Transaction APIs
```js ```js
import data_rdb from '@ohos.data.relationalStore' import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
const STORE_CONFIG = { name: "RdbTest.db", // Assume that the current RDB store version is 3.
securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST) // When an RDB store is created, the default version is 0.
console.info('create table done.') if (rdbStore.version == 0) {
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null)
// Set the RDB store version. The input parameter must be an integer greater than 0.
rdbStore.version = 3
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null)
rdbStore.version = 2
}
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null)
rdbStore.version = 3
}
}) })
``` ```
Stage model: Stage model:
```ts ```ts
import data_rdb from '@ohos.data.relationalStore' import data_rdb from '@ohos.data.relationalStore'
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
context = this.context const STORE_CONFIG = {
name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1
}
// Assume that the current RDB store version is 3.
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
// When an RDB store is created, the default version is 0.
if (rdbStore.version == 0) {
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null)
// Set the RDB store version. The input parameter must be an integer greater than 0.
rdbStore.version = 3
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null)
rdbStore.version = 2
}
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null)
rdbStore.version = 3
}
})
} }
} }
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = { name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
``` ```
2. Insert data. 2. Insert data.
(1) Create a **ValuesBucket** to store the data you need to insert. (1) Create a **ValuesBucket** instance to store the data you need to insert.
(2) Call the **insert()** method to insert data into the RDB store. (2) Call the **insert()** method to insert data into the RDB store.
...@@ -384,14 +422,13 @@ Table 15 Transaction APIs ...@@ -384,14 +422,13 @@ Table 15 Transaction APIs
8. Query data of a remote device. 8. Query data of a remote device.
(1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device. (1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device.
(2) Call the resultSet() API to obtain the result. (2) Call the resultSet() API to obtain the result.
The sample code is as follows: The sample code is as follows:
```js ```js
let rdbPredicate = new data_rdb.RdbPredicates('employee') let rdbPredicate = new data_rdb.RdbPredicates('employee')
predicates.greaterThan("id", 0) predicates.greaterThan("id", 0)
let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate)
...@@ -406,31 +443,32 @@ Table 15 Transaction APIs ...@@ -406,31 +443,32 @@ Table 15 Transaction APIs
}).catch((err) => { }).catch((err) => {
console.info("failed to remoteQuery, err: " + err) console.info("failed to remoteQuery, err: " + err)
}) })
``` ```
9. Back up and restore an RDB store. 9. Back up and restore an RDB store.
(1) Back up the current RDB store. (1) Back up the current RDB store.
The sample code is as follows: The sample code is as follows:
```js ```js
let promiseBackup = rdbStore.backup("dbBackup.db") let promiseBackup = rdbStore.backup("dbBackup.db")
promiseBackup.then(() => { promiseBackup.then(() => {
console.info('Backup success.') console.info('Backup success.')
}).catch((err) => { }).catch((err) => {
console.info('Backup failed, err: ' + err) console.info('Backup failed, err: ' + err)
}) })
``` ```
(2) Restore the RDB store using the backup file.
The sample code is as follows: (2) Restore the RDB store using the backup file.
```js The sample code is as follows:
```js
let promiseRestore = rdbStore.restore("dbBackup.db") let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(() => { promiseRestore.then(() => {
console.info('Restore success.') console.info('Restore success.')
}).catch((err) => { }).catch((err) => {
console.info('Restore failed, err: ' + err) console.info('Restore failed, err: ' + err)
}) })
``` ```
...@@ -20,13 +20,13 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -20,13 +20,13 @@ The following table lists the USB APIs currently available. For details, see the
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. | | getDevices(): Array<Readonly\<USBDevice>> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. | | bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise\<number> | Performs bulk transfer. |
| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. | | getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. |
| controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise\<number> | Performs control transfer. | | controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise&lt;number&gt; | Performs control transfer. |
## How to Develop ## How to Develop
...@@ -51,7 +51,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -51,7 +51,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
vendorId: 7531, vendorId: 7531,
productId: 2, productId: 2,
clazz: 9, clazz: 9,
subclass: 0, subClass: 0,
protocol: 1, protocol: 1,
devAddress: 1, devAddress: 1,
busNum: 1, busNum: 1,
...@@ -68,7 +68,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -68,7 +68,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
id: 0, id: 0,
protocol: 0, protocol: 0,
clazz: 9, clazz: 9,
subclass: 0, subClass: 0,
alternateSetting: 0, alternateSetting: 0,
name: "1-1", name: "1-1",
endpoints: [ endpoints: [
...@@ -93,7 +93,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -93,7 +93,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
``` ```
2. Obtain the device operation permissions. 2. Obtain the device operation permissions.
```js ```js
let deviceName = deviceList[0].name; let deviceName = deviceList[0].name;
...@@ -105,11 +105,11 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -105,11 +105,11 @@ You can set a USB device as the USB host to connect to other USB devices for dat
}); });
``` ```
3. Open the device. 3. Open the device.
```js ```js
// Open the device, and obtain the USB device pipe for data transfer. // Open the device, and obtain the USB device pipe for data transfer.
let pipe = usb.connectDevice(deviceList[0]); let interface1 = deviceList[0].configs[0].interfaces[0];
/* /*
Claim the corresponding interface from deviceList. Claim the corresponding interface from deviceList.
interface1 must be one present in the device configuration. interface1 must be one present in the device configuration.
...@@ -117,14 +117,16 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -117,14 +117,16 @@ You can set a USB device as the USB host to connect to other USB devices for dat
usb.claimInterface(pipe, interface1, true); usb.claimInterface(pipe, interface1, true);
``` ```
4. Perform data transfer. 4. Perform data transfer.
```js ```js
/* /*
Read data. Select the corresponding RX endpoint from deviceList for data transfer. Read data. Select the corresponding RX endpoint from deviceList for data transfer.
(endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array. (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array.
*/ */
let inEndpoint = interface1.endpoints[2];
let outEndpoint = interface1.endpoints[1];
let dataUint8Array = new Uint8Array(1024);
usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => { usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
if (dataLength >= 0) { if (dataLength >= 0) {
console.info("usb readData result Length : " + dataLength); console.info("usb readData result Length : " + dataLength);
...@@ -137,7 +139,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat ...@@ -137,7 +139,7 @@ You can set a USB device as the USB host to connect to other USB devices for dat
console.info("usb readData error : " + JSON.stringify(error)); console.info("usb readData error : " + JSON.stringify(error));
}); });
// Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0) // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0)
usb.bulkTransfer(pipe, endpoint, dataUint8Array, 15000).then(dataLength => { usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then(dataLength => {
if (dataLength >= 0) { if (dataLength >= 0) {
console.info("usb writeData result write length : " + dataLength); console.info("usb writeData result write length : " + dataLength);
} else { } else {
......
# DFX # DFX
- [Development of Application Event Logging](hiappevent-guidelines.md) - Application Event Logging
- [Development of Performance Tracing](hitracemeter-guidelines.md) - [Development of Application Event Logging](hiappevent-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) - Distributed Call Chain Tracing
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- HiLog
- [HiLog Development](hilog-guidelines.md)
- Performance Tracing
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- Error Management - Error Management
- [Development of Error Manager](errormanager-guidelines.md) - [Development of Error Manager](errormanager-guidelines.md)
- [Development of Application Recovery](apprecovery-guidelines.md) - [Development of Application Recovery](apprecovery-guidelines.md)
# HiLog Development
## Introduction
HiLog is the log system of OpenHarmony that provides logging for the system framework, services, and applications to record information on user operations and system running status.
> **NOTE**
> This development guide is applicable only when you use Native APIs for application development. For details about the APIs, see [HiLog Native API Reference](https://gitee.com/openharmony-sig/interface_native_header/blob/master/en/native_sdk/dfx/log.h).
## Available APIs
| API/Macro| Description|
| -------- | -------- |
| int OH_LOG_Print(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...) | Outputs logs based on the specified log type, log level, service domain, log tag, and variable parameters determined by the format specifier and privacy identifier in the printf format.|
| #define OH_LOG_DEBUG(type, ...) ((void)OH_LOG_Print((type), LOG_DEBUG, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__))| Outputs DEBUG logs. This is a function-like macro.|
| #define OH_LOG_INFO(type, ...) ((void)OH_LOG_Print((type), LOG_INFO, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs INFO logs. This is a function-like macro.|
| #define OH_LOG_WARN(type, ...) ((void)OH_LOG_Print((type), LOG_WARN, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs WARN logs. This is a function-like macro.|
| #define OH_LOG_ERROR(type, ...) ((void)OH_LOG_Print((type), LOG_ERROR, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs ERROR logs. This is a function-like macro.|
| #define OH_LOG_FATAL(type, ...) ((void)OH_LOG_Print((type), LOG_FATAL, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs FATAL logs. This is a function-like macro.|
| bool OH_LOG_IsLoggable(unsigned int domain, const char *tag, LogLevel level) | Checks whether logs of the specified service domain, tag, and level can be printed.<br>Input arguments:<br>- **domain**: service domain.<br>- **tag**: log tag.<br>- **level**: log level.<br>Output arguments: none<br>Return value: Returns **true** if the specified logs can be printed; returns **false** otherwise.|
## Development Examples
1. Include the **hilog** header file in the source file.
```c++
#include "hilog/log.h"
```
2. Define the **domain** and **tag** macros.
```c++
#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0x3200 // Service domain. The value ranges from 0xD0000 to 0xDFFFF.
#define LOG_TAG "MY_TAG"
```
3. Print logs. For example, to print INFO logs, use the following code:
```c++
OH_LOG_INFO(LOG_APP, "Failed to visit %{private}s, reason:%{public}d.", url, errno);
```
4. View the output log information.
```
12-11 12:21:47.579 2695 2695 I A03200/MY_TAG: Failed to visit <private>, reason:11.
```
...@@ -2,9 +2,7 @@ ...@@ -2,9 +2,7 @@
## Introduction ## Introduction
The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications. hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls. The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process. The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications.
hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls. The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process.
## Basic Concepts ## Basic Concepts
...@@ -18,47 +16,106 @@ The APIs for distributed call chain tracing are provided by the **hiTraceChain** ...@@ -18,47 +16,106 @@ The APIs for distributed call chain tracing are provided by the **hiTraceChain**
**APIs for distributed call chain tracing** **APIs for distributed call chain tracing**
| API| Return Value| Description| | API | Return Value | Description |
| ------------------------------------------------------------------------------------------------------------------- | -------------- | ------------ | | ------------------------------------------------------------------------------------------------------------------- | -------------- | ------------ |
| hiTraceChain.begin(name: string, flags: number = HiTraceFlag.DEFAULT) | HiTraceId | Starts call chain tracing.| | hiTraceChain.begin(name: string, flags: number = HiTraceFlag.DEFAULT) | HiTraceId | Starts call chain tracing. |
| hiTraceChain.tracepoint(mode: HiTraceCommunicationMode, type: HiTraceTracepointType, id: HiTraceId, msg?: string) | void | Creates a trace point.| | hiTraceChain.end(id: HiTraceId) | void | Stops call chain tracing. |
| hiTraceChain.end(id: HiTraceId) | void | Stops call chain tracing.|
## How to Develop ## How to Develop
In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed. The following example illustrates how to simulate one-time [system event logging](../reference/apis/js-apis-hisysevent.md) to implement cross-thread distributed call chain tracing in a single HAP service.
1. Create a JS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **js** > **default** > **pages** > **index**, and double-click **index.js**. Add the code to implement call chain tracing upon page loading. The sample code is as follows: 1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add a button to trigger system event logging.
``` ```ts
import hiTraceChain from '@ohos.hiTraceChain' import hiTraceChain from '@ohos.hiTraceChain';
import hiSysEvent from '@ohos.hiSysEvent';
export default {
data: { @Entry
title: "" @Component
}, struct Index {
onInit() { @State message: string = 'Start writing system event';
this.title = this.$t('strings.world');
build() {
// 1. Enable distributed call chain tracing. Row() {
let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC | hiTraceChain.HiTraceFlag.DONOT_CREATE_SPAN); Column() {
Button(this.message)
// 2. Start the service process. .fontSize(20)
console.log(`business start`); .margin(5)
.width(350)
// 3. Add a trace point. .height(60)
hiTraceChain.tracepoint(hiTraceChain.HiTraceCommunicationMode.THREAD, hiTraceChain.HiTraceTracepointType.SS, asyncTraceId, "Just an example"); .fontWeight(FontWeight.Bold)
.onClick(() => {
// 4. Keep the service process running. try {
console.log(`business running`); // Enable distributed call chain tracing before the service starts.
let traceId = hiTraceChain.begin("Write a new system event", hiTraceChain.HiTraceFlag.INCLUDE_ASYNC);
// 5. End the service process. // Implement one-time system event logging when the service starts.
console.log(`business end`); hiSysEvent.write({
domain: "RELIABILITY",
// 6. Stop call chain tracing. name: "STACK",
hiTraceChain.end(asyncTraceId); eventType: hiSysEvent.EventType.FAULT,
} params: {
} PID: 1,
UID: 1,
PACKAGE_NAME: "com.demo.hitracechain",
PROCESS_NAME: "hitracechaindemo",
MSG: "no msg."
}
}).then((val) => {
console.info(`write result is ${val}`);
// Disable distributed call chain tracing when the service ends.
hiTraceChain.end(traceId);
}).catch((err) => {
console.error(`error message is ${err.message}`);
});
} catch (err) {
console.error(`error message is ${err.message}`);
}
})
}
.width('100%')
}
.height('100%')
}
}
```
2. Touch the run button on the IDE to run the project. Then, touch the **Start writing system event** button on the application UI to trigger system event logging.
3. View the information printed in the **Log** window. You can use **.*: \[([0-9a-zA-Z]{15}),.*].*** to access distributed call chain tracing information specific to the HAP service. The process ID of the HAP service is **8801**. Two threads, whose IDs are **8801** and **8819**, are involved in the system event logging. Based on the chain ID **edcfa53017a88e3**, you can then effectively trace the log information of the two threads.
```text
07-05 19:50:47.690 8801-8801/com.demo.hitracechain I C02d03/HiTraceC: [edcfa53017a88e3, 0, 0] HiTraceBegin name:Write a new system event flags:0x01.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 0, 0] Native2Js: chainId is edcfa53017a88e3.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 0, 0] Native2Js: spanId is 0.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 0, 0] Native2Js: parentSpanId is 0.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 0, 0] Native2Js: flags is 1.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] domain is RELIABILITY.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] name is STACK.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] eventType is 1.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=3, typeName=6.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=3, typeName=6.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=4, typeName=6.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=4, typeName=6.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain E C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] napi value type not match: valueType=4, typeName=6.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] create napi value of string type, value is JSHiSysEventWrite.
07-05 19:50:47.690 8801-8801/com.demo.hitracechain I C03900/Ace: [edcfa53017a88e3, 0, 0] [flutter_ace_view.cpp(operator())-(0)] Mark 0 id Touch Event Processed
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02800/ClientMsgHandler: [edcfa53017a88e3, 0, 0] in OnDispatchEventProcessed, enter
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02800/ANRHandler: [edcfa53017a88e3, 0, 0] in SetLastProcessedEventId, enter
07-05 19:50:47.690 8801-8819/com.demo.hitracechain D C02d08/HISYSEVENT: [edcfa53017a88e3, 0, 0] size=312, sysevent={"domain_":"RELIABILITY","name_":"STACK","type_":1,"time_":47591447690,"tz_":"+0000","pid_":8801,"tid_":8819,"uid_":20010045,"traceid_":"edcfa53017a88e3","spanid_":"0","pspanid_":"0","trace_flag_":1,"UID":1,"PID":1,"MSG":"no msg.","PROCESS_NAME":"hitracechaindemo","PACKAGE_NAME":"com.demo.hitracechain"}
07-05 19:50:47.690 8801-8801/com.demo.hitracechain D C02800/ANRHandler: [edcfa53017a88e3, 0, 0] in SetLastProcessedEventId, Processed event type:0, id:831, actionTime:6694499314, currentTime:6694501330, timeoutTime:4997984
07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02800/ANRHandler: [edcfa53017a88e3, 0, 0] in SetLastProcessedEventId, leave
07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02800/ClientMsgHandler: [edcfa53017a88e3, 0, 0] in OnDispatchEventProcessed, leave
07-05 19:50:47.691 8801-8819/com.demo.hitracechain D C02d08/HISYSEVENT: [edcfa53017a88e3, 0, 0] reset send buffer size old=245760, new=524288
07-05 19:50:47.691 8801-8819/com.demo.hitracechain D C02d08/HISYSEVENT: [edcfa53017a88e3, 0, 0] HiSysEvent send data successful
07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d08/NAPI_HISYSEVENT_UTIL: [edcfa53017a88e3, 0, 0] create napi value of int32 type, value is 0.
07-05 19:50:47.691 8801-8801/com.demo.hitracechain E A0fefe/JsApp: [edcfa53017a88e3, 399db38, 0] write result is 0
07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 399db38, 0] Js2Native: chainId is edcfa53017a88e3.
07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 399db38, 0] Js2Native: spanId is 0.
07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 399db38, 0] Js2Native: parentSpanId is 0.
07-05 19:50:47.691 8801-8801/com.demo.hitracechain D C02d03/HITRACE_UTIL_NAPI: [edcfa53017a88e3, 399db38, 0] Js2Native: flags is 1.
07-05 19:50:47.691 8801-8801/com.demo.hitracechain I C02d03/HiTraceC: [edcfa53017a88e3, 399db38, 0] HiTraceEnd.
``` ```
2. Click the run button on the application page. Then, you'll obtain the log information for service analysis. ## About Cross-Process/Cross-Device Distributed Call Chain Tracing
Cross-process/cross-device distributed call chain tracing depends on the NAPI implementation of the corresponding service APIs of each OpenHarmony module. For details, see the [HiTraceChain Development](../../device-dev/subsystems/subsys-dfx-hitracechain.md).
...@@ -33,7 +33,7 @@ ArkTS sample code: ...@@ -33,7 +33,7 @@ ArkTS sample code:
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility", abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'choose', //choose or save 'startMode': 'choose', //choose or save
} }
...@@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult( ...@@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult(
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility", abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'save', //choose or save 'startMode': 'save', //choose or save
'saveFile': 'test.jpg', 'saveFile': 'test.jpg',
......
此差异已折叠。
此差异已折叠。
# AVSession Development # AVSession Development
> **NOTE**
>
> All APIs of the **AVSession** module are system APIs and can be called only by system applications.
## Development for the Session Access End ## Development for the Session Access End
### Basic Concepts ### Basic Concepts
...@@ -28,7 +32,7 @@ Table 1 Common APIs for session access end development ...@@ -28,7 +32,7 @@ Table 1 Common APIs for session access end development
```js ```js
import avSession from '@ohos.multimedia.avsession'; import avSession from '@ohos.multimedia.avsession';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
``` ```
...@@ -50,7 +54,7 @@ avSession.createAVSession(context, "AudioAppSample", 'audio').then((session) => ...@@ -50,7 +54,7 @@ avSession.createAVSession(context, "AudioAppSample", 'audio').then((session) =>
3. Set the session information, including: 3. Set the session information, including:
- Session metadata. In addition to the current media asset ID (mandatory), you can set the title, album, author, duration, and previous/next media asset ID. For details about the session metadata, see **AVMetadata** in the API document. - Session metadata. In addition to the current media asset ID (mandatory), you can set the title, album, author, duration, and previous/next media asset ID. For details about the session metadata, see **AVMetadata** in the API document.
- Launcher ability, which is implemented by calling an API of **WantAgent**. Generally, **WantAgent** is used to encapsulate want information. For more information, see [wantAgent](../reference/apis/js-apis-wantAgent.md). - Launcher ability, which is implemented by calling an API of [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md). Generally, **WantAgent** is used to encapsulate want information.
- Playback state information. - Playback state information.
```js ```js
// Set the session metadata. // Set the session metadata.
...@@ -83,7 +87,7 @@ let wantAgentInfo = { ...@@ -83,7 +87,7 @@ let wantAgentInfo = {
wants: [ wants: [
{ {
bundleName: "com.neu.setResultOnAbilityResultTest1", bundleName: "com.neu.setResultOnAbilityResultTest1",
abilityName: "com.example.test.MainAbility", abilityName: "com.example.test.EntryAbility",
} }
], ],
operationType: wantAgent.OperationType.START_ABILITIES, operationType: wantAgent.OperationType.START_ABILITIES,
...@@ -187,7 +191,7 @@ currentSession.on('playNext', () => { ...@@ -187,7 +191,7 @@ currentSession.on('playNext', () => {
}); });
console.log ("Call AudioPlayer.play."); console.log ("Call AudioPlayer.play.");
// Set the playback state information. // Set the playback state information.
let time = (new Data()).getTime(); let time = (new Date()).getTime();
currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY, position: {elapsedTime: 0, updateTime: time}, bufferedTime:2000}).then(() => { currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY, position: {elapsedTime: 0, updateTime: time}, bufferedTime:2000}).then(() => {
console.info('setAVPlaybackState successfully'); console.info('setAVPlaybackState successfully');
}).catch((err) => { }).catch((err) => {
...@@ -282,7 +286,7 @@ currentSession.off('outputDeviceChange'); ...@@ -282,7 +286,7 @@ currentSession.off('outputDeviceChange');
// Deactivate the session and destroy the object. // Deactivate the session and destroy the object.
currentSession.deactivate().then(() => { currentSession.deactivate().then(() => {
currentSession.destory(); currentSession.destroy();
}); });
``` ```
...@@ -365,7 +369,7 @@ Table 2 Common APIs for session control end development ...@@ -365,7 +369,7 @@ Table 2 Common APIs for session control end development
```js ```js
import avSession from '@ohos.multimedia.avsession'; import avSession from '@ohos.multimedia.avsession';
import {Action, KeyEvent} from '@ohos.multimodalInput.KeyEvent'; import {Action, KeyEvent} from '@ohos.multimodalInput.KeyEvent';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
``` ```
......
# AVSession Overview # AVSession Overview
> **NOTE**
>
> All APIs of the **AVSession** module are system APIs and can be called only by system applications.
## Overview ## Overview
AVSession, short for audio and video session, is also known as media session. AVSession, short for audio and video session, is also known as media session.
...@@ -49,4 +53,4 @@ The **AVSession** module provides two classes: **AVSession** and **AVSessionCont ...@@ -49,4 +53,4 @@ The **AVSession** module provides two classes: **AVSession** and **AVSessionCont
- AVSession can transmit media playback information and control commands. It does not display information or execute control commands. - AVSession can transmit media playback information and control commands. It does not display information or execute control commands.
- Do not develop Media Controller for common applications. For common audio and video applications running on OpenHarmony, the default control end is Media Controller, which is a system application. You do not need to carry out additional development for Media Controller. - Do not develop Media Controller for common applications. For common audio and video applications running on OpenHarmony, the default control end is Media Controller, which is a system application. You do not need to carry out additional development for Media Controller.
- If you want to develop your own system running OpenHarmony, you can develop your own Media Controller. - If you want to develop your own system running OpenHarmony, you can develop your own Media Controller.
- For better background management of audio and video applications, the **AVSession** module enforces background control for third-party applications. Only third-party applications that have accessed AVSession can play audio in the background. Otherwise, the system forcibly pauses the playback when a third-party application switches to the background. - For better background management of audio and video applications, the **AVSession** module enforces background control for applications. Only applications that have accessed AVSession can play audio in the background. Otherwise, the system forcibly pauses the playback when an application switches to the background.
...@@ -118,9 +118,9 @@ The following steps describe how to use the canvas and brush of the Native Drawi ...@@ -118,9 +118,9 @@ The following steps describe how to use the canvas and brush of the Native Drawi
// Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush. // Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush.
OH_Drawing_CanvasDrawPath(cCanvas, cPath); OH_Drawing_CanvasDrawPath(cCanvas, cPath);
// Destroy the created objects when they are no longer needed. // Destroy the created objects when they are no longer needed.
OH_Drawing_BrushDestory(cBrush); OH_Drawing_BrushDestroy(cBrush);
OH_Drawing_PenDestory(cPen); OH_Drawing_PenDestroy(cPen);
OH_Drawing_PathDestory(cPath); OH_Drawing_PathDestroy(cPath);
``` ```
6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas. 6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas.
...@@ -133,9 +133,9 @@ The following steps describe how to use the canvas and brush of the Native Drawi ...@@ -133,9 +133,9 @@ The following steps describe how to use the canvas and brush of the Native Drawi
LOGI("memcpy_s failed"); LOGI("memcpy_s failed");
} }
// Destroy the canvas object. // Destroy the canvas object.
OH_Drawing_CanvasDestory(cCanvas); OH_Drawing_CanvasDestroy(cCanvas);
// Destroy the bitmap object. // Destroy the bitmap object.
OH_Drawing_BitmapDestory(cBitmap); OH_Drawing_BitmapDestroy(cBitmap);
``` ```
## Development Procedure for Text Drawing ## Development Procedure for Text Drawing
......
...@@ -29,20 +29,72 @@ The following scenarios are common for native window development: ...@@ -29,20 +29,72 @@ The following scenarios are common for native window development:
| OH_NativeWindow_NativeWindowSetMetaDataSet(OHNativeWindow \*window, uint32_t sequence, OHHDRMetadataKey key, int32_t size, const uint8_t \*metaData) | Sets the HDR static metadata set of the native window.| | OH_NativeWindow_NativeWindowSetMetaDataSet(OHNativeWindow \*window, uint32_t sequence, OHHDRMetadataKey key, int32_t size, const uint8_t \*metaData) | Sets the HDR static metadata set of the native window.|
| OH_NativeWindow_NativeWindowSetTunnelHandle(OHNativeWindow \*window, const OHExtDataHandle \*handle) | Sets the tunnel handle to the native window.| | OH_NativeWindow_NativeWindowSetTunnelHandle(OHNativeWindow \*window, const OHExtDataHandle \*handle) | Sets the tunnel handle to the native window.|
## How to Develop ## How to Develop
The following describes how to use the NAPI provided by **NativeWindow** to request a graphics buffer, write the produced graphics content to the buffer, and flush the buffer to the graphics queue. The following describes how to use the NAPI provided by **NativeWindow** to request a graphics buffer, write the produced graphics content to the buffer, and flush the buffer to the graphics queue.
1. Obtain a **NativeWindow** instance. For example, use **Surface** to create a **NativeWindow** instance. 1. Obtain a **NativeWindow** instance, which can be obtained by running the APIs provided by **OH_NativeXComponent_Callback**.
```c++ 1. Define **XComponent** in an .ets file.
sptr<OHOS::Surface> cSurface = Surface::CreateSurfaceAsConsumer(); ```ts
sptr<IBufferConsumerListener> listener = new BufferConsumerListenerTest(); XComponent({ id: 'xcomponentId', type: 'surface', libraryname: 'nativerender'})
cSurface->RegisterConsumerListener(listener); .onLoad((context) => {
sptr<OHOS::IBufferProducer> producer = cSurface->GetProducer(); this.context = context;
sptr<OHOS::Surface> pSurface = Surface::CreateSurfaceAsProducer(producer); })
OHNativeWindow* nativeWindow = OH_NativeWindow_CreateNativeWindow(&pSurface); .onDestroy(() => {
``` })
```
2. Obtain **NativeXComponent** at the native C++ layer.
```c++
napi_value exportInstance = nullptr;
napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance);
OH_NativeXComponent *nativeXComponent = nullptr;
napi_unwrap(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent));
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = { };
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize);
```
3. Define **OH_NativeXComponent_Callback**.
```c++
// Define the callback.
void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window)
{
// Obtain a NativeWindow instance.
OHNativeWindow* nativeWindow = window;
// ...
}
void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window)
{
// Obtain a NativeWindow instance.
OHNativeWindow* nativeWindow = window;
// ...
}
void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window)
{
// Obtain a NativeWindow instance.
OHNativeWindow* nativeWindow = window;
// ...
}
void DispatchTouchEventCB(OH_NativeXComponent* component, void* window)
{
// Obtain a NativeWindow instance.
OHNativeWindow* nativeWindow = window;
// ...
}
```
```c++
// Initialize OH_NativeXComponent_Callback.
OH_NativeXComponent_Callback callback_;
callback_->OnSurfaceCreated = OnSurfaceCreatedCB;
callback_->OnSurfaceChanged = OnSurfaceChangedCB;
callback_->OnSurfaceDestroyed = OnSurfaceDestroyedCB;
callback_->DispatchTouchEvent = DispatchTouchEventCB;
```
4. Register **OH_NativeXComponent_Callback** with **NativeXComponent**.
```c++
OH_NativeXComponent_RegisterCallback(nativeXComponent, &callback_);
```
2. Set the attributes of a native window buffer by using **OH_NativeWindow_NativeWindowHandleOpt**. 2. Set the attributes of a native window buffer by using **OH_NativeWindow_NativeWindowHandleOpt**.
```c++ ```c++
...@@ -90,7 +142,6 @@ The following describes how to use the NAPI provided by **NativeWindow** to requ ...@@ -90,7 +142,6 @@ The following describes how to use the NAPI provided by **NativeWindow** to requ
``` ```
5. Flush the native window buffer to the graphics queue. 5. Flush the native window buffer to the graphics queue.
```c++ ```c++
// Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the native window buffer are changed. // Set the refresh region. If Rect in Region is a null pointer or rectNumber is 0, all contents in the native window buffer are changed.
Region region{nullptr, 0}; Region region{nullptr, 0};
......
...@@ -30,21 +30,21 @@ This document gives an overview of the **app.json5** configuration file. To star ...@@ -30,21 +30,21 @@ This document gives an overview of the **app.json5** configuration file. To star
As shown above, the **app.json5** file contains several tags. As shown above, the **app.json5** file contains several tags.
**Table 1** Tags in the app.json5 file **Table 1** Tags in the app.json5 file
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:<br>- Consists of letters, digits, underscores (_), and periods (.).<br>- Starts with a letter.<br>- Contains 7 to 127 bytes.<br>You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.<br>If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No| | bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:<br>- Consists of letters, digits, underscores (_), and periods (.).<br>- Starts with a letter.<br>- Contains 7 to 127 bytes.<br>You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.<br>If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No|
| debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.<br>- **true**: The application can be debugged.<br>- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)| | debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.<br>- **true**: The application can be debugged.<br>- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)|
| icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index. | String| No| | icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index.| String| No|
| label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index. | String| No| | label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index.| String| No|
| description | Description of the application. The value is a string with a maximum of 255 bytes or a resource index to the description. | String| Yes (initial value: left empty)| | description | Description of the application. The value is a string with a maximum of 255 bytes or a resource index to the description.| String| Yes (initial value: left empty)|
| vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | vendor | Vendor of the application. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)|
| versionCode | Version number of the application. The value is a 32-bit non-negative integer less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number| No| | versionCode | Version number of the application. The value is a 32-bit non-negative integer less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number| No|
| versionName | Version number of the application displayed to users.<br>The value consists of only digits and dots. The four-part format *A.B.C.D* is recommended, wherein:<br>Part 1 (*A*): major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.<br>Part 2 (*B*): minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.<br>Part 3 (*C*): feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.<br>Part 4 (*D*): maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.<br>The value contains a maximum of 127 bytes.| String| No| | versionName | Version number of the application displayed to users.<br>The value consists of only digits and dots. The four-part format *A.B.C.D* is recommended, wherein:<br>Part 1 (*A*): major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.<br>Part 2 (*B*): minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.<br>Part 3 (*C*): feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.<br>Part 4 (*D*): maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.<br>The value contains a maximum of 127 bytes.| String| No|
| minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario.| Number| Yes (initial value: value of **versionCode**)| | minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario.| Number| Yes (initial value: value of **versionCode**)|
| minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)| | minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)|
| targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)| | targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)|
| apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.<br>- **Canary**: indicates a restricted release.<br>- **Beta**: indicates a publicly released beta version.<br>- **Release**: indicates a publicly released official version.<br>The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)| | apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.<br>- **Canary**: indicates a restricted release.<br>- **Beta**: indicates a publicly released beta version.<br>- **Release**: indicates a publicly released official version.<br>The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)|
| distributedNotificationEnabled | Whether distributed notification is enabled for the application. When distributed notification is enabled and device A and device B where the application is installed are on the same distributed network, the devices behave in this way: If device A receives a message, device B will receive a distributed notification prompting the user to check the message received on device A.<br>- **true**: Distributed notification is enabled.<br>- **false**: Distributed notification is not enabled.| Boolean| Yes (initial value: **false**)| | distributedNotificationEnabled | Whether distributed notification is enabled for the application. When distributed notification is enabled and device A and device B where the application is installed are on the same distributed network, the devices behave in this way: If device A receives a message, device B will receive a distributed notification prompting the user to check the message received on device A.<br>- **true**: Distributed notification is enabled.<br>- **false**: Distributed notification is not enabled.| Boolean| Yes (initial value: **false**)|
| entityType | Type of the application. The options are as follows:<br>- game<br>- media<br>- communication<br>- news<br>- travel<br>- utility<br>- shopping<br>- education<br>- kids<br>- business<br>- photography<br>- unspecified| String| Yes (initial value: **"unspecified"**)| | entityType | Type of the application. The options are as follows:<br>- game<br>- media<br>- communication<br>- news<br>- travel<br>- utility<br>- shopping<br>- education<br>- kids<br>- business<br>- photography<br>- unspecified| String| Yes (initial value: **"unspecified"**)|
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
The **app** tag contains application-wide configuration. The internal structure is as follows: The **app** tag contains application-wide configuration. The internal structure is as follows:
### Internal Structure of the app Tag **Table 1** Internal structure of the app tag
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -14,15 +14,19 @@ The **app** tag contains application-wide configuration. The internal structure ...@@ -14,15 +14,19 @@ The **app** tag contains application-wide configuration. The internal structure
| smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)| | smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)|
| smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)| | smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)|
#### Internal Structure of the version Atttribute ## Internal Structure of the version Atttribute
**Table 2** Internal structure of the version atttribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:<br>For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999.<br>*A* indicates the major version number.<br>*B* indicates the minor version number.<br>*C* indicates the patch version number. For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.<br>*A* indicates the major version number.<br>*B* indicates the minor version number.<br>*C* indicates the feature version number.<br>*D* indicates the patch version number.| Number| No| | name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:<br>For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999. <br>- *A* indicates the major version number.<br>- *B* indicates the minor version number.<br>- *C* indicates the patch version number.<br/>For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.<br>- *A* indicates the major version number.<br>- *B* indicates the minor version number.<br>- *C* indicates the feature version number.<br>- *D* indicates the patch version number. | Number| No|
| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:<br>API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No| | code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:<br>API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No|
| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)| | minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)|
#### Internal Structure of the apiVersion Attribute ## Internal Structure of the apiVersion Attribute
**Table 3** Internal structure of the apiVersion attribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -30,7 +34,7 @@ The **app** tag contains application-wide configuration. The internal structure ...@@ -30,7 +34,7 @@ The **app** tag contains application-wide configuration. The internal structure
| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| | target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
| releaseType | SDK status when the application is running.<br>**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.<br>**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.<br>**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)| | releaseType | SDK status when the application is running.<br>**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.<br>**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.<br>**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
### Example of the **app** Tag Example of the **app** tag:
```json ```json
"app": { "app": {
......
# Application Installation and Uninstallation Process # Application Installation and Uninstallation Process
## Developers
Developers can install and uninstall applications by running debug commands. For details, see [Multi-HAP Development, Debugging, Release, and Deployment Process](multi-hap-release-deployment.md#debugging).
The OpenHarmony bundle manager service module provides APIs for installing, updating, and uninstalling applications. You can call these APIs when needed. After you release your application to the application market, users can install and uninstall it on their device. **Figure 1** Process of installing and uninstalling an application (applicable to developers)
![hap-intall-uninstall](figures/hap-install-uninstall-developer.png)
## Consumers
When an application has been released to the application market, consumers can install or uninstall the application on their device through the application market.
**Figure 1** Process of installing and uninstalling an application **Figure 2** Process of installing and uninstalling an application (applicable to consumers)
![hap-intall-uninstall](figures/hap-intall-uninstall.png) ![hap-intall-uninstall](figures/hap-install-uninstall-user.png)
\ No newline at end of file
...@@ -263,11 +263,11 @@ struct MyComponent { ...@@ -263,11 +263,11 @@ struct MyComponent {
> >
> - **LazyForEach** must be used in the container component. Currently, only the **\<List>**, **\<Grid>**, and **\<Swiper>** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time. > - **LazyForEach** must be used in the container component. Currently, only the **\<List>**, **\<Grid>**, and **\<Swiper>** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time.
> >
> - **LazyForEach** must create and only one child component in each iteration. > - **LazyForEach** must create one and only one child component in each iteration.
> >
> - The generated child components must be allowed in the parent container component of **LazyForEach**. > - The generated child components must be the ones allowed in the parent container component of **LazyForEach**.
> >
> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement. > - **LazyForEach** can be included in an **if/else** statement.
> >
> - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**. > - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**.
> >
......
...@@ -46,33 +46,77 @@ struct bindPopupPage { ...@@ -46,33 +46,77 @@ struct bindPopupPage {
## Restrictions on Data Type Declarations of State Variables ## Restrictions on Data Type Declarations of State Variables
The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types. 1. The data types of state variables decorated by state decorators must be explicitly declared. They cannot be declared as **any** or **Date**.
Example: Example:
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct IndexPage { struct DatePickerExample {
// Incorrect: @State message: string | Resource = 'Hello World' // Incorrect: @State isLunar: any = false
@State message: string = 'Hello World' @State isLunar: boolean = false
// Incorrect: @State selectedDate: Date = new Date('2021-08-08')
build() { private selectedDate: Date = new Date('2021-08-08')
Row() {
Column() { build() {
Text(`${this.message}`) Column() {
.fontSize(50) Button('Switch Calendar')
.fontWeight(FontWeight.Bold) .margin({ top: 30 })
.onClick(() => {
this.isLunar = !this.isLunar
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
.lunar(this.isLunar)
.onChange((value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info('select current date is: ' + JSON.stringify(value))
})
}.width('100%')
} }
.width('100%')
} }
.height('100%') ```
}
} ![datePicker](../../application-dev/reference/arkui-ts/figures/datePicker.gif)
```
2. The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types.
The **Length**, **ResourceStr**, and **ResourceColor** types are combinations of primitive data types or reference data types. Therefore, they cannot be used by the aforementioned types of state variables.
For details about the definitions of **Length**, **ResourceStr**, and **ResourceColor**, see [Types](../../application-dev/reference/arkui-ts/ts-types.md).
Example:
```ts
// xxx.ets
@Entry
@Component
struct IndexPage {
// Incorrect: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
// Incorrect: @State message: ResourceStr = $r('app.string.hello')
@State resourceStr: Resource = $r('app.string.hello')
build() {
Row() {
Column() {
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
![hello](figures/hello.PNG) ![hello](figures/hello.PNG)
## Initialization and Restrictions of Custom Components' Member Variables ## Initialization and Restrictions of Custom Components' Member Variables
...@@ -98,6 +142,8 @@ The allowed method depends on the decorator of the state variable, as shown in t ...@@ -98,6 +142,8 @@ The allowed method depends on the decorator of the state variable, as shown in t
| @Link | Forbidden | Mandatory | | @Link | Forbidden | Mandatory |
| @StorageLink | Mandatory | Forbidden | | @StorageLink | Mandatory | Forbidden |
| @StorageProp | Mandatory | Forbidden | | @StorageProp | Mandatory | Forbidden |
| @LocalStorageLink | Mandatory | Forbidden |
| @LocalStorageProp | Mandatory | Forbidden |
| @Provide | Mandatory | Optional | | @Provide | Mandatory | Optional |
| @Consume | Forbidden | Forbidden | | @Consume | Forbidden | Forbidden |
| @ObjectLink | Forbidden | Mandatory | | @ObjectLink | Forbidden | Mandatory |
...@@ -111,25 +157,78 @@ As indicated by the preceding table: ...@@ -111,25 +157,78 @@ As indicated by the preceding table:
Comply with the following rules when using constructors to initialize member variables: Comply with the following rules when using constructors to initialize member variables:
| From the Variable in the Parent Component (Below) to the Variable in the Child Component (Right)| @State | @Link | @Prop | Normal Variable| | **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** |
| -------------------------------------------- | ------ | ------ | ------ | -------- | |---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------|
| @State | Not allowed| Allowed | Allowed | Allowed | | **regular** | Supported | Supported | Supported | Supported | Not supported | Not supported | Supported |
| @Link | Not allowed| Allowed | Not recommended| Allowed | | **@State** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| @Prop | Not allowed| Not allowed| Allowed | Allowed | | **@Link** | Not supported | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
| @StorageLink | Not allowed| Allowed | Not allowed| Not allowed | | **@Prop** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| @StorageProp | Not allowed| Not allowed| Not allowed| Allowed | | **@Provide** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| Normal variable | Allowed | Not allowed| Not allowed| Allowed | | **@Consume** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported |
| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported |
As indicated by the preceding table: | **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** |
|------------------|------------------|------------------|-----------------------|------------------------|
| **regular** | Supported | Not supported | Not supported | Not supported |
| **@State** | Supported | Supported | Supported | Supported |
| **@Link** | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
| **@Prop** | Supported | Supported | Supported | Supported |
| **@Provide** | Supported | Supported | Supported | Supported |
| **@Consume** | Not supported | Not supported | Not supported | Not supported |
| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported |
> **NOTE**
>
> **Supported (1)**: The dollar sign ($) must be used, for example, **this.$varA**.
>
> **regular**: refers to a regular variable that is not decorated by any decorator.
As indicated by the preceding tables:
- The **@ObjectLink** decorated variable cannot be directly initialized from a decorated variable in the parent component. The source of the parent component must be an array item or object attribute decorated by **@State**, **@Link**, **@Provide**, **@Consume**, or **@ObjectLink**.
- The normal variables of the parent component can be used to initialize the **@State** decorated variables of the child component, but not the **@Link** or **@Prop** decorated variables. - The regular variables of the parent component can be used to initialize the **@State** variable of the child component, but cannot be used to initialize the **@Link**, **@Consume**, and **@ObjectLink** variables.
- The **@State** decorated variable of the parent component can be used to initialize the **@Prop**, **@Link** (using **$**), or normal variables of the child component, but not the **@State** decorated variables of the child component. - The **@State** variable of the parent component can be used to initialize the **@Prop**, **@Link** (through **$**), or regular variables of the child component, but cannot be used to initialize the **@Consume** variable.
- The **@Link** decorated variables of the parent component can be used to initialize the **@Link** decorated or normal variables of the child component. However, initializing the **@State** decorated members of the child component can result in a syntax error. In addition, initializing the **@Prop** decorated variables is not recommended. - The **@Link** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component.
- The **@Prop** decorated variables of the parent component can be used to initialize the normal variables or **@Prop** decorated variables of the child component, but not the **@State** or **@Link** decorated variables. - The **@Prop** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component.
- Passing **@StorageLink** and **@StorageProp** from the parent component to the child component is prohibited. - **@StorageLink**, **@StorageProp**, **@LocalStorageLink**, and **@LocalStorageProp** variables cannot be initialized from the parent component.
- In addition to the preceding rules, the TypeScript strong type rules need to be followed. - In addition to the preceding rules, the TypeScript strong type rules need to be followed.
Example:
```ts
@Entry
@Component
struct Parent {
message: string = "Hello World"
build() {
Column() {
Child({
stateMessage: this.message,
/* ArkTS:ERROR The regular property 'message' cannot be assigned
to the @Link property 'linkMessage'.*/
linkMessage: this.$message
})
}
.width('100%')
}
}
@Component
struct Child {
@State stateMessage: string = "Hello World"
@Link linkMessage: string
build() {
Column() {
Text(this.stateMessage)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
}
```
...@@ -30,3 +30,5 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c ...@@ -30,3 +30,5 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c
- **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. - **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**.
- **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key. - **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key.
- **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started. - **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started.
For details about how to use state variables, see [Restrictions on Data Type Declarations of State Variables](arkts-restrictions-and-extensions.md).
# Internal Structure of deviceConfig Tag # Internal structure of deviceConfig Tag
The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type. The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type.
### Table 1 Internal Structure of the deviceConfig Tag ## Internal Structure of the deviceConfig Tag
**Table 1** Internal structure of the deviceConfig tag
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -16,7 +18,9 @@ The **deviceConfig** tag contains device-specific configuration of the applicati ...@@ -16,7 +18,9 @@ The **deviceConfig** tag contains device-specific configuration of the applicati
Table 2 describes the internal structure of the **deviceConfig** attributes. Table 2 describes the internal structure of the **deviceConfig** attributes.
#### Table 2 Internal Structure of the deviceConfig Attributes ## Internal Structure of the deviceConfig Attributes
**Table 2** Internal structure of the deviceConfig attributes
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -26,27 +30,33 @@ Table 2 describes the internal structure of the **deviceConfig** attributes. ...@@ -26,27 +30,33 @@ Table 2 describes the internal structure of the **deviceConfig** attributes.
| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)|
| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)| | network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)|
#### Table 3 Internal Structure of the network Attribute ## Internal Structure of the network Attribute
**Table 3** Internal structure of the network attribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.<br>**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)| | cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.<br>**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)|
| securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)| | securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)|
#### Table 4 Internal Structure of the securityConfig Attribute ## Internal Structure of the securityConfig Attribute
**Table 4** Internal structure of the securityConfig attribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| | domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)|
#### Table 5 Internal Structure of the domainSettings Attribute ## Internal Structure of the domainSettings Attribute
**Table 5** Internal structure of the domainSettings attribute
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)|
| domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)| | domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)|
### Example of the deviceConfig Tag Example of the **deviceConfig** tag:
```json ```json
"deviceConfig": { "deviceConfig": {
......
...@@ -28,12 +28,12 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca ...@@ -28,12 +28,12 @@ You can use DevEco Studio to build code into one or more HAP files. Then, you ca
uninstall bundle successfully. uninstall bundle successfully.
``` ```
* Using Bundle Manager (bm) for debugging * Using [Bundle Manager (bm)](../../application-dev/tools/bm-tool.md) for debugging
When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows: When using bm to install or update an HAP file, the HAP file path is the one on the real device. The command reference is as follows:
``` ```
// Installation and update: Multiple file paths can be specified. // Installation and update: Multiple file paths can be specified.
bm install -p /data/app/entry.hap /data/app/ feature.hap bm install -p /data/app/entry.hap /data/app/feature.hap
// The execution result is as follows: // The execution result is as follows:
install bundle successfully. install bundle successfully.
// Uninstall // Uninstall
......
...@@ -224,7 +224,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba ...@@ -224,7 +224,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba
```ts ```ts
import notification from '@ohos.notification'; import notification from '@ohos.notification';
import particleAbility from '@ohos.ability.particleAbility'; import particleAbility from '@ohos.ability.particleAbility';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
function callback(err, data) { function callback(err, data) {
if (err) { if (err) {
...@@ -293,7 +293,7 @@ Requests a continuous task from the system. This API uses a promise to return th ...@@ -293,7 +293,7 @@ Requests a continuous task from the system. This API uses a promise to return th
```ts ```ts
import notification from '@ohos.notification'; import notification from '@ohos.notification';
import particleAbility from '@ohos.ability.particleAbility'; import particleAbility from '@ohos.ability.particleAbility';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
...@@ -445,7 +445,6 @@ particleAbility.disconnectAbility(connId).then((data) => { ...@@ -445,7 +445,6 @@ particleAbility.disconnectAbility(connId).then((data) => {
}).catch((error) => { }).catch((error) => {
console.log('particleAbilityTest result errCode : ' + error.code) console.log('particleAbilityTest result errCode : ' + error.code)
}); });
``` ```
## particleAbility.disconnectAbility ## particleAbility.disconnectAbility
...@@ -491,10 +490,10 @@ var connId = particleAbility.connectAbility( ...@@ -491,10 +490,10 @@ var connId = particleAbility.connectAbility(
onFailed: onFailedCallback, onFailed: onFailedCallback,
}, },
); );
var result = particleAbility.disconnectAbility(connId).then((data) => {
console.log(" data: " + data); particleAbility.disconnectAbility(connId, (err) => {
}).catch((error) => { console.log("particleAbilityTest disconnectAbility err====>"
console.log('particleAbilityTest result errCode : ' + error.code) + ("json err=") + JSON.stringify(err));
}); });
``` ```
......
...@@ -72,7 +72,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro ...@@ -72,7 +72,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro
| ID | Error Message| | ID | Error Message|
| --------- | ------- | | --------- | ------- |
| 100001 | If no page is found for pageId or fail to get object property list. | | 100001 | if no page is found for pageId or fail to get object property list. |
**Example** **Example**
......
...@@ -9,7 +9,7 @@ The **Configuration** module defines environment change information. ...@@ -9,7 +9,7 @@ The **Configuration** module defines environment change information.
## Modules to Import ## Modules to Import
```ts ```ts
import Configuration from '@ohos.app.ability.Configuration' import Configuration from '@ohos.app.ability.Configuration';
``` ```
**System capability**: SystemCapability.Ability.AbilityBase **System capability**: SystemCapability.Ability.AbilityBase
...@@ -26,30 +26,30 @@ import Configuration from '@ohos.app.ability.Configuration' ...@@ -26,30 +26,30 @@ import Configuration from '@ohos.app.ability.Configuration'
For details about the fields, see the **ohos.app.ability.Configuration.d.ts** file. For details about the fields, see the **ohos.app.ability.Configuration.d.ts** file.
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let envCallback = { let envCallback = {
onConfigurationUpdated(config) { onConfigurationUpdated(config) {
console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`)
let language = config.language; let language = config.language;
let colorMode = config.colorMode; let colorMode = config.colorMode;
let direction = config.direction; let direction = config.direction;
let screenDensity = config.screenDensity; let screenDensity = config.screenDensity;
let displayId = config.displayId; let displayId = config.displayId;
let hasPointerDevice = config.hasPointerDevice; let hasPointerDevice = config.hasPointerDevice;
}
};
try {
let applicationContext = this.context.getApplicationContext();
let callbackId = applicationContext.on("environment", envCallback);
console.log("callbackId: " + callbackId);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
} }
};
try {
let applicationContext = this.context.getApplicationContext();
let callbackId = applicationContext.on("environment", envCallback);
console.log("callbackId: " + callbackId);
} catch (paramError) {
console.log("error: " + paramError.code + ", " + paramError.message);
}
} }
} }
``` ```
...@@ -124,7 +124,7 @@ Updates a widget. This API uses an asynchronous callback to return the result. ...@@ -124,7 +124,7 @@ Updates a widget. This API uses an asynchronous callback to return the result.
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288"; let formId = "12400633174999288";
...@@ -173,7 +173,7 @@ Updates a widget. This API uses a promise to return the result. ...@@ -173,7 +173,7 @@ Updates a widget. This API uses a promise to return the result.
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288"; let formId = "12400633174999288";
...@@ -349,7 +349,7 @@ Requests to publish a widget carrying data to the widget host. This API uses an ...@@ -349,7 +349,7 @@ Requests to publish a widget carrying data to the widget host. This API uses an
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
let want = { let want = {
......
...@@ -8,14 +8,17 @@ This module provides the following common ability-related functions: ...@@ -8,14 +8,17 @@ This module provides the following common ability-related functions:
- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. - [Callee](#callee): implements callbacks for registration and deregistration of caller notifications.
> **NOTE** > **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 are deprecated since API version 9. You are advised to use [@ohos.app.ability.UIAbility (UIAbility)](js-apis-app-ability-uiAbility.md) instead.
>
> 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 can be used only in the stage model. > The APIs of this module can be used only in the stage model.
## Modules to Import ## Modules to Import
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.application.Ability';
``` ```
## Attributes ## Attributes
...@@ -72,7 +75,7 @@ Called when a **WindowStage** is created for this ability. ...@@ -72,7 +75,7 @@ Called when a **WindowStage** is created for this ability.
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
console.log('onWindowStageCreate'); console.log('onWindowStageCreate');
} }
...@@ -91,7 +94,7 @@ Called when the **WindowStage** is destroyed for this ability. ...@@ -91,7 +94,7 @@ Called when the **WindowStage** is destroyed for this ability.
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onWindowStageDestroy() { onWindowStageDestroy() {
console.log('onWindowStageDestroy'); console.log('onWindowStageDestroy');
} }
...@@ -116,7 +119,7 @@ Called when the **WindowStage** is restored during the migration of this ability ...@@ -116,7 +119,7 @@ Called when the **WindowStage** is restored during the migration of this ability
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onWindowStageRestore(windowStage) { onWindowStageRestore(windowStage) {
console.log('onWindowStageRestore'); console.log('onWindowStageRestore');
} }
...@@ -133,9 +136,9 @@ Called when this ability is destroyed to clear resources. ...@@ -133,9 +136,9 @@ Called when this ability is destroyed to clear resources.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onDestroy() { onDestroy() {
console.log('onDestroy'); console.log('onDestroy');
} }
...@@ -152,9 +155,9 @@ Called when this ability is switched from the background to the foreground. ...@@ -152,9 +155,9 @@ Called when this ability is switched from the background to the foreground.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onForeground() { onForeground() {
console.log('onForeground'); console.log('onForeground');
} }
...@@ -171,9 +174,9 @@ Called when this ability is switched from the foreground to the background. ...@@ -171,9 +174,9 @@ Called when this ability is switched from the foreground to the background.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onBackground() { onBackground() {
console.log('onBackground'); console.log('onBackground');
} }
...@@ -202,10 +205,11 @@ Called to save data during the ability migration preparation process. ...@@ -202,10 +205,11 @@ Called to save data during the ability migration preparation process.
| AbilityConstant.OnContinueResult | Continuation result.| | AbilityConstant.OnContinueResult | Continuation result.|
**Example** **Example**
```ts ```ts
import AbilityConstant from "@ohos.application.AbilityConstant" import AbilityConstant from "@ohos.app.ability.AbilityConstant";
class myAbility extends Ability {
export default class EntryAbility extends UIAbility {
onContinue(wantParams) { onContinue(wantParams) {
console.log('onContinue'); console.log('onContinue');
wantParams["myData"] = "my1234567"; wantParams["myData"] = "my1234567";
...@@ -231,9 +235,9 @@ Called when a new Want is passed in and this UIAbility is started again. ...@@ -231,9 +235,9 @@ Called when a new Want is passed in and this UIAbility is started again.
| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.|
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onNewWant(want, launchParams) { onNewWant(want, launchParams) {
console.log('onNewWant, want:' + want.abilityName); console.log('onNewWant, want:' + want.abilityName);
console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); console.log('onNewWant, launchParams:' + JSON.stringify(launchParams));
...@@ -256,9 +260,9 @@ Called when the global configuration is updated. ...@@ -256,9 +260,9 @@ Called when the global configuration is updated.
| config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| | config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.|
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onConfigurationUpdated(config) { onConfigurationUpdated(config) {
console.log('onConfigurationUpdated, language:' + config.language); console.log('onConfigurationUpdated, language:' + config.language);
} }
...@@ -280,9 +284,9 @@ Dumps client information. ...@@ -280,9 +284,9 @@ Dumps client information.
| params | Array\<string> | Yes| Parameters in the form of a command.| | params | Array\<string> | Yes| Parameters in the form of a command.|
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
dump(params) { dump(params) {
console.log('dump, params:' + JSON.stringify(params)); console.log('dump, params:' + JSON.stringify(params));
return ["params"] return ["params"]
...@@ -305,9 +309,9 @@ Called when the system has decided to adjust the memory level. For example, this ...@@ -305,9 +309,9 @@ Called when the system has decided to adjust the memory level. For example, this
| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.|
**Example** **Example**
```ts ```ts
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onMemoryLevel(level) { onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level)); console.log('onMemoryLevel, level:' + JSON.stringify(level));
} }
...@@ -338,9 +342,9 @@ Called when the framework automatically saves the ability state in the case of a ...@@ -338,9 +342,9 @@ Called when the framework automatically saves the ability state in the case of a
**Example** **Example**
```ts ```ts
import AbilityConstant from '@ohos.application.AbilityConstant' import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class myAbility extends Ability { export default class EntryAbility extends UIAbility {
onSaveState(reason, wantParam) { onSaveState(reason, wantParam) {
console.log('onSaveState'); console.log('onSaveState');
wantParam["myData"] = "my1234567"; wantParam["myData"] = "my1234567";
...@@ -349,8 +353,6 @@ class myAbility extends Ability { ...@@ -349,8 +353,6 @@ class myAbility extends Ability {
} }
``` ```
## Caller ## Caller
Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability). Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability).
...@@ -387,7 +389,7 @@ Sends sequenceable data to the target ability. ...@@ -387,7 +389,7 @@ Sends sequenceable data to the target ability.
| 16000050 | Internal Error. | | 16000050 | Internal Error. |
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -545,7 +547,6 @@ Releases the caller interface of the target ability. ...@@ -545,7 +547,6 @@ Releases the caller interface of the target ability.
| 16000050 | Internal Error. | | 16000050 | Internal Error. |
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -589,7 +590,7 @@ Registers a callback that is invoked when the stub on the target ability is disc ...@@ -589,7 +590,7 @@ Registers a callback that is invoked when the stub on the target ability is disc
| callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.|
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -716,7 +717,6 @@ Deregisters a caller notification callback, which is invoked when the target abi ...@@ -716,7 +717,6 @@ Deregisters a caller notification callback, which is invoked when the target abi
**Example** **Example**
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
......
...@@ -9,7 +9,7 @@ The **AbilityDelegatorRegistry** module provides APIs for storing the global reg ...@@ -9,7 +9,7 @@ The **AbilityDelegatorRegistry** module provides APIs for storing the global reg
## Modules to Import ## Modules to Import
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
``` ```
## AbilityLifecycleState ## AbilityLifecycleState
......
...@@ -156,7 +156,7 @@ Called when an ability is continued on another device. ...@@ -156,7 +156,7 @@ Called when an ability is continued on another device.
**Example** **Example**
```ts ```ts
import AbilityStage from "@ohos.application.AbilityStage"; import AbilityStage from "@ohos.app.ability.AbilityStage";
var lifecycleId; var lifecycleId;
......
...@@ -10,7 +10,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying ...@@ -10,7 +10,7 @@ The **AbilityManager** module provides APIs for obtaining, adding, and modifying
## Modules to Import ## Modules to Import
```ts ```ts
import abilityManager from '@ohos.application.abilityManager' import abilityManager from '@ohos.application.abilityManager';
``` ```
## AbilityState ## AbilityState
...@@ -38,7 +38,7 @@ Updates the configuration. This API uses an asynchronous callback to return the ...@@ -38,7 +38,7 @@ Updates the configuration. This API uses an asynchronous callback to return the
**Permission required**: ohos.permission.UPDATE_CONFIGURATION **Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -176,7 +176,7 @@ abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { ...@@ -176,7 +176,7 @@ abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => {
getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>> getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>>
Obtains the extension running information. This API uses a promise to return the result. Obtains the extension running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO **Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -232,7 +232,7 @@ abilityManager.getTopAbility((err,data) => { ...@@ -232,7 +232,7 @@ abilityManager.getTopAbility((err,data) => {
getTopAbility(): Promise\<ElementName>; getTopAbility(): Promise\<ElementName>;
Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result. Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value** **Return value**
......
# @ohos.application.AccessibilityExtensionAbility # @ohos.application.AccessibilityExtensionAbility (AccessibilityExtensionAbility)
The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the ExtensionAbility framework. The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the ExtensionAbility framework.
......
...@@ -420,7 +420,7 @@ Deregisters the application state observer. This API uses a promise to return th ...@@ -420,7 +420,7 @@ Deregisters the application state observer. This API uses a promise to return th
getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void; getForegroundApplications(callback: AsyncCallback\<Array\<AppStateData>>): void;
Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md).
**Required permissions**: ohos.permission.GET_RUNNING_INFO **Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
......
...@@ -26,7 +26,6 @@ import Configuration from '@ohos.application.Configuration' ...@@ -26,7 +26,6 @@ import Configuration from '@ohos.application.Configuration'
For details about the fields, see the **ohos.application.Configuration.d.ts** file. For details about the fields, see the **ohos.application.Configuration.d.ts** file.
**Example** **Example**
```ts ```ts
import hilog from '@ohos.hilog'; import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
......
...@@ -8,7 +8,7 @@ The **ErrorManager** module provides APIs for registering and deregistering erro ...@@ -8,7 +8,7 @@ The **ErrorManager** module provides APIs for registering and deregistering erro
## Modules to Import ## Modules to Import
```ts ```ts
import errorManager from '@ohos.application.errorManager' import errorManager from '@ohos.application.errorManager';
``` ```
## ErrorManager.registerErrorObserver ## ErrorManager.registerErrorObserver
...@@ -20,7 +20,7 @@ Registers an error observer. ...@@ -20,7 +20,7 @@ Registers an error observer.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.| | observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.|
...@@ -45,7 +45,7 @@ Deregisters an error observer. This API uses an asynchronous callback to return ...@@ -45,7 +45,7 @@ Deregisters an error observer. This API uses an asynchronous callback to return
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| observerId | number | Yes| Numeric code of the observer.| | observerId | number | Yes| Numeric code of the observer.|
...@@ -74,7 +74,7 @@ Deregisters an error observer. This API uses a promise to return the result. ...@@ -74,7 +74,7 @@ Deregisters an error observer. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| observerId | number | Yes| Numeric code of the observer.| | observerId | number | Yes| Numeric code of the observer.|
......
...@@ -48,7 +48,7 @@ Creates a **FormBindingData** object. ...@@ -48,7 +48,7 @@ Creates a **FormBindingData** object.
**Example** **Example**
```ts ```ts
import formBindingData from @ohos.application.formBindingData; import formBindingData from '@ohos.application.formBindingData';
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
try { try {
......
...@@ -94,7 +94,7 @@ Updates a widget. This API uses an asynchronous callback to return the result. ...@@ -94,7 +94,7 @@ Updates a widget. This API uses an asynchronous callback to return the result.
**Example** **Example**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288"; let formId = "12400633174999288";
......
...@@ -1001,7 +1001,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ...@@ -1001,7 +1001,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err
**Example** **Example**
```js ```js
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
...@@ -1066,7 +1066,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ...@@ -1066,7 +1066,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err
**Example** **Example**
```js ```js
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
// WantAgentInfo object // WantAgentInfo object
let wantAgentInfo = { let wantAgentInfo = {
...@@ -2222,7 +2222,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ...@@ -2222,7 +2222,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err
**Example** **Example**
```js ```js
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
controller.getLaunchAbility().then((agent) => { controller.getLaunchAbility().then((agent) => {
console.info(`GetLaunchAbility : SUCCESS : wantAgent : ${agent}`); console.info(`GetLaunchAbility : SUCCESS : wantAgent : ${agent}`);
...@@ -2257,7 +2257,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err ...@@ -2257,7 +2257,7 @@ For details about the error codes, see [AVSession Management Error Codes](../err
**Example** **Example**
```js ```js
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
controller.getLaunchAbility(function (err, agent) { controller.getLaunchAbility(function (err, agent) {
if (err) { if (err) {
......
...@@ -173,7 +173,7 @@ FA model: ...@@ -173,7 +173,7 @@ FA model:
```js ```js
import backgroundTaskManager from '@ohos.backgroundTaskManager'; import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
function callback(err, data) { function callback(err, data) {
if (err) { if (err) {
...@@ -207,7 +207,7 @@ Stage model: ...@@ -207,7 +207,7 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.backgroundTaskManager'; import backgroundTaskManager from '@ohos.backgroundTaskManager';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
function callback(err, data) { function callback(err, data) {
if (err) { if (err) {
...@@ -270,7 +270,7 @@ FA model: ...@@ -270,7 +270,7 @@ FA model:
```js ```js
import backgroundTaskManager from '@ohos.backgroundTaskManager'; import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
...@@ -299,7 +299,7 @@ Stage model: ...@@ -299,7 +299,7 @@ Stage model:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.backgroundTaskManager'; import backgroundTaskManager from '@ohos.backgroundTaskManager';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
......
...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re ...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.|
...@@ -69,9 +69,11 @@ Stage model: ...@@ -69,9 +69,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result ...@@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
**Return value** **Return value**
...@@ -139,9 +141,11 @@ Stage model: ...@@ -139,9 +141,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. | | name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -215,9 +219,11 @@ Stage model: ...@@ -215,9 +219,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.| | name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value** **Return value**
...@@ -294,9 +300,11 @@ Stage model: ...@@ -294,9 +300,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. | | name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -358,9 +366,11 @@ Stage model: ...@@ -358,9 +366,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.| | name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value** **Return value**
...@@ -428,9 +438,9 @@ Stage model: ...@@ -428,9 +438,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
......
...@@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { const STORE_CONFIG = {
name: "RdbTest.db", name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1 securityLevel: data_rdb.SecurityLevel.S1
} }
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
if (err) { if (err) {
console.info("Failed to get RdbStore, err: " + err) console.info("Failed to get RdbStore, err: " + err)
return return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
} }
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}) })
...@@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { ...@@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
console.log("Got RdbStore successfully.")
})
} }
} }
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
})
``` ```
## data_rdb.getRdbStore ## data_rdb.getRdbStore
...@@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { const STORE_CONFIG = {
name: "RdbTest.db", name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1 securityLevel: data_rdb.SecurityLevel.S1
} }
let promise = data_rdb.getRdbStore(context, STORE_CONFIG); let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => { promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
console.log("Failed to get RdbStore, err: " + err) console.log("Failed to get RdbStore, err: " + err)
...@@ -170,35 +147,23 @@ promise.then(async (rdbStore) => { ...@@ -170,35 +147,23 @@ promise.then(async (rdbStore) => {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG);
promise.then(async (rdbStore) => {
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
} }
} }
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
``` ```
## data_rdb.deleteRdbStore ## data_rdb.deleteRdbStore
...@@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) { if (err) {
console.info("Failed to delete RdbStore, err: " + err) console.info("Failed to delete RdbStore, err: " + err)
...@@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { ...@@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
} }
} }
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
``` ```
## data_rdb.deleteRdbStore ## data_rdb.deleteRdbStore
...@@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{ promise.then(()=>{
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
...@@ -318,24 +277,18 @@ promise.then(()=>{ ...@@ -318,24 +277,18 @@ promise.then(()=>{
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
} }
} }
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
``` ```
## StoreConfig ## StoreConfig
...@@ -423,17 +376,6 @@ Defines the resolution to use when **insert()** and **update()** conflict. ...@@ -423,17 +376,6 @@ Defines the resolution to use when **insert()** and **update()** conflict.
| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.| | ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.|
| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.| | ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.|
## OpenStatus<sup>10+</sup>
Enumerates the RDB store status.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Value | Description |
| --------- | ---- | --------------------------------------------------- |
| ON_CREATE | 0 | The RDB store is created for the first time. |
| ON_OPEN | 1 | The RDB store is already created. |
## RdbPredicates ## RdbPredicates
Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false.
...@@ -1283,7 +1225,16 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the ...@@ -1283,7 +1225,16 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | ----------- | ---- | -------------------------------- | | ------------ | ----------- | ---- | -------------------------------- |
| openStatus<sup>10+</sup> | number | Yes | RDB store status. The value **0** indicates the **ON_CREATE** state, which means the RDB store is created for the first time. The value **1** indicates the **ON_OPEN** state, which means the RDB store is already created. | | version<sup>10+</sup> | number | Yes | RDB store version, which is an integer greater than 0. |
**Example**
```js
// Set the RDB store version.
rdbStore.version = 3
// Obtain the RDB store version.
console.info("Get RdbStore version is " + rdbStore.version)
```
### insert ### insert
......
# @ohos.util.Deque (Linear Container Deque) # @ohos.util.Deque (Linear Container Deque)
> **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Double-ended queue (deque) is a sequence container implemented based on the queue data structure that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. **Deque** can dynamically adjust the capacity based on project requirements. It doubles the capacity each time. **Deque** differs from **[Queue](js-apis-queue.md)** and **[Vector](js-apis-vector.md)** mainly in the following aspects: Double-ended queue (deque) is a sequence container implemented based on the queue data structure that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. **Deque** can dynamically adjust the capacity based on project requirements. It doubles the capacity each time. **Deque** differs from **[Queue](js-apis-queue.md)** and **[Vector](js-apis-vector.md)** mainly in the following aspects:
......
# @ohos.deviceUsageStatistics (Device Usage Statistics) # @ohos.bundleState (Device Usage Statistics)
This module provides APIs for collecting statistics on device usage. This module provides APIs for collecting statistics on device usage.
...@@ -454,6 +454,20 @@ Provides the usage duration information of an application. ...@@ -454,6 +454,20 @@ Provides the usage duration information of an application.
| infosBeginTime | number | No | Time logged in the first application usage record in the **BundleActiveInfo** object.| | infosBeginTime | number | No | Time logged in the first application usage record in the **BundleActiveInfo** object.|
| infosEndTime | number | No | Time logged in the last application usage record in the **BundleActiveInfo** object.| | infosEndTime | number | No | Time logged in the last application usage record in the **BundleActiveInfo** object.|
### merge<sup>(deprecated)</sup>
merge(toMerge: BundleStateInfo): void
Merges the device usage statistics of applications with the same bundle name.
**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| toMerge | [BundleStateInfo](#bundlestateinfo) | Yes| Device usage statistics to merge.|
## BundleActiveState ## BundleActiveState
Provides information about an application event. Provides information about an application event.
......
此差异已折叠。
此差异已折叠。
...@@ -26,7 +26,7 @@ Describes the ability delegator arguments. ...@@ -26,7 +26,7 @@ Describes the ability delegator arguments.
**Example** **Example**
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
var args = AbilityDelegatorRegistry.getArguments(); var args = AbilityDelegatorRegistry.getArguments();
``` ```
...@@ -30,7 +30,7 @@ Describes an ability monitor. ...@@ -30,7 +30,7 @@ Describes an ability monitor.
**Example** **Example**
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
function onAbilityCreateCallback(data) { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info("onAbilityCreateCallback");
......
...@@ -28,7 +28,8 @@ The ability running information is obtained by calling [getAbilityRunningInfos]( ...@@ -28,7 +28,8 @@ The ability running information is obtained by calling [getAbilityRunningInfos](
**Example** **Example**
```ts ```ts
import abilitymanager from '@ohos.application.abilityManager'; import abilitymanager from '@ohos.app.ability.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => { abilitymanager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data));
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
......
...@@ -14,7 +14,8 @@ This module provides APIs for accessing a specific ability stage. You can use th ...@@ -14,7 +14,8 @@ This module provides APIs for accessing a specific ability stage. You can use th
The ability stage context is obtained through an **AbilityStage** instance. The ability stage context is obtained through an **AbilityStage** instance.
```ts ```ts
import AbilityStage from '@ohos.application.AbilityStage'; import AbilityStage from '@ohos.app.ability.AbilityStage';
class MyAbilityStage extends AbilityStage { class MyAbilityStage extends AbilityStage {
onCreate() { onCreate() {
let abilityStageContext = this.context; let abilityStageContext = this.context;
......
...@@ -11,7 +11,7 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilitySta ...@@ -11,7 +11,7 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilitySta
**Example** **Example**
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let monitor = { let monitor = {
moduleName: "feature_as1", moduleName: "feature_as1",
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册