提交 2c2d30f3 编写于 作者: X xsz233 提交者: Gitee

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

Signed-off-by: Nxsz233 <xushizhe@huawei.com>
......@@ -18,7 +18,7 @@
- master:最新开发版本。
- OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。
- OpenHarmony 3.2 Beta5版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta5.md)了解版本详情。
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
......
......@@ -34,11 +34,9 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below.
### Data Provider Application Development (Only for System Applications)
[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override the APIs as required.
[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
- **onCreate**
......@@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
```ts
import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.rdb';
import rdb from '@ohos.data.relationalStore';
import fileIo from '@ohos.fileio';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
```
4. Override the **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
5. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
5. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
6. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
```ts
const DB_NAME = "DB00.db";
......@@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
let rdbStore;
let result;
export default class DataShareExtAbility extends Extension {
private rdbStore_;
// Override onCreate().
onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt'
result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store.
rdb.getRdbStore(this.context, {
name: DB_NAME
}, 1, function (err, data) {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
}, function (err, data) {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
});
callback();
if (callbakc) {
callback();
}
});
}
// Override query().
query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) {
......@@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
};
```
6. Define **DataShareExtensionAbility** in **module.json5**.
7. Define **DataShareExtensionAbility** in **module.json5**.
| Field | Description |
| --------- | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. |
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. |
| | |
| Field| Description |
| ------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.|
| "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
| "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
**module.json5 example**
......@@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
]
```
### Data Consumer Application Development
1. Import dependencies.
......@@ -212,7 +208,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = new Array("*");
let valArray = ['*'];
// Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data);
......
......@@ -142,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | Synchronizes data between devices. This API uses a promise to return the result.<br>- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.<br>- **predicates**: specifies the data and devices to synchronize.<br>- **string**: device ID. <br>- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.|
| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | Synchronizes data between devices. This API uses a promise to return the result.<br>- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.<br>- **predicates**: specifies the data and devices to synchronize.<br>- **string**: device ID. <br>- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.|
**Registering an RDB Store Observer**
......@@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local
### Transaction
Table 15 Transaction APIs
**Table 15** Transaction APIs
| Class | API | Description |
| -------- | ----------------------- | --------------------------------- |
......@@ -202,44 +202,82 @@ Table 15 Transaction APIs
```js
import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
const STORE_CONFIG = { name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1}
// Assume that the current RDB store version is 3.
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
// When an RDB store is created, the default version is 0.
if (rdbStore.version == 0) {
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null)
// Set the RDB store version. The input parameter must be an integer greater than 0.
rdbStore.version = 3
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null)
rdbStore.version = 2
}
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null)
rdbStore.version = 3
}
})
```
Stage model:
```ts
import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context
const STORE_CONFIG = {
name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1
}
// Assume that the current RDB store version is 3.
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
// When an RDB store is created, the default version is 0.
if (rdbStore.version == 0) {
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null)
// Set the RDB store version. The input parameter must be an integer greater than 0.
rdbStore.version = 3
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null)
rdbStore.version = 2
}
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null)
rdbStore.version = 3
}
})
}
}
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = { name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
```
2. Insert data.
(1) Create a **ValuesBucket** to store the data you need to insert.
(1) Create a **ValuesBucket** instance to store the data you need to insert.
(2) Call the **insert()** method to insert data into the RDB store.
......@@ -384,14 +422,13 @@ Table 15 Transaction APIs
8. Query data of a remote device.
(1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device.
(2) Call the resultSet() API to obtain the result.
The sample code is as follows:
```js
```js
let rdbPredicate = new data_rdb.RdbPredicates('employee')
predicates.greaterThan("id", 0)
let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate)
......@@ -406,31 +443,32 @@ Table 15 Transaction APIs
}).catch((err) => {
console.info("failed to remoteQuery, err: " + err)
})
```
```
9. Back up and restore an RDB store.
(1) Back up the current RDB store.
The sample code is as follows:
The sample code is as follows:
```js
```js
let promiseBackup = rdbStore.backup("dbBackup.db")
promiseBackup.then(() => {
console.info('Backup success.')
console.info('Backup success.')
}).catch((err) => {
console.info('Backup failed, err: ' + err)
console.info('Backup failed, err: ' + err)
})
```
(2) Restore the RDB store using the backup file.
```
The sample code is as follows:
(2) Restore the RDB store using the backup file.
```js
The sample code is as follows:
```js
let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(() => {
console.info('Restore success.')
console.info('Restore success.')
}).catch((err) => {
console.info('Restore failed, err: ' + err)
console.info('Restore failed, err: ' + err)
})
```
```
......@@ -33,7 +33,7 @@ ArkTS sample code:
globalThis.context.startAbilityForResult(
{
bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility",
abilityName: "MainAbility",
parameters: {
'startMode': 'choose', //choose or save
}
......@@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult(
globalThis.context.startAbilityForResult(
{
bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility",
abilityName: "MainAbility",
parameters: {
'startMode': 'save', //choose or save
'saveFile': 'test.jpg',
......
此差异已折叠。
此差异已折叠。
......@@ -3,7 +3,7 @@
The **app** tag contains application-wide configuration. The internal structure is as follows:
### Internal Structure of the app Tag
**Table 1** Internal structure of the app tag
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
......@@ -14,15 +14,19 @@ The **app** tag contains application-wide configuration. The internal structure
| smartWindowSize | Screen size used when the application runs in the emulator.| String| Yes (initial value: left empty)|
| smartWindowDeviceType | Types of emulated devcies on which the application can run.| String array| Yes (initial value: left empty)|
#### Internal Structure of the version Atttribute
## Internal Structure of the version Atttribute
**Table 2** Internal structure of the version atttribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:<br>For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999.<br>*A* indicates the major version number.<br>*B* indicates the minor version number.<br>*C* indicates the patch version number. For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.<br>*A* indicates the major version number.<br>*B* indicates the minor version number.<br>*C* indicates the feature version number.<br>*D* indicates the patch version number.| Number| No|
| name | Application version number displayed to users. The value can be customized and cannot exceed 127 bytes. The configuration rules are as follows:<br>For API version 5 and earlier versions, use the three-part format *A.B.C* (compatible with a two-part format *A.B*), where A, B, and C are integers ranging from 0 to 999. <br>- *A* indicates the major version number.<br>- *B* indicates the minor version number.<br>- *C* indicates the patch version number.<br/>For API version 6 and later versions, the four-part format *A.B.C.D* is recommended, where A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.<br>- *A* indicates the major version number.<br>- *B* indicates the minor version number.<br>- *C* indicates the feature version number.<br>- *D* indicates the patch version number. | Number| No|
| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The configuration rules are as follows:<br>API version 5 and earlier versions: The value is a non-negative integer within 32 binary digits, which needs to be converted from the value of **version.name**. The conversion rule is as follows: Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001. API version 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer less than 2 to the power of 31. Note that the value must be updated each time the application version is updated, and the value for a later version must be greater than that for an earlier version.| Number| No|
| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices. The value rules are the same as those of **version.code**.| Number| No (initial value: value of **code**)|
#### Internal Structure of the apiVersion Attribute
## Internal Structure of the apiVersion Attribute
**Table 3** Internal structure of the apiVersion attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
......@@ -30,7 +34,7 @@ The **app** tag contains application-wide configuration. The internal structure
| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
| releaseType | SDK status when the application is running.<br>**canary**: preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.<br>**beta**: release open to all developers. This release does not promise API stability and may require tolerance of instability. After several releases, the beta version is declared as an API stability milestone through Release Notes, and APIs of later versions are frozen.<br>**release**: official release open to all developers. This release promises that all APIs are stable. When a version is in this state, the **Stage** field is not displayed in the version number.| String| Yes (initial value: configured in **build.profile** and filled in **config.json** by DevEco Studio during packaging)|
### Example of the **app** Tag
Example of the **app** tag:
```json
"app": {
......
......@@ -46,33 +46,77 @@ struct bindPopupPage {
## Restrictions on Data Type Declarations of State Variables
The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types.
Example:
```ts
// xxx.ets
@Entry
@Component
struct IndexPage {
// Incorrect: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
1. The data types of state variables decorated by state decorators must be explicitly declared. They cannot be declared as **any** or **Date**.
Example:
```ts
// xxx.ets
@Entry
@Component
struct DatePickerExample {
// Incorrect: @State isLunar: any = false
@State isLunar: boolean = false
// Incorrect: @State selectedDate: Date = new Date('2021-08-08')
private selectedDate: Date = new Date('2021-08-08')
build() {
Column() {
Button('Switch Calendar')
.margin({ top: 30 })
.onClick(() => {
this.isLunar = !this.isLunar
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
.lunar(this.isLunar)
.onChange((value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info('select current date is: ' + JSON.stringify(value))
})
}.width('100%')
}
.width('100%')
}
.height('100%')
}
}
```
```
![datePicker](../../application-dev/reference/arkui-ts/figures/datePicker.gif)
2. The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types.
The **Length**, **ResourceStr**, and **ResourceColor** types are combinations of primitive data types or reference data types. Therefore, they cannot be used by the aforementioned types of state variables.
For details about the definitions of **Length**, **ResourceStr**, and **ResourceColor**, see [Types](../../application-dev/reference/arkui-ts/ts-types.md).
Example:
```ts
// xxx.ets
@Entry
@Component
struct IndexPage {
// Incorrect: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
// Incorrect: @State message: ResourceStr = $r('app.string.hello')
@State resourceStr: Resource = $r('app.string.hello')
build() {
Row() {
Column() {
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
![hello](figures/hello.PNG)
![hello](figures/hello.PNG)
## Initialization and Restrictions of Custom Components' Member Variables
......@@ -98,6 +142,8 @@ The allowed method depends on the decorator of the state variable, as shown in t
| @Link | Forbidden | Mandatory |
| @StorageLink | Mandatory | Forbidden |
| @StorageProp | Mandatory | Forbidden |
| @LocalStorageLink | Mandatory | Forbidden |
| @LocalStorageProp | Mandatory | Forbidden |
| @Provide | Mandatory | Optional |
| @Consume | Forbidden | Forbidden |
| @ObjectLink | Forbidden | Mandatory |
......@@ -111,25 +157,78 @@ As indicated by the preceding table:
Comply with the following rules when using constructors to initialize member variables:
| From the Variable in the Parent Component (Below) to the Variable in the Child Component (Right)| @State | @Link | @Prop | Normal Variable|
| -------------------------------------------- | ------ | ------ | ------ | -------- |
| @State | Not allowed| Allowed | Allowed | Allowed |
| @Link | Not allowed| Allowed | Not recommended| Allowed |
| @Prop | Not allowed| Not allowed| Allowed | Allowed |
| @StorageLink | Not allowed| Allowed | Not allowed| Not allowed |
| @StorageProp | Not allowed| Not allowed| Not allowed| Allowed |
| Normal variable | Allowed | Not allowed| Not allowed| Allowed |
| **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** |
|---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------|
| **regular** | Supported | Supported | Supported | Supported | Not supported | Not supported | Supported |
| **@State** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| **@Link** | Not supported | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
| **@Prop** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| **@Provide** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
| **@Consume** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported |
| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported |
As indicated by the preceding table:
| **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** |
|------------------|------------------|------------------|-----------------------|------------------------|
| **regular** | Supported | Not supported | Not supported | Not supported |
| **@State** | Supported | Supported | Supported | Supported |
| **@Link** | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
| **@Prop** | Supported | Supported | Supported | Supported |
| **@Provide** | Supported | Supported | Supported | Supported |
| **@Consume** | Not supported | Not supported | Not supported | Not supported |
| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported |
> **NOTE**
>
> **Supported (1)**: The dollar sign ($) must be used, for example, **this.$varA**.
>
> **regular**: refers to a regular variable that is not decorated by any decorator.
As indicated by the preceding tables:
- The **@ObjectLink** decorated variable cannot be directly initialized from a decorated variable in the parent component. The source of the parent component must be an array item or object attribute decorated by **@State**, **@Link**, **@Provide**, **@Consume**, or **@ObjectLink**.
- The normal variables of the parent component can be used to initialize the **@State** decorated variables of the child component, but not the **@Link** or **@Prop** decorated variables.
- The regular variables of the parent component can be used to initialize the **@State** variable of the child component, but cannot be used to initialize the **@Link**, **@Consume**, and **@ObjectLink** variables.
- The **@State** decorated variable of the parent component can be used to initialize the **@Prop**, **@Link** (using **$**), or normal variables of the child component, but not the **@State** decorated variables of the child component.
- The **@State** variable of the parent component can be used to initialize the **@Prop**, **@Link** (through **$**), or regular variables of the child component, but cannot be used to initialize the **@Consume** variable.
- The **@Link** decorated variables of the parent component can be used to initialize the **@Link** decorated or normal variables of the child component. However, initializing the **@State** decorated members of the child component can result in a syntax error. In addition, initializing the **@Prop** decorated variables is not recommended.
- The **@Link** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component.
- The **@Prop** decorated variables of the parent component can be used to initialize the normal variables or **@Prop** decorated variables of the child component, but not the **@State** or **@Link** decorated variables.
- The **@Prop** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component.
- Passing **@StorageLink** and **@StorageProp** from the parent component to the child component is prohibited.
- **@StorageLink**, **@StorageProp**, **@LocalStorageLink**, and **@LocalStorageProp** variables cannot be initialized from the parent component.
- In addition to the preceding rules, the TypeScript strong type rules need to be followed.
Example:
```ts
@Entry
@Component
struct Parent {
message: string = "Hello World"
build() {
Column() {
Child({
stateMessage: this.message,
/* ArkTS:ERROR The regular property 'message' cannot be assigned
to the @Link property 'linkMessage'.*/
linkMessage: this.$message
})
}
.width('100%')
}
}
@Component
struct Child {
@State stateMessage: string = "Hello World"
@Link linkMessage: string
build() {
Column() {
Text(this.stateMessage)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
}
```
......@@ -30,3 +30,5 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c
- **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**.
- **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key.
- **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started.
For details about how to use state variables, see [Restrictions on Data Type Declarations of State Variables](arkts-restrictions-and-extensions.md).
# Internal Structure of deviceConfig Tag
# Internal structure of deviceConfig Tag
The **deviceConfig** tag contains device-specific configuration of the application, including attributes such as **default**, **tv**, **car**, and **wearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type.
### Table 1 Internal Structure of the deviceConfig Tag
## Internal Structure of the deviceConfig Tag
**Table 1** Internal structure of the deviceConfig tag
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
......@@ -16,7 +18,9 @@ The **deviceConfig** tag contains device-specific configuration of the applicati
Table 2 describes the internal structure of the **deviceConfig** attributes.
#### Table 2 Internal Structure of the deviceConfig Attributes
## Internal Structure of the deviceConfig Attributes
**Table 2** Internal structure of the deviceConfig attributes
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
......@@ -26,27 +30,33 @@ Table 2 describes the internal structure of the **deviceConfig** attributes.
| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)|
| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)|
#### Table 3 Internal Structure of the network Attribute
## Internal Structure of the network Attribute
**Table 3** Internal structure of the network attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.<br>**true**: The application is allowed to use plaintext traffic. **false**: The application is not allowed to use plaintext traffic.| Boolean| Yes (initial value: **false**)|
| securityConfig | Network security configuration of the application.| Object| Yes (initial value: left empty)|
#### Table 4 Internal Structure of the securityConfig Attribute
## Internal Structure of the securityConfig Attribute
**Table 4** Internal structure of the securityConfig attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| domainSettings | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)|
#### Table 5 Internal Structure of the domainSettings Attribute
## Internal Structure of the domainSettings Attribute
**Table 5** Internal structure of the domainSettings attribute
| Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- |
| cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute. **true**: Plaintext traffic can be transmitted. **false**: Plaintext traffic cannot be transmitted.| Boolean| Yes (initial value: left empty)|
| domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**. **subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches. **name** (string): indicates the domain name.| Object array| Yes (initial value: left empty)|
### Example of the deviceConfig Tag
Example of the **deviceConfig** tag:
```json
"deviceConfig": {
......
......@@ -122,7 +122,7 @@
- continuation
- [continuationExtraParams](js-apis-continuation-continuationExtraParams.md)
- [continuationResult](js-apis-continuation-continuationResult.md)
- Common Event and Notification
- [@ohos.commonEventManager (Common Event) (Recommended)](js-apis-commonEventManager.md)
- [@ohos.events.emitter (Emitter)](js-apis-emitter.md)
......@@ -203,7 +203,6 @@
- [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md)
- security
- [PermissionRequestResult](js-apis-permissionrequestresult.md)
- Data Management
- [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md)
- [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md)
......@@ -215,11 +214,15 @@
- [@ohos.data.relationalStore (RDB Store)](js-apis-data-relationalStore.md)
- [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md)
- data/rdb
- [resultSet](js-apis-data-resultset.md)
- [resultSet (Result Set)](js-apis-data-resultset.md)
- File Management
- [@ohos.environment](js-apis-environment.md)
- [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md)
- [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md)
- [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md)
- [@ohos.file.fs (File Management)](js-apis-file-fs.md)
- [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md)
- [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md)
- [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md)
- [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md)
- [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md)
......
......@@ -72,7 +72,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro
| ID | Error Message|
| --------- | ------- |
| 100001 | If no page is found for pageId or fail to get object property list. |
| 100001 | if no page is found for pageId or fail to get object property list. |
**Example**
......
......@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.|
......@@ -69,9 +69,11 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.|
**Return value**
......@@ -139,9 +141,11 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
......@@ -215,9 +219,11 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value**
......@@ -294,9 +300,11 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
......@@ -358,9 +366,11 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......@@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value**
......@@ -428,9 +438,9 @@ Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability';
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context;
}
......
......@@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
})
......@@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
console.log("Got RdbStore successfully.")
})
}
}
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
})
```
## data_rdb.getRdbStore
......@@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
......@@ -170,35 +147,23 @@ promise.then(async (rdbStore) => {
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG);
promise.then(async (rdbStore) => {
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
}
}
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
```
## data_rdb.deleteRdbStore
......@@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
......@@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
}
}
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
```
## data_rdb.deleteRdbStore
......@@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
......@@ -318,24 +277,18 @@ promise.then(()=>{
Stage model:
```ts
// Obtain the context.
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
context = this.context
let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
}
}
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
```
## StoreConfig
......@@ -423,17 +376,6 @@ Defines the resolution to use when **insert()** and **update()** conflict.
| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.|
| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.|
## OpenStatus<sup>10+</sup>
Enumerates the RDB store status.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Value | Description |
| --------- | ---- | --------------------------------------------------- |
| ON_CREATE | 0 | The RDB store is created for the first time. |
| ON_OPEN | 1 | The RDB store is already created. |
## RdbPredicates
Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false.
......@@ -1283,7 +1225,16 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the
| Name | Type | Mandatory| Description |
| ------------ | ----------- | ---- | -------------------------------- |
| openStatus<sup>10+</sup> | number | Yes | RDB store status. The value **0** indicates the **ON_CREATE** state, which means the RDB store is created for the first time. The value **1** indicates the **ON_OPEN** state, which means the RDB store is already created. |
| version<sup>10+</sup> | number | Yes | RDB store version, which is an integer greater than 0. |
**Example**
```js
// Set the RDB store version.
rdbStore.version = 3
// Obtain the RDB store version.
console.info("Get RdbStore version is " + rdbStore.version)
```
### insert
......
# @ohos.environment (Directory Environment Capability)
# @ohos.file.environment (Directory Environment Capability)
The **Environment** module provides APIs for obtaining the root directories of the storage and public files.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs and cannot be called by third-party applications.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import environment from '@ohos.environment';
import environment from '@ohos.file.environment';
```
## environment.getStorageDataDir
......@@ -30,10 +31,10 @@ Obtains the root directory of the storage. This API uses a promise to return the
**Example**
```js
environment.getStorageDataDir().then(function(path){
console.info("getStorageDataDir successfully:"+ path);
}).catch(function(error){
console.info("getStorageDataDir failed with error:"+ error);
environment.getStorageDataDir().then((path) => {
console.info("getStorageDataDir successfully, Path: " + path);
}).catch((err) => {
console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code);
});
```
......@@ -54,8 +55,12 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac
**Example**
```js
environment.getStorageDataDir(function(error, path){
// do something
environment.getStorageDataDir((err, path) => {
if (err) {
console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getStorageDataDir successfully, Path: " + path);
}
});
```
......@@ -76,10 +81,10 @@ Obtains the root directory of public files. This API uses a promise to return th
**Example**
```js
environment.getUserDataDir().then(function(path){
console.info("getUserDataDir successfully:"+ path);
}).catch(function(error){
console.info("getUserDataDir failed with error:"+ error);
environment.getUserDataDir().then((path) => {
console.info("getUserDataDir successfully, Path: " + path);
}).catch((err) => {
console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code);
});
```
......@@ -100,7 +105,11 @@ Obtains the root directory of public files. This API uses an asynchronous callba
**Example**
```js
environment.getUserDataDir(function(error, path){
// do something
environment.getUserDataDir((err, path) => {
if (err) {
console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getUserDataDir successfully, Path: " + path);
}
});
```
此差异已折叠。
# @ohos.file.hash (File Hash Processing)
The **fileHash** module implements hash processing on files.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import Hash from '@ohos.file.hash';
```
## Guidelines
Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the file or directory in the application sandbox as follows:
**Stage Model**
```js
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
let context = this.context;
let pathDir = context.filesDir;
}
}
```
**FA Model**
```js
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
let pathDir = data;
})
```
For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context).
## Hash.hash
hash(path: string, algorithm: string): Promise&lt;string&gt;
Calculates a hash value for a file. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the file in the application sandbox. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
**Return value**
| Type | Description |
| --------------------- | -------------------------- |
| Promise&lt;string&gt; | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
**Example**
```js
let filePath = pathDir + "/test.txt";
Hash.hash(filePath, "sha256").then((str) => {
console.info("calculate file hash succeed:" + str);
}).catch((err) => {
console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
});
```
## Hash.hash
hash(path: string, algorithm: string, callback: AsyncCallback&lt;string&gt;): void
Calculates a hash value for a file. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | --------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the file in the application sandbox. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
**Example**
```js
Hash.hash(filePath, "sha256", (err, str) => {
if (err) {
console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("calculate file hash succeed:" + str);
}
});
```
# @ohos.file.securityLabel (Data Label)
The **securityLabel** module provides APIs for managing data security levels of files, including obtaining and setting file security levels.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>- The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import securityLabel from '@ohos.file.securityLabel';
```
## Guidelines
Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the file or directory in the application sandbox as follows:
**Stage Model**
```js
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
let context = this.context;
let pathDir = context.filesDir;
}
}
```
**FA Model**
```js
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
let pathDir = data;
})
```
For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context).
## securityLabel.setSecurityLabel
setSecurityLabel(path:string, type:dataLevel):Promise&lt;void&gt;
Sets a security label for a file in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
**Return value**
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
securityLabel.setSecurityLabel(path, "s0").then(() => {
console.info("setSecurityLabel successfully");
}).catch((err) => {
console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code);
});
```
## securityLabel.setSecurityLabel
setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback&lt;void&gt;):void
Sets a security label for a file in asynchronous mode. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------- | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Example**
```js
securityLabel.setSecurityLabel(path, "s0", (err) => {
if (err) {
console.info("setSecurityLabel failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("setSecurityLabel successfully.");
}
});
```
## securityLabel.setSecurityLabelSync
setSecurityLabelSync(path:string, type:dataLevel):void
Sets a security label for a file in synchronous mode.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------------------------------------------- |
| path | string | Yes | Path of the target file. |
| type | dataLevel | Yes | File security level to set, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.|
**Example**
```js
securityLabel.setSecurityLabelSync(path, "s0");
```
## securityLabel.getSecurityLabel
getSecurityLabel(path:string):Promise&lt;string&gt;
Obtains the security label of a file in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------- |
| path | string | Yes | Path of the target file.|
**Return value**
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;string&gt; | Security label obtained.|
**Example**
```js
securityLabel.getSecurityLabel(path).then((type) => {
console.log("getSecurityLabel successfully, Label: " + type);
}).catch((err) => {
console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code);
});
```
## securityLabel.getSecurityLabel
getSecurityLabel(path:string, callback:AsyncCallback&lt;string&gt;): void
Obtains the security label of a file in asynchronous mode. This API uses a callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | -------------------------- |
| path | string | Yes | Path of the target file. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the security label obtained.|
**Example**
```js
securityLabel.getSecurityLabel(path, (err, type) => {
if (err) {
console.log("getSecurityLabel failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.log("getSecurityLabel successfully, Label: " + type);
}
});
```
## securityLabel.getSecurityLabelSync
getSecurityLabelSync(path:string):string
Obtains the security label of a file in synchronous mode.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------- |
| path | string | Yes | Path of the target file.|
**Return value**
| Type | Description |
| ------ | ------------ |
| string | Security label obtained.|
**Example**
```js
let type = securityLabel.getSecurityLabelSync(path);
console.log("getSecurityLabel successfully, Label: " + type);
```
# @ohos.file.statvfs (File System Space Statistics)
The **statfs** module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import statvfs from '@ohos.file.statvfs';
```
## statvfs.getFreeSize
getFreeSize(path:string):Promise&lt;number&gt;
Obtains the number of free bytes of the specified file system in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
**Return value**
| Type | Description |
| --------------------- | -------------- |
| Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.|
**Example**
```js
let path = "/dev";
statfs.getFreeSize(path).then((number) => {
console.info("getFreeSize promise successfully, Size: " + number);
}).catch((err) => {
console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code);
});
```
## statfs.getFreeSize
getFreeSize(path:string, callback:AsyncCallback&lt;number&gt;): void
Obtains the number of free bytes of the specified file system in asynchronous mode. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.|
**Example**
```js
let path = "/dev";
statfs.getFreeSize(path, (err, number) => {
if (err) {
console.info("getFreeSize failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getFreeSize callback successfully, Size: " + number);
}
});
```
## statfs.getTotalSize
getTotalSize(path: string): Promise&lt;number&gt;
Obtains the total number of bytes of the specified file system in asynchronous mode. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
**Return value**
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.|
**Example**
```js
let path = "/dev";
statfs.getTotalSize(path).then((number) => {
console.info("getTotalSize promise successfully, Size: " + number);
}).catch((err) => {
console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code);
});
```
## statfs.getTotalSize
getTotalSize(path: string, callback: AsyncCallback&lt;number&gt;): void
Obtains the total number of bytes of the specified file system in asynchronous mode. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. |
**Example**
```js
let path = "/dev";
statfs.getTotalSize(path, (err, number) => {
if (err) {
console.info("getTotalSize with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getTotalSize promise successfully, Size: " + number);
}
});
```
......@@ -84,13 +84,13 @@ Activates an OS account. This API uses an asynchronous callback to return the re
try {
accountManager.activateOsAccount(localId, (err)=>{
if (err) {
console.log("activateOsAccount failed, error:" + JSON.stringify(err));
console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`);
} else {
console.log("activateOsAccount successfully");
}
});
} catch (err) {
console.log("activateOsAccount exception:" + JSON.stringify(err));
console.error(`activateOsAccount failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -170,13 +170,13 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous
try {
accountManager.checkMultiOsAccountEnabled((err, isEnabled) => {
if (err) {
console.log("checkMultiOsAccountEnabled failed, error: " + JSON.stringify(err));
console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
} else {
console.log("checkMultiOsAccountEnabled successfully, isEnabled: " + isEnabled);
}
});
} catch (err) {
console.log("checkMultiOsAccountEnabled exception: " + JSON.stringify(err));
console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -208,10 +208,10 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
accountManager.checkMultiOsAccountEnabled().then((isEnabled) => {
console.log('checkMultiOsAccountEnabled successfully, isEnabled: ' + isEnabled);
}).catch((err) => {
console.log('checkMultiOsAccountEnabled failed, error: ' + JSON.stringify(err));
console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console.log('checkMultiOsAccountEnabled exception: ' + JSON.stringify(err));
console.error(`checkMultiOsAccountEnabled failed, code is ${err.code}, message is ${err.message}`);
}
```
......@@ -3604,7 +3604,7 @@ Obtains the type of the account to which the current process belongs. This API u
getDistributedVirtualDeviceId(callback: AsyncCallback&lt;string&gt;): void
Obtains the ID of the distributed virtual device. This API uses an asynchronous callback to return the result.
Obtains the ID of this distributed virtual device. This API uses an asynchronous callback to return the result.
> **NOTE**
>
......@@ -3634,7 +3634,7 @@ Obtains the ID of the distributed virtual device. This API uses an asynchronous
getDistributedVirtualDeviceId(): Promise&lt;string&gt;
Obtains the ID of the distributed virtual device. This API uses a promise to return the result.
Obtains the ID of this distributed virtual device. This API uses a promise to return the result.
> **NOTE**
>
......@@ -4323,13 +4323,13 @@ Unregisters this PIN inputer.
pinAuth.unregisterInputer();
```
### InputerManager <sup>10+</sup>
## InputerManager <sup>9+</sup>
Provides APIs for managing credential inputers.
### registerInputer<sup>10+</sup>
### registerInputer<sup>9+</sup>
registerInputer(authType: AuthType, inputer: IInputer): void;
static registerInputer(authType: AuthType, inputer: IInputer): void
Register a credential inputer.
......@@ -4357,11 +4357,10 @@ Register a credential inputer.
**Example**
```js
let inputerMgr = new account_osAccount.InputerManager();
let authType = account_osAccount.AuthType.DOMAIN;
let password = new Uint8Array([0, 0, 0, 0, 0]);
try {
inputerMgr.registerInputer(authType, {
account_osAccount.InputerManager.registerInputer(authType, {
onGetData: (authSubType, callback) => {
callback.onSetData(authSubType, password);
}
......@@ -4372,9 +4371,9 @@ Register a credential inputer.
}
```
### unregisterInputer<sup>10+</sup>
### unregisterInputer<sup>9+</sup>
unregisterInputer(authType: AuthType): void;
static unregisterInputer(authType: AuthType): void
Unregisters this credential inputer.
......@@ -4398,16 +4397,129 @@ Unregisters this credential inputer.
**Example**
```js
let inputerMgr = new account_osAccount.InputerManager();
let authType = account_osAccount.AuthType.DOMAIN;
try {
inputerMgr.unregisterInputer(authType);
account_osAccount.InputerManager.unregisterInputer(authType);
console.log('unregisterInputer success.');
} catch(err) {
console.log("unregisterInputer err:" + JSON.stringify(err));
}
```
## DomainPlugin<sup>9+</sup>
Provides APIs for domain account authentication.
**System API**: This is a system API.
### auth<sup>9+</sup>
auth(domainAccountInfo: DomainAccountInfo, credential: Uint8Array, callback: IUserAuthCallback): void
Authenticates a domain account.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.OsAccount
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | --------------------------------------- | ---- | --------------- |
| domainAccountInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.|
| credential | Uint8Array | Yes | Credentials of the domain account.|
| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result.|
**Example**
```js
let plugin = {
auth: (domainInfo, credential, callback) => {
// mock authentication
callback.onResult(0, {});
}
}
account_osAccount.DomainAccountManager.registerPlugin(plugin);
let userAuth = new account_osAccount.UserAuth();
let challenge = new Uint8Array([0]);
let authType = account_osAccount.AuthType.PIN;
let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1;
try {
userAuth.auth(challenge, authType, authTrustLevel, {
onResult: (resultCode, authResult) => {
console.log('auth resultCode = ' + resultCode);
console.log('auth authResult = ' + JSON.stringify(authResult));
}
});
} catch (err) {
console.log('auth exception = ' + JSON.stringify(err));
}
```
## DomainAccountManager <sup>9+</sup>
Provides APIs for domain account management.
### registerPlugin<sup>9+</sup>
static registerPlugin(plugin: DomainPlugin): void
Registers a domain plug-in.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.OsAccount
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
**Parameters**
| Name | Type | Mandatory| Description |
| ----------| ----------------------- | --- | -------------------------- |
| plugin | [DomainPlugin](#domainplugin9) | Yes | Domain plug-in to register.|
**Error codes**
| ID| Error Message |
| -------- | --------------------------- |
| 12300201 | The domain plugin has been registered. |
**Example**
```js
let plugin = {
auth: (domainInfo, credential, callback) => {
// mock authentication
callback.onResult(0, {});
}
}
try {
account_osAccount.DomainAccountManager.registerPlugin(plugin);
console.log('registerPlugin success.');
} catch(err) {
console.log("registerPlugin err:" + JSON.stringify(err));
}
```
### unregisterPlugin<sup>9+</sup>
static unregisterPlugin(): void
Unregisters this domain plug-in.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.OsAccount
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
**Example**
```js
try {
account_osAccount.DomainAccountManager.unregisterPlugin();
console.log('unregisterPlugin success.');
} catch(err) {
console.log("unregisterPlugin err:" + JSON.stringify(err));
}
```
## UserIdentityManager<sup>8+</sup>
Provides APIs for user identity management (IDM).
......
......@@ -120,9 +120,9 @@ try {
}
```
## privacyManager.getPermissionUsedRecords
## privacyManager.getPermissionUsedRecord
getPermissionUsedRecords(request: PermissionUsedRequest): Promise&lt;PermissionUsedResponse&gt;
getPermissionUsedRecord(request: PermissionUsedRequest): Promise&lt;PermissionUsedResponse&gt;
Obtains historical permission usage records. This API uses a promise to return the result.
......@@ -170,19 +170,19 @@ let request = {
"flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
};
try {
privacyManager.getPermissionUsedRecords(request).then((data) => {
console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`);
privacyManager.getPermissionUsedRecord(request).then((data) => {
console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
}).catch((err) => {
console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`);
console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
});
} catch(err) {
console.log(`catch err->${JSON.stringify(err)}`);
}
```
## privacyManager.getPermissionUsedRecords
## privacyManager.getPermissionUsedRecord
getPermissionUsedRecords(request: PermissionUsedRequest, callback: AsyncCallback&lt;PermissionUsedResponse&gt;): void
getPermissionUsedRecord(request: PermissionUsedRequest, callback: AsyncCallback&lt;PermissionUsedResponse&gt;): void
Obtains historical permission usage records. This API uses an asynchronous callback to return the result.
......@@ -225,11 +225,11 @@ let request = {
"flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL,
};
try {
privacyManager.getPermissionUsedRecords(request, (err, data) => {
privacyManager.getPermissionUsedRecord(request, (err, data) => {
if (err) {
console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`);
console.log(`getPermissionUsedRecord fail, err->${JSON.stringify(err)}`);
} else {
console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`);
console.log(`getPermissionUsedRecord success, data->${JSON.stringify(data)}`);
}
});
} catch(err) {
......
......@@ -32,7 +32,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -40,7 +40,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
try {
promptAction.showToast({
message: 'Message Info',
duration: 2000,
duration: 2000
});
} catch (error) {
console.error(`showToast args error code is ${error.code}, message is ${error.message}`);
......@@ -88,7 +88,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -100,11 +100,11 @@ try {
buttons: [
{
text: 'button1',
color: '#000000',
color: '#000000'
},
{
text: 'button2',
color: '#000000',
color: '#000000'
}
],
})
......@@ -142,7 +142,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -154,11 +154,11 @@ try {
buttons: [
{
text: 'button1',
color: '#000000',
color: '#000000'
},
{
text: 'button2',
color: '#000000',
color: '#000000'
}
]
}, (err, data) => {
......@@ -218,7 +218,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -229,11 +229,11 @@ try {
buttons: [
{
text: 'item1',
color: '#666666',
color: '#666666'
},
{
text: 'item2',
color: '#000000',
color: '#000000'
},
]
}, (err, data) => {
......@@ -276,7 +276,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | If UI execution context not found. |
| 100001 | if UI execution context not found. |
**Example**
......@@ -287,11 +287,11 @@ try {
buttons: [
{
text: 'item1',
color: '#666666',
color: '#666666'
},
{
text: 'item2',
color: '#000000',
color: '#000000'
},
]
})
......
......@@ -563,6 +563,7 @@ Describes the page routing options.
> **NOTE**
>
> The page routing stack supports a maximum of 32 pages.
## RouterMode<sup>9+</sup>
......
......@@ -4,7 +4,9 @@ The **statfs** module provides APIs for obtaining file system information, inclu
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [@ohos.file.statvfs](js-apis-file-statvfs.md).
## Modules to Import
......@@ -21,15 +23,15 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
**Return value**
| Type | Description |
| --------------------- | -------------- |
| Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.|
| Type | Description |
| --------------------- | -------------- |
| Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.|
**Example**
......@@ -52,10 +54,10 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.|
**Example**
......@@ -79,15 +81,15 @@ Obtains the total number of bytes of the specified file system in asynchronous m
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
**Return value**
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.|
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.|
**Example**
......@@ -110,10 +112,10 @@ Obtains the total number of bytes of the specified file system in asynchronous m
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. |
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. |
**Example**
......
......@@ -38,7 +38,7 @@ export default {
showToast() {
prompt.showToast({
message: 'Message Info',
duration: 2000,
duration: 2000
});
}
}
......@@ -67,11 +67,11 @@ export default {
showDialog() {
prompt.showDialog({
title: 'Title Info',
message: 'Message Info',
message: 'Message Info',
buttons: [
{
text: 'button',
color: '#666666',
color: '#666666'
},
],
success: function(data) {
......@@ -110,12 +110,12 @@ export default {
buttons: [
{
text: 'item1',
color: '#666666',
color: '#666666'
},
{
text: 'item2',
color: '#000000',
},
color: '#000000'
},
],
success: function(tapIndex) {
console.log('dialog success callback, click button : ' + data.tapIndex);
......
......@@ -31,7 +31,7 @@ Enumerates the match patterns supported for component attributes.
| Name | Value | Description |
| ----------- | ---- | -------------- |
| EQUALS | 0 | Equal to the given value. |
| EQUALS | 0 | Equals the given value. |
| CONTAINS | 1 | Contains the given value. |
| STARTS_WITH | 2 | Starts with the given value.|
| ENDS_WITH | 3 | Ends with the given value.|
......@@ -70,12 +70,12 @@ Provides bounds information of a component.
**System capability**: SystemCapability.Test.UiTest
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | ------------------------- |
| leftX | number | Yes | No | X-coordinate of the upper left corner of the component bounds.|
| topY | number | Yes | No | Y-coordinate of the upper left corner of the component bounds.|
| rightX | number | Yes | No | X-coordinate of the lower right corner of the component bounds.|
| bottomY | number | Yes | No | Y-coordinate of the lower right corner of the component bounds.|
| Name | Type | Readable| Writable| Description |
| ------ | ------ | ---- | ---- | ------------------------- |
| left | number | Yes | No | X-coordinate of the upper left corner of the component bounds.|
| top | number | Yes | No | Y-coordinate of the upper left corner of the component bounds.|
| right | number | Yes | No | X-coordinate of the lower right corner of the component bounds.|
| bottom | number | Yes | No | Y-coordinate of the lower right corner of the component bounds.|
## WindowMode<sup>9+</sup>
......@@ -219,7 +219,7 @@ Specifies the clickable status attribute of the target component.
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Clickable status of the target component.<br>**true**: clickable.<br>**false**: not clickable.<br> Default value: **true**|
| b | boolean | No | Clickable status of the target component.<br>**true**: clickable.<br>**false**: not clickable.<br>Default value: **true** |
**Return value**
......@@ -245,7 +245,7 @@ Specifies the long-clickable status attribute of the target component.
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Long-clickable status of the target component.<br>**true**: long-clickable.<br>**false**: not long-clickable.<br> Default value: **true**|
| b | boolean | No | Long-clickable status of the target component.<br>**true**: long-clickable.<br>**false**: not long-clickable.<br>Default value: **true** |
**Return value**
......@@ -272,7 +272,7 @@ Specifies the scrollable status attribute of the target component.
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------------------------------- |
| b | boolean | No | Scrollable status of the target component.<br>**true**: scrollable.<br>**false**: not scrollable.<br> Default value: **true**|
| b | boolean | No | Scrollable status of the target component.<br>**true**: scrollable.<br>**false**: not scrollable.<br>Default value: **true** |
**Return value**
......@@ -298,7 +298,7 @@ Specifies the enabled status attribute of the target component.
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | --------------------------------------------------------- |
| b | boolean | No | Enabled status of the target component.<br>**true**: enabled.<br>**false**: disabled.<br> Default value: **true**|
| b | boolean | No | Enabled status of the target component.<br>**true**: enabled.<br>**false**: not enabled.<br>Default value: **true** |
**Return value**
......@@ -324,7 +324,7 @@ Specifies the focused status attribute of the target component.
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------------------------- |
| b | boolean | No | Focused status of the target component.<br>**true**: focused.<br>**false**: not focused.<br> Default value: **true**|
| b | boolean | No | Focused status of the target component.<br>**true**: focused.<br>**false**: not focused.<br>Default value: **true** |
**Return value**
......@@ -350,7 +350,7 @@ Specifies the selected status attribute of the target component.
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Selected status of the target component.<br>**true**: selected.<br>**false**: not selected.<br> Default value: **true**|
| b | boolean | No | Selected status of the target component.<br>**true**: selected.<br>**false**: not selected.<br>Default value: **true** |
**Return value**
......@@ -376,7 +376,7 @@ Specifies the checked status attribute of the target component.
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Checked status of the target component.<br>**true**: checked.<br>**false**: not checked.<br> Default value: **false**|
| b | boolean | No | Checked status of the target component.<br>**true**: checked.<br>**false**: not checked.<br>Default value: **false** |
**Return value**
......@@ -402,7 +402,7 @@ Specifies the checkable status attribute of the target component.
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Checkable status of the target component.<br>**true**: checkable.<br>**false**: not checkable.<br> Default value: **false**|
| b | boolean | No | Checkable status of the target component.<br>**true**: checkable.<br>**false**: not checkable.<br>Default value: **false** |
**Return value**
......@@ -2788,7 +2788,7 @@ This API is deprecated since API version 9. You are advised to use [clickable<su
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Clickable status of the target component.<br>**true**: clickable.<br>**false**: not clickable.<br> Default value: **true**|
| b | boolean | No | Clickable status of the target component.<br>**true**: clickable.<br>**false**: not clickable.<br>Default value: **true** |
**Return value**
......@@ -2817,7 +2817,7 @@ This API is deprecated since API version 9. You are advised to use [scrollable<s
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------------------------------- |
| b | boolean | No | Scrollable status of the target component.<br>**true**: scrollable.<br>**false**: not scrollable.<br> Default value: **true**|
| b | boolean | No | Scrollable status of the target component.<br>**true**: scrollable.<br>**false**: not scrollable.<br>Default value: **true** |
**Return value**
......@@ -2845,7 +2845,7 @@ This API is deprecated since API version 9. You are advised to use [enabled<sup>
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | --------------------------------------------------------- |
| b | boolean | No | Enabled status of the target component.<br>**true**: enabled.<br>**false**: not disabled.<br> Default value: **true**|
| b | boolean | No | Enabled status of the target component.<br>**true**: enabled.<br>**false**: not enabled.<br>Default value: **true** |
**Return value**
......@@ -2873,7 +2873,7 @@ This API is deprecated since API version 9. You are advised to use [focused<sup>
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------------------------- |
| b | boolean | No | Focused status of the target component.<br>**true**: focused.<br>**false**: not focused.<br> Default value: **true**|
| b | boolean | No | Focused status of the target component.<br>**true**: focused.<br>**false**: not focused.<br>Default value: **true** |
**Return value**
......@@ -2901,7 +2901,7 @@ This API is deprecated since API version 9. You are advised to use [selected<sup
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| b | boolean | No | Selected status of the target component.<br>**true**: selected.<br>**false**: not selected.<br> Default value: **true**|
| b | boolean | No | Selected status of the target component.<br>**true**: selected.<br>**false**: not selected.<br>Default value: **true** |
**Return value**
......
# File Management Error Codes
The error codes of the file management subsystem consist of the following:
- Basic file I/O error codes
- User data management error codes
- User file access error codes
- Spatial statistics error codes
The error codes of the file management subsystem consist of the following:<br>- Basic file I/O error codes<br>- User data management error codes<br>- User file access error codes<br>- Spatial statistics error codes
## Basic File I/O Error Codes
......@@ -719,3 +714,41 @@ Fail to notify agent
**Solution**
Check whether the client is normal.
## Error Code Adaptation
The APIs provided by the file management subsystem support exception handling.
Sample code for exception handling in a synchronous API:
```js
import fs from '@ohos.file.fs'
try {
let file = fs.openSync(path, fs.OpenMode.READ_ONLY);
} catch (err) {
console.error("openSync errCode:" + err.code + ", errMessage:" + err.message);
}
```
Sample code for exception handling in an asynchronous API (promise):
```js
import fs from '@ohos.file.fs'
try {
let file = await fs.open(path, fs.OpenMode.READ_ONLY);
} catch (err) {
console.error("open promise errCode:" + err.code + ", errMessage:" + err.message);
}
```
Sample code for exception handling in an asynchronous API (callback):
```js
import fs from '@ohos.file.fs'
try {
fs.open(path, fs.OpenMode.READ_ONLY, function(e, file){ // Asynchronous thread (such as the system call) errors are obtained via a callback.
if (e) {
console.error("open in async errCode:" + e.code + ", errMessage:" + e.message);
}
});
} catch (err) {// Main thread errors (such as invalid parameters) are obtained by try catch.
console.error("open callback errCode:" + err.code + ", errMessage:" + err.message);
}
```
......@@ -534,9 +534,9 @@ Allows an application to change the telephone state.
**Enable ACL**: TRUE
## ohos.permission.START_ABILIIES_FROM_BACKGROUND
## ohos.permission.START_ABILITIES_FROM_BACKGROUND
Allows an application to start Feature abilities in the background.
Allows an application to start or access other components from the background.
**Permission level**: system_basic
......@@ -1594,6 +1594,16 @@ Allows a system application to obtain the authentication and networking capabili
**Enable ACL**: TRUE
## ohos.permission.APP_TRACKING_CONSENT
Allows an application to read advertisement identifiers.
**Permission level**: normal
**Authorization mode**: user_grant
**Enable ACL**: TRUE
## ohos.permission.RUN_ANY_CODE
Allows an application to run unsigned code.
......
......@@ -26,6 +26,7 @@
- [Exception Debugging](kernel-mini-memory-exception.md)
- [Trace](kernel-mini-memory-trace.md)
- [LMS](kernel-mini-memory-lms.md)
- [Shell](kernel-mini-debug-shell.md)
- Appendix
- [Kernel Coding Specification](kernel-mini-appx-code.md)
- [Standard Libraries](kernel-mini-appx-lib.md)
......
......@@ -177,7 +177,7 @@ int main (void) {
// ...
osKernelInitialize(); // Initialize CMSIS-RTOS.
osThreadNew(app_main, NULL, NULL); // Create the main thread of the application.
osThreadNew(app_main, NULL, NULL); // Create the main thread of the application.
osKernelStart(); // Start to execute the thread.
for (;;) {}
}
......@@ -196,14 +196,14 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
#### Available APIs
**Table 1** APIs for process management
**Table 11** APIs for process management
| Header File| API| Description|
| -------- | -------- | -------- |
| \#include &lt;stdlib.h&gt; | void abort(void); | Terminates the thread.|
| \#include &lt;assert.h&gt; | void assert(scalar expression); | Terminates the thread if the assertion is false.|
| \#include &lt;pthread.h&gt; | int pthread_cond_destroy(pthread_cond_t *cond); | Destroys a condition variable.|
| \#include &lt;pthread.h&gt; | int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t \*restrict attr); | Initializes a condition variable.|
| \#include &lt;pthread.h&gt; | int pthread_cond_destroy(pthread_cond_t \*cond); | Destroys a condition variable.|
| \#include &lt;pthread.h&gt; | int pthread_cond_init(pthread_cond_t \*restrict cond, const pthread_condattr_t \*restrict attr); | Initializes a condition variable.|
| \#include &lt;pthread.h&gt; | int pthread_cond_timedwait(pthread_cond_t \*restrict cond, pthread_mutex_t \*restrict mutex, const struct timespec \*restrict abstime); | Waits for the condition.|
| \#include &lt;pthread.h&gt; | int pthread_condattr_init(pthread_condattr_t \*attr); | Initializes the condition variable attribute.|
| \#include &lt;pthread.h&gt; | int pthread_mutex_unlock(pthread_mutex_t \*mutex); | Unlocks a mutex.|
......@@ -212,13 +212,13 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;pthread.h&gt; | pthread_t pthread_self(void); | Obtains the ID of the current thread.|
| \#include &lt;pthread.h&gt; | int pthread_getschedparam(pthread_t thread, int \*policy, struct sched_param \*param); | Obtains the scheduling policy and parameters of a thread.|
| \#include &lt;pthread.h&gt; | int pthread_setschedparam(pthread_t thread, intpolicy, const struct sched_param \*param); | Sets a scheduling policy and parameters for a thread.|
| \#include &lt;pthread.h&gt; | int pthread_mutex_init(pthread_mutex_t \* &#95;&#95;restrict m, const pthread_mutexattr_t \*__restrict a); | Initializes a mutex.|
| \#include &lt;pthread.h&gt; | int pthread_mutex_init(pthread_mutex_t *\_restrict m, const pthread_mutexattr_t \*__restrict a); | Initializes a mutex.|
| \#include &lt;pthread.h&gt; | int pthread_mutex_lock(pthread_mutex_t \*m); | Locks a mutex.|
| \#include &lt;pthread.h&gt; | int pthread_mutex_trylock(pthread_mutex_t \*m); | Attempts to lock a mutex.|
| \#include &lt;pthread.h&gt; | int pthread_mutex_destroy(pthread_mutex_t \*m); | Destroys a mutex.|
| \#include &lt;pthread.h&gt; | int pthread_attr_init(pthread_attr_t \*attr); | Initializes a thread attribute object.|
| \#include &lt;pthread.h&gt; | int pthread_attr_destroy(pthread_attr_t \*attr); | Destroys a thread attribute object.|
| \#include &lt;pthread.h&gt; | int pthread_attr_getstacksize(const&nbsp;pthread_attr_t&nbsp;\*attr,&nbsp;size_t&nbsp;\*stacksize); | Obtains the stack size of a thread attribute object.|
| \#include &lt;pthread.h&gt; | int pthread_attr_getstacksize(const pthread_attr*t \*attr, size*t \*stacksize); | Obtains the stack size of a thread attribute object.|
| \#include &lt;pthread.h&gt; | int pthread_attr_setstacksize(pthread_attr_t \*attr, size_t stacksize); | Sets the stack size for a thread attribute object.|
| \#include &lt;pthread.h&gt; | int pthread_attr_getschedparam(const pthread_attr_t \*attr, struct sched_param \*param); | Obtains scheduling parameter attributes of a thread attribute object.|
| \#include &lt;pthread.h&gt; | int pthread_attr_setschedparam(pthread_attr_t \*attr, const struct sched_param \*param); | Sets scheduling parameter attributes for a thread attribute object.|
......@@ -226,9 +226,9 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;pthread.h&gt; | int pthread_setname_np(pthread_t pthread, constchar \*name); | Sets the thread name.|
| \#include &lt;pthread.h&gt; | int pthread_cond_broadcast(pthread_cond_t \*c); | Unblocks all threads that are currently blocked on the condition variable **cond**.|
| \#include &lt;pthread.h&gt; | int pthread_cond_signal(pthread_cond_t \*c); | Unblocks a thread.|
| \#include &lt;pthread.h&gt; | int pthread_cond_wait(pthread_cond_t \*__restrictc, pthread_mutex_t \*__restrict m); | Waits for the condition.|
| \#include &lt;pthread.h&gt; | int pthread_cond_wait(pthread_cond_t *\__restrictc, pthread_mutex_t \*__restrict m); | Waits for the condition.|
**Table 2** APIs for file system management
**Table 12** APIs for file system management
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -250,7 +250,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;sys/stat.h&gt; | int fstat(int fd, struct stat \*buf); | Obtains file status.|
| \#include &lt;sys/statfs.h&gt; | int statfs(const char \*path, struct statfs \*buf); | Obtains the file system information for a file in a specified path.|
**Table 3** APIs for time management
**Table 13** APIs for time management
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -265,19 +265,19 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;unistd.h&gt; | int usleep(useconds_t usec); | Goes to hibernation, in microseconds.|
| \#include &lt;time.h&gt; | int nanosleep(const struct timespec \*tspec1, structtimespec \*tspec2); | Suspends the current thread till the specified time.|
| \#include &lt;time.h&gt; | int clock_gettime(clockid_t id, struct timespec \*tspec); | Obtains the clock time.|
| \#include &lt;time.h&gt; | int timer_create(clockid_t id, struct sigevent \*__restrict evp, timer_t \*__restrict t); | Creates a timer for a thread.|
| \#include &lt;time.h&gt; | int timer_create(clockid_t id, struct sigevent *\__restrict evp, timer_t \*__restrict t); | Creates a timer for a thread.|
| \#include &lt;time.h&gt; | int timer_delete(timer_t t); | Deletes the timer for a thread.|
| \#include &lt;time.h&gt; | int timer_settime(timer_t t, int flags, const structitimerspec \*__restrict val, struct itimerspec \*__restrict old); | Sets a timer for a thread.|
| \#include &lt;time.h&gt; | int timer_settime(timer_t t, int flags, const struct itimerspec *\__restrict val, struct itimerspec \*_restrict old); | Sets a timer for a thread.|
| \#include &lt;time.h&gt; | time_t time (time_t \*t); | Obtains the time.|
| \#include &lt;time.h&gt; | char \*strptime(const char \*s, const char \*format, struct tm \*tm); | Converts the time string into the time **tm** structure.|
**Table 4** APIs for util
**Table 14** APIs for util
| Header File| API| Description|
| -------- | -------- | -------- |
| \#include &lt;stdlib.h&gt; | int atoi(const char \*nptr); | Converts the string pointed to by **nptr** into an integer (**int** type).|
| \#include &lt;stdlib.h&gt; | long atol(const char \*nptr); | Converts the string pointed to by **nptr** into a long Integer (long type).|
| \#include &lt;stdlib.h&gt; | long long atoll(const char \*nptr); | Converts the string pointed to by **nptr** into a long long Integer (long long type).|
| \#include &lt;stdlib.h&gt; | int atoi(const char \*nptr); | Converts a string into an integer (**int** type).|
| \#include &lt;stdlib.h&gt; | long atol(const char \*nptr); | Converts the string into a long Integer (**long** type).|
| \#include &lt;stdlib.h&gt; | long long atoll(const char \*nptr); | Converts a string into a long longer integer (**long long** type).|
| \#include &lt;ctype.h&gt; | int isalnum(int c); | Checks whether the passed character is alphanumeric.|
| \#include &lt;ctype.h&gt; | int isascii(int c); | Checks whether the passed character is an ASCII character.|
| \#include &lt;ctype.h&gt; | int isdigit(int c); | Checks whether the passed character is a digit.|
......@@ -302,17 +302,17 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;strings.h&gt; | int strncasecmp(const char \*s1, const char \*s2, size_t n); | Compares the bytes of the specified length in two strings, ignoring case.|
| \#include &lt;strings.h&gt; | int strcasecmp(const char \*s1, const char \*s2); | Compares two strings, ignoring case.|
| \#include &lt;string.h&gt; | int strncmp(const char \*s1, const char \*s2, size_t n); | Compares the bytes of the specified length in two strings.|
| \#include &lt;string.h&gt; | char \*strrchr(const char \*s, int c); | Searches for the last occurrence of a character in a string.|
| \#include &lt;string.h&gt; | char \*strrchr(const char \*s, int c); | Searches for a character in a string.|
| \#include &lt;string.h&gt; | char \*strstr(const char \*haystack, const char \*needle); | Searches for the specified substring in a string.|
| \#include &lt;stdlib.h&gt; | long int strtol(const char \*nptr, char \*\*endptr, int base); | Converts the string pointed to by **nptr** into a **long int** value according to the given **base**.|
| \#include &lt;stdlib.h&gt; | unsigned long int strtoul(const char \*nptr, char\*\*endptr, int base); | Converts the string pointed to by **nptr** into an unsigned long integer.|
| \#include &lt;stdlib.h&gt; | unsigned long long int strtoull(const char \*nptr,char \*\*endptr, int base); | Converts the string pointed to by **nptr** into an unsigned long long integer.|
| \#include &lt;stdlib.h&gt; | unsigned long int strtoul(const char \*nptr, char\*\*endptr, int base); | Converts a string into an unsigned long integer.|
| \#include &lt;stdlib.h&gt; | unsigned long long int strtoull(const char \*nptr,char \*\*endptr,int base); | Converts a string into an unsigned long long integer.|
| \#include &lt;regex.h&gt; | int regcomp(regex_t \*preg, const char \*regex,int cflags); | Compiles a regular expression.|
| \#include &lt;regex.h&gt; | int regexec(const regex_t \*preg, const char \*string, size_t nmatch, regmatch_t pmatch[], int eflags); | Executes the compiled regular expression.|
| \#include &lt;regex.h&gt; | void regfree(regex_t \*preg); | Releases the regular expression.|
| \#include &lt;string.h&gt; | char \*strerror(int errnum); | Obtains an error message string of the specified error code.|
**Table 5** APIs for math operations
**Table 15** APIs for math operations
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -322,7 +322,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;math.h&gt; | double round(double x); | Rounds off the value from zero to the nearest integer.|
| \#include &lt;math.h&gt; | double sqrt(double x); | Obtains the square root of **x**.|
**Table 6** APIs for I/O operations
**Table 16** APIs for I/O operations
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -335,16 +335,16 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;stdio.h&gt; | int fileno(FILE \*stream); | Obtains the file descriptor for a stream.|
| \#include &lt;stdio.h&gt; | FILE \*fopen(const char \*path, const char \*mode); | Opens a stream.|
| \#include &lt;stdio.h&gt; | int fputs(const char \*s, FILE \*stream); | Writes a line to the specified stream.|
| \#include &lt;stdio.h&gt; | size_t fread(void \*ptr, size_t size, size_t nmemb,FILE \*stream); | Reads a stream.|
| \#include &lt;stdio.h&gt; | size_t fread(void \*ptr, size_t size, size_t nmemb, FILE \*stream); | Reads a stream.|
| \#include &lt;stdio.h&gt; | int fseek(FILE \*stream, long offset, int whence); | Sets the position of the stream pointer.|
| \#include &lt;stdio.h&gt; | long ftell(FILE \*stream); | Obtains the position of the stream pointer.|
| \#include &lt;stdio.h&gt; | size_t fwrite(const void \*ptr, size_t size, size_tnmemb,FILE \*stream); | Writes data to a stream.|
| \#include &lt;stdio.h&gt; | size_t fwrite(const void \*ptr, size_t size, size_tnmemb, FILE \*stream); | Writes data to a stream.|
| \#include &lt;stdio.h&gt; | void perror(const char \*s); | Prints system error information.|
| \#include &lt;stdio.h&gt; | void rewind(FILE \*stream); | Sets the position to the beginning of the file of the specified stream.|
| \#include &lt;unistd.h&gt; | ssize_t write(int fd, const void \*buf, size_t size); | Writes data a file.|
| \#include &lt;unistd.h&gt; | ssize_t read(int fd, void \*buf, size_t size); | Reads data from a file.|
**Table 7** APIs for network
**Table 17** APIs for network
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -363,7 +363,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;sys/socket.h&gt; | ssize_t sendto(int sockfd, const void \*buf, size_t len, intflags,const struct sockaddr \*dest_addr, socklen_t addrlen); | Sends a message on a socket.|
| \#include &lt;sys/socket.h&gt; | int setsockopt(int sockfd, int level, int optname,constvoid \*optval, socklen_t optlen); | Sets options associated with a socket.|
**Table 8** APIs for memory management
**Table 18** APIs for memory management
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -374,7 +374,7 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;stdlib.h&gt; | void \*malloc(size_t size); | Dynamically allocates memory blocks.|
| \#include &lt;stdlib.h&gt; | void free(void \*ptr); | Release the memory space pointed to by **ptr**.|
**Table 9** APIs for IPC
**Table 19** APIs for IPC
| Header File| API| Description|
| -------- | -------- | -------- |
......@@ -386,11 +386,11 @@ The OpenHarmony kernel uses the **musl libc** library and self-developed APIs an
| \#include &lt;mqueue.h&gt; | mqd_t mq_open(const char \*mqName, int openFlag, ...); | Opens an existing message queue with the specified name or creates a message queue.|
| \#include &lt;mqueue.h&gt; | int mq_close(mqd_t personal); | Closes a message queue with the specified descriptor.|
| \#include &lt;mqueue.h&gt; | int mq_unlink(const char \*mqName); | Deletes the message queue of the specified name.|
| \#include &lt;mqueue.h&gt; | int mq_send(mqd_t personal, const char \*msg,size_t msgLen, unsigned int msgPrio); | Puts a message with the specified content and length into a message queue.|
| \#include &lt;mqueue.h&gt; | ssize_t mq_receive(mqd_t personal, char \*msg,size_t msgLen, unsigned int \*msgPrio); | Deletes the oldest message from a message queue and puts it in the buffer pointed to by **msg_ptr**.|
| \#include &lt;mqueue.h&gt; | int mq_send(mqd_t personal, const char \*msg, size_t msgLen, unsigned int msgPrio); | Puts a message with the specified content and length into a message queue.|
| \#include &lt;mqueue.h&gt; | ssize_t mq_receive(mqd_t personal, char \*msg, size_t msgLen, unsigned int \*msgPrio); | Deletes the oldest message from a message queue and puts it in the buffer pointed to by **msg_ptr**.|
| \#include &lt;mqueue.h&gt; | int mq_timedsend(mqd_t personal, const char\*msg, size_t msgLen, unsigned int msgPrio, const struct timespec \*absTimeout) | Puts a message with the specified content and length into a message queue at the specified time.|
| \#include &lt;mqueue.h&gt; | ssize_t mq_timedreceive(mqd_t personal, char\*msg, size_t msgLen, unsigned int \*msgPrio, const struct timespec \*absTimeout); | Obtains a message with the specified content and length from a message queue.|
| \#include &lt;mqueue.h&gt; | int mq_setattr(mqd_t mqdes, const struct mq_attr \*__restrict newattr, struct mq_attr \*__restrict oldattr); | Sets the message queue attributes specified by the descriptor.|
| \#include &lt;mqueue.h&gt; | int mq_setattr(mqd_t mqdes, const struct mq_attr \*\_\_restrict newattr, struct mq_attr *\__restrict oldattr); | Sets the message queue attributes specified by the descriptor.|
| \#include &lt;libc.h&gt; | const char \*libc_get_version_string(void); | Obtains the libc version string.|
| \#include &lt;libc.h&gt; | int libc_get_version(void); | Obtains the libc version.|
......@@ -459,6 +459,8 @@ Example:
Creates a thread, transfers the information in the parent thread to the child thread, and prints the transferred information and the thread ID in the child thread.
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **DemoForTest** function is called in **TestTaskEntry**.
```
#include <stdio.h>
......
# Events
# Event
## Basic Concepts
An event is a mechanism for communication between tasks. It can be used to synchronize tasks. The events have the following features:
An event is a communication mechanism used to synchronize tasks. Events have the following features:
- Events can be synchronized in one-to-many or many-to-many mode. In one-to-many mode, a task can wait for multiple events. In many-to-many mode, multiple tasks can wait for multiple events. However, a write event wakes up only one task from the block.
- Event read timeout mechanism is used.
- Events are used only for task synchronization, but not for data transmission.
- Events are used for task synchronization, but not for data transmission.
APIs are provided to initialize, read/write, clear, and destroy events.
......@@ -18,7 +18,7 @@ APIs are provided to initialize, read/write, clear, and destroy events.
### Event Control Block
The event control block is a struct configured in the event initialization function. It is passed in as an input parameter to identify the event for operations such as event read and write. The data structure of the event control block is as follows:
The event control block is a structure in the event initialization function. It passes in event identifies for operations such as event read and write. The data structure of the event control block is as follows:
```
......@@ -31,23 +31,33 @@ typedef struct tagEvent {
### Working Principles
**Initializing an event**: An event control block is created to maintain a collection of processed events and a linked list of tasks waiting for specific events.
**Initializing an Event**
**Writing an event**: When a specified event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related task based on the task conditions.
An event control block is created to maintain a set of processed events and a linked list of tasks waiting for specific events.
**Reading an event**: If the read event already exists, it is returned synchronously. In other cases, the return time is determined based on the timeout period and event triggering status. If the wait event condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired.
**Writing an Event**
The input parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** indicates the mask of the event. **mode** indicates the handling mode, which can be any of the following:
When an event is written to the event control block, the event control block updates the event set, traverses the task linked list, and determines whether to wake up related tasks based on the task conditions.
- **LOS_WAITMODE_AND**: Event reading is successful only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
**Reading an Event**
- **LOS_WAITMODE_OR**: Event reading is successful when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
If the event to read already exists, it is returned synchronously. In other cases, the event is returned based on the timeout period and event triggering conditions. If the wait condition is met before the timeout period expires, the blocked task will be directly woken up. Otherwise, the blocked task will be woken up only after the timeout period has expired.
The parameters **eventMask** and **mode** determine whether the condition for reading an event is met. **eventMask** specifies the event mask. **mode** specifies the handling mode, which can be any of the following:
- **LOS_WAITMODE_AND**: Read the event only when all the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
- **LOS_WAITMODE_OR**: Read the event only when any of the events corresponding to **eventMask** occur. Otherwise, the task will be blocked, or an error code will be returned.
- **LOS_WAITMODE_CLR**: This mode must be used with one or all of the event modes (LOS_WAITMODE_AND | LOS_WAITMODE_CLR or LOS_WAITMODE_OR | LOS_WAITMODE_CLR). In this mode, if all event modes or any event mode is successful, the corresponding event type bit in the event control block will be automatically cleared.
**Clearing events**: Clear the event set of the event control block based on the specified mask. If the mask is **0**, the event set will be cleared. If the mask is **0xffff**, no event will be cleared, and the event set remains unchanged.
**Clearing Events**
The events in the event set of the event control block can be cleared based on the specified mask. The mask **0** means to clear the event set; the mask **0xffff** means the opposite.
**Destroying Events**
**Destroying an event**: Destroy the specified event control block.
The event control block can be destroyed to release resources.
**Figure 1** Event working mechanism for a mini system
......@@ -58,12 +68,12 @@ The input parameters **eventMask** and **mode** determine whether the condition
| Category| API| Description|
| -------- | -------- | -------- |
| Event check| LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.<br>**NOTICE**<br><br>If **mode** contains **LOS_WAITMODE_CLR** and the expected event occurs, the event that meets the requirements in **eventID** will be cleared. In this case, **eventID** is an input parameter and an output parameter. In other cases, **eventID** is used only as an input parameter.|
| Initialization| LOS_EventInit | Initializes an event control block.|
| Event read| LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).<br>If no event is read, **0** is returned.<br>If an event is successfully read, a positive value (event set) is returned.<br>In other cases, an error code is returned.|
| Event write| LOS_EventWrite | Writes an event to the event control block.|
| Event clearance| LOS_EventClear | Clears an event in the event control block based on the event mask.|
| Event destruction| LOS_EventDestroy | Destroys an event control block.|
| Checking an event | LOS_EventPoll | Checks whether the expected event occurs based on **eventID**, **eventMask**, and **mode**.<br>**NOTE**<br>If **mode** contains **LOS_WAITMODE_CLR** and the expected event occurs, the event that meets the requirements in **eventID** will be cleared. In this case, **eventID** is an input parameter and an output parameter. In other cases, **eventID** is used only as an input parameter. |
| Initializing an event control block | LOS_EventInit | Initializes an event control block.|
| Reading an event | LOS_EventRead | Reads an event (wait event). The task will be blocked to wait based on the timeout period (in ticks).<br>If no event is read, **0** is returned.<br>If an event is successfully read, a positive value (event set) is returned.<br>In other cases, an error code is returned.|
| Writing an event | LOS_EventWrite | Writes an event to the event control block.|
| Clearing events | LOS_EventClear | Clears events in the event control block based on the event mask. |
| Destroying events | LOS_EventDestroy | Destroys an event control block.|
## How to Develop
......@@ -72,11 +82,11 @@ The typical event development process is as follows:
1. Initialize an event control block.
2. Block a read event control block.
2. Block a read event.
3. Write related events.
3. Write events.
4. Wake up a blocked task, read the event, and check whether the event meets conditions.
4. Wake up the blocked task, read the event, and check whether the event meets conditions.
5. Handle the event control block.
......@@ -84,7 +94,7 @@ The typical event development process is as follows:
> **NOTE**
> - When an event is read or written, the 25th bit of the event is reserved and cannot be set.
> - For event read and write operations, the 25th bit (`0x02U << 24`) of the event is reserved and cannot be set.
>
> - Repeated writes of the same event are treated as one write.
......@@ -111,7 +121,7 @@ In the **ExampleEvent** task, create an **EventReadTask** task with a timout per
The sample code is as follows:
The sample code is compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleEvent()** in **TestTaskEntry**.
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleEvent()** function is called in **TestTaskEntry**.
```
......
......@@ -77,7 +77,7 @@ The preceding figure illustrates how to write data to the tail node only. Writin
## Available APIs
| Category| Description|
| Category| API Description |
| -------- | -------- |
| Creating or deleting a message queue| **LOS_QueueCreate**: creates a message queue. The system dynamically allocates the queue space.<br>**LOS_QueueCreateStatic**: creates a static message queue. You need to pass in the queue space.<br>**LOS_QueueDelete**: deletes a message queue. After a static message queue is deleted, you need to release the queue space.|
| Reading or writing data (address without the content) in a queue| **LOS_QueueRead**: reads data in the head node of the specified queue. The data in the queue node is an address.<br>**LOS_QueueWrite**: writes the **bufferAddr** (buffer address) to the tail node of the specified queue.<br>**LOS_QueueWriteHead**: writes the **bufferAddr** (buffer address) to the head node of the specified queue.|
......@@ -136,7 +136,7 @@ Create a queue and two tasks. Enable task 1 to write data to the queue, and task
The sample code is as follows:
The sample code is compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleQueue** in **TestTaskEntry**.
The sample code can be compiled and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. The **ExampleQueue** function is called in **TestTaskEntry**.
```
......
此差异已折叠。
# Bitwise Operation
## Basic Concepts
A bitwise operation operates on a binary number at the level of its individual bits. For example, a variable can be set as a program status word \(PSW\), and each bit \(flag bit\) in the PSW can have a self-defined meaning.
## Available APIs<a name="section848334511411"></a>
The system provides operations for setting the flag bit to **1** or **0**, changing the flag bit content, and obtaining the most significant bit and least significant bit of the flag bit 1 in a PSW. You can also perform bitwise operations on system registers. The following table describes the APIs available for the bitwise operation module. For more details about the APIs, see the API reference.
**Table 1** Bitwise operation module APIs
<a name="table148791521769"></a>
<table><thead align="left"><tr id="row13880624615"><th class="cellrowborder" valign="top" width="16.89168916891689%" id="mcps1.2.4.1.1"><p id="p1587119571763"><a name="p1587119571763"></a><a name="p1587119571763"></a>Function</p>
</th>
<th class="cellrowborder" valign="top" width="35.54355435543554%" id="mcps1.2.4.1.2"><p id="p38714577610"><a name="p38714577610"></a><a name="p38714577610"></a>API</p>
</th>
<th class="cellrowborder" valign="top" width="47.56475647564757%" id="mcps1.2.4.1.3"><p id="p108711657563"><a name="p108711657563"></a><a name="p108711657563"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row18801722069"><td class="cellrowborder" rowspan="2" valign="top" width="16.89168916891689%" headers="mcps1.2.4.1.1 "><p id="p108717579612"><a name="p108717579612"></a><a name="p108717579612"></a>Setting the flag bit to <strong id="b129301229122320"><a name="b129301229122320"></a><a name="b129301229122320"></a>1</strong> or <strong id="b1899463182312"><a name="b1899463182312"></a><a name="b1899463182312"></a>0</strong></p>
</td>
<td class="cellrowborder" valign="top" width="35.54355435543554%" headers="mcps1.2.4.1.2 "><p id="p88717574616"><a name="p88717574616"></a><a name="p88717574616"></a>LOS_BitmapSet</p>
</td>
<td class="cellrowborder" valign="top" width="47.56475647564757%" headers="mcps1.2.4.1.3 "><p id="p16871957668"><a name="p16871957668"></a><a name="p16871957668"></a>Sets a flag bit of a PSW to <strong id="b1283195411179"><a name="b1283195411179"></a><a name="b1283195411179"></a>1</strong>.</p>
</td>
</tr>
<tr id="row38805219612"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p68713574610"><a name="p68713574610"></a><a name="p68713574610"></a>LOS_BitmapClr</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p14871155718618"><a name="p14871155718618"></a><a name="p14871155718618"></a>Sets a flag bit of a PSW to <strong id="b15267438112312"><a name="b15267438112312"></a><a name="b15267438112312"></a>0</strong>.</p>
</td>
</tr>
<tr id="row16880112663"><td class="cellrowborder" rowspan="2" valign="top" width="16.89168916891689%" headers="mcps1.2.4.1.1 "><p id="p158710579615"><a name="p158710579615"></a><a name="p158710579615"></a>Obtaining the bit whose flag bit is <strong id="b58742415239"><a name="b58742415239"></a><a name="b58742415239"></a>1</strong></p>
</td>
<td class="cellrowborder" valign="top" width="35.54355435543554%" headers="mcps1.2.4.1.2 "><p id="p1787145718612"><a name="p1787145718612"></a><a name="p1787145718612"></a>LOS_HighBitGet</p>
</td>
<td class="cellrowborder" valign="top" width="47.56475647564757%" headers="mcps1.2.4.1.3 "><p id="p168713571468"><a name="p168713571468"></a><a name="p168713571468"></a>Obtains the most significant bit of <strong id="b485014714235"><a name="b485014714235"></a><a name="b485014714235"></a>1</strong> in the PSW.</p>
</td>
</tr>
<tr id="row138803219613"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p15871957467"><a name="p15871957467"></a><a name="p15871957467"></a>LOS_LowBitGet</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p148719571569"><a name="p148719571569"></a><a name="p148719571569"></a>Obtains the least significant bit of <strong id="b9907125542319"><a name="b9907125542319"></a><a name="b9907125542319"></a>1</strong> in the PSW.</p>
</td>
</tr>
<tr id="row0880182168"><td class="cellrowborder" rowspan="3" valign="top" width="16.89168916891689%" headers="mcps1.2.4.1.1 "><p id="p10871957265"><a name="p10871957265"></a><a name="p10871957265"></a>Operating continuous bits</p>
</td>
<td class="cellrowborder" valign="top" width="35.54355435543554%" headers="mcps1.2.4.1.2 "><p id="p787185717616"><a name="p787185717616"></a><a name="p787185717616"></a>LOS_BitmapSetNBits</p>
</td>
<td class="cellrowborder" valign="top" width="47.56475647564757%" headers="mcps1.2.4.1.3 "><p id="p10871135714613"><a name="p10871135714613"></a><a name="p10871135714613"></a>Sets the continuous flag bits of a PSW to <strong id="b145631313234"><a name="b145631313234"></a><a name="b145631313234"></a>1</strong>.</p>
</td>
</tr>
<tr id="row12881728619"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18710575615"><a name="p18710575615"></a><a name="p18710575615"></a>LOS_BitmapClrNBits</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1387145711610"><a name="p1387145711610"></a><a name="p1387145711610"></a>Sets the continuous flag bits of a PSW to <strong id="b185031722103115"><a name="b185031722103115"></a><a name="b185031722103115"></a>0</strong>.</p>
</td>
</tr>
<tr id="row4881192262"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1987155714611"><a name="p1987155714611"></a><a name="p1987155714611"></a>LOS_BitmapFfz</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p187115571369"><a name="p187115571369"></a><a name="p187115571369"></a>Obtains the first 0 bit starting from the least significant bit (LSB).</p>
</td>
</tr>
</tbody>
</table>
## Development Example<a name="section67569495514"></a>
### Example Description<a name="section33551554391"></a>
A bitwise operation operates on the bits of a binary number. A variable can be set as a program status word (PSW), and each bit (flag bit) in the PSW can have a self-defined meaning.
## **Available APIs**
The system provides operations for setting the flag bit to **1** or **0**, changing the flag bit content, and obtaining the most significant bit (MSB) and least significant bit (LSB) of the flag bit 1 in a PSW. You can also perform bitwise operations on system registers. The following table describes the APIs available for the bitwise operation module. For more details about the APIs, see the API reference.
**Table 1** APIs of the bitwise operation module
| Category | API Description |
| -------- | -------- |
| Setting a flag bit| - **LOS_BitmapSet**: sets a flag bit of a PSW to **1**.<br>- **LOS_BitmapClr**: sets a flag bit of a PSW to **0**. |
| Obtaining the bit whose flag bit is **1**| -**LOS_HighBitGet**: obtains the most significant bit of 1 in a PSW.<br>- **LOS_LowBitGet**: obtains the least significant bit of 1 in a PSW. |
| Operating continuous bits| - **LOS_BitmapSetNBits**: sets the consecutive flag bits of a PSW to **1**.<br>- **LOS_BitmapClrNBits**: sets the consecutive flag bits of a PSW to **0**.<br>- **LOS_BitmapFfz**: obtains the first 0 bit starting from the LSB. |
## Development Example
### Example Description
This example implements the following:
1. Set a flag bit to **1**.
2. Obtain the most significant bit of flag bit 1.
3. Set a flag bit to **0**.
4. Obtain the least significant bit of the flag bit 1.
1. Set a flag bit to **1**.
2. Obtain the MSB of flag bit 1.
3. Set a flag bit to **0**.
4. Obtain the LSB of flag bit 1.
### Sample Code
The sample code can be compiled and verified in **./kernel/liteos_a/testsuites/kernel/src/osTest.c**. The **BitSample** function is called in **TestTaskEntry**.
```
#include "los_bitmap.h"
......@@ -105,10 +67,12 @@ static UINT32 BitSample(VOID)
}
```
### Verification
The development is successful if the return result is as follows:
```
Bitmap Sample!
The flag is 0x10101010
......@@ -117,4 +81,3 @@ LOS_HighBitGet:The highest one bit is 28, the flag is 0x10101110
LOS_BitmapClr: pos : 28, the flag is 0x00101110
LOS_LowBitGet: The lowest one bit is 4, the flag is 0x00101110
```
......@@ -13,10 +13,12 @@ The following describes how to set up the Ubuntu environment.
## System Requirements
- Ubuntu: Ubuntu 18.04 to 21.10; version 20.04 with 16 GB or larger memory is recommended
- Ubuntu: Ubuntu 18.04 to 21.10; version 20.04 with 16 GB or larger memory and a 100 GB or larger hard disk is recommended
- User name (Ubuntu): cannot contain Chinese characters
- DevEco Device Tool: latest and same version installed on both Ubuntu and Windows
## Procedure
......@@ -28,6 +30,7 @@ The following describes how to set up the Ubuntu environment.
```
![en-us_image_0000001226764302](figures/en-us_image_0000001226764302.png)
2. Start the command-line tool, run the following command, enter your password, and select **No** to set **Ubuntu shell** to **bash**.
```shell
......@@ -36,24 +39,24 @@ The following describes how to set up the Ubuntu environment.
![ubuntu-dash-to-bash](figures/ubuntu-dash-to-bash.png)
2. Download the [DevEco Device Tool 3.0 Release](https://device.harmonyos.com/cn/ide#download) Linux edition.
2. Download the latest version of [DevEco Device Tool](https://device.harmonyos.com/cn/ide#download) for Linux.
3. Decompress the DevEco Device Tool software package and assign permission on the folder obtained from the decompression.
1. Go to the directory where the DevEco Device Tool software package is stored and run the following command to decompress the software package. In the command, change **devicetool-linux-tool-3.1.0.300.zip** to the actual software package name.
1. Go to the directory where the DevEco Device Tool software package is stored and run the following command to decompress the software package. In the command, **devicetool-linux-tool-{Version}.zip** indicates the software package name.
```shell
unzip devicetool-linux-tool-3.1.0.300.zip
unzip devicetool-linux-tool-{Version}.zip
```
2. Open the folder of the decompressed software package and run the following command to grant the execute permission on the installation file. In the command, change **devicetool-linux-tool-3.1.0.300.sh** to the actual installation file name.
2. Open the folder of the decompressed software package and run the following command to grant the execute permission on the installation file. In the command, **devicetool-linux-tool-{Version}.sh** indicates the installation file name.
```shell
chmod u+x devicetool-linux-tool-3.1.0.300.sh
chmod u+x devicetool-linux-tool-{Version}.sh
```
4. Run the following command to install DevEco Device Tool, where **devicetool-linux-tool-3.1.0.300.sh** indicates the installation file name.
4. Run the following command to install DevEco Device Tool, where **devicetool-linux-tool-{Version}.sh** indicates the installation file name.
```shell
sudo ./devicetool-linux-tool-3.1.0.300.sh
sudo ./devicetool-linux-tool-{Version}.sh
```
5. On the page for agreeing to the user agreement and privacy statement, read and agree to the user agreement and privacy statement. You can scroll through the options by pressing the up and down arrow keys on the keyboard.
......
......@@ -36,7 +36,7 @@ base/telephony/
## Constraints
1. The open-source version currently provides the cellular call (CS call only), SMS & MMS, and cellular data services and supports the dual-SIM framework.
2. The Hardware Device Interface (HDI) support is subject to the chip vendors' adaptation capability. For details, see [Telephony Development](../device-dev/subsystems/subsys-tel-guide).
2. The Hardware Device Interface (HDI) support is subject to the chip vendors' adaptation capability. For details, see [Telephony Development](../device-dev/subsystems/subsys-tel-overview.md).
## Usage Guidelines
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册