提交 0933e6a5 编写于 作者: T Ted 提交者: Gitee

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

Signed-off-by: NTed <wangruichang@huawei.com>
......@@ -23,12 +23,10 @@ Example URIs:
- Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10*
- Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10*
> **NOTE**
>
>
> In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**.
## Available APIs
**Table 1** Data ability lifecycle APIs
......@@ -140,7 +138,7 @@ Import the basic dependency packages and obtain the URI string for communicating
The basic dependency packages include:
- @ohos.ability.featureAbility
- @ohos.data.dataability
- @ohos.data.dataAbility
- @ohos.data.rdb
#### Data Ability API Development
......@@ -154,7 +152,7 @@ The basic dependency packages include:
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb'
var urivar = "dataability:///com.ix.DataAbility"
var DAHelper = featureAbility.acquireDataAbilityHelper(
urivar
......
......@@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h
The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md).
**Table 2** Ability APIs
|API|Description|
|:------|:------|
|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.|
......@@ -58,7 +59,7 @@ To create Page abilities for an application in the stage model, you must impleme
```
import AbilityStage from "@ohos.application.AbilityStage"
```
2. Implement the `AbilityStage` class.
2. Implement the `AbilityStage` class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**.
```ts
export default class MyAbilityStage extends AbilityStage {
onCreate() {
......@@ -70,9 +71,9 @@ To create Page abilities for an application in the stage model, you must impleme
```js
import Ability from '@ohos.application.Ability'
```
4. Implement the lifecycle callbacks of the `Ability` class.
4. Implement the lifecycle callbacks of the `Ability` class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**.
In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md).
In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/application-window-stage.md).
```ts
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
......@@ -87,7 +88,7 @@ To create Page abilities for an application in the stage model, you must impleme
console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => {
console.log("MainAbility load content succeed with data: " + JSON.stringify(data))
console.log("MainAbility load content succeed")
}).catch((error) => {
console.error("MainAbility load content failed with error: " + JSON.stringify(error))
})
......@@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme
}
```
### Obtaining AbilityStage and Ability Configurations
Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows:
Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details.
The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows:
```ts
import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage {
......@@ -140,7 +144,7 @@ export default class MainAbility extends Ability {
console.log("MainAbility ability name" + abilityInfo.name)
let config = this.context.config
console.log("MyAbilityStage config language" + config.language)
console.log("MainAbility config language" + config.language)
}
}
```
......
......@@ -74,7 +74,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
console.log("on close")
});
// Bind the IP address and port number.
// Bind the local IP address and port number.
let bindAddress = {
address: '192.168.xx.xx',
port: 1234, // Bound port, for example, 1234.
......
# Distributed Data Service Overview<a name="EN-US_TOPIC_0000001183067628"></a>
# Distributed Data Service Overview
The distributed data service \(DDS\) implements distributed database collaboration across devices for applications. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices.
The distributed data service (DDS) implements distributed database collaboration across devices for applications.
## Basic Concepts<a name="section17506141102520"></a>
Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices.
You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts
- **KV data model**
......@@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati
The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases.
## Working Principles<a name="section315111581616"></a>
## Working Principles
The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following:
......@@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d
![](figures/en-us_image_0000001183386164.png)
## Constraints<a name="section95382010203311"></a>
## Constraints
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database.
- The KV data model specifications supported by the DDS are as follows:
......
......@@ -2,45 +2,48 @@
> **NOTE**
>
> This feature is supported since API Version 9. For the versions earlier than API Version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
> This feature is supported since API Version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
## When to Use
Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs.
Preferences are used for storing the data that is frequently used by applications, but not for storing a large amount of data or data frequently changed. The application data is persistently stored on a device in the form of files.
## Available APIs
Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can call the **Preferences** APIs to manage data.
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md).
## Available APIs
### Creating a Preferences Instance
The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required.
Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance.
The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.
**Table 1** API for creating a **Preferences** instance
For details about **Preferences** APIs, see [Preferences](../reference/apis/js-apis-data-preferences.md).
| Package | API | Description |
| ----------------- | ------------------------------------------- | ------------------------------------------- |
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance for data operations.|
### Obtaining a **Preferences** Instance
### Writing Data
Obtain a **Preferences** instance for data operations. A **Preferences** instance is obtained after data is read from a specified file and loaded to the instance.
Call the **put()** method to add or modify data in a **Preferences** instance.
**Table 1** API for obtaining a **Preferences** instance
**Table 2** API for writing data
| Package | API | Description |
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\<Preferences> | Obtains a **Preferences** instance.|
| Class | API | Description |
| ------- | -------------------------------------------------- | ----------------------------------------------- |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Accessing Data
### Reading Data
Call the **put()** method to add or modify data in a **Preferences** instance.
Call the **get()** method to read data from a **Preferences** instance.
**Table 3** API for reading data
Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance.
**Table 2** APIs for accessing **Preferences** data
| Class | API | Description |
| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data to the **Preferences** instance. The value to write can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data from the **Preferences** instance. The value to read can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| Preferences | getAll(): Promise<Object> | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance. |
| Class | API | Description |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- |
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Storing Data Persistently
......@@ -48,18 +51,18 @@ Call the **flush()** method to write the cached data back to its text file for p
**Table 4** API for data persistence
| Class | API | Description |
| ------- | ----------------------- | --------------------------------------- |
| Preferences | flush(): Promise\<void> | Writes data from the **Preferences** instance back to its file through an asynchronous thread.|
| Class | API | Description |
| ----------- | ----------------------- | ------------------------------------------- |
| Preferences | flush(): Promise\<void> | Flushes data from the **Preferences** instance to its file through an asynchronous thread.|
### Observing Data Changes
You can subscribe to data changes. When the value of the subscribed key is changed by **flush()**, a callback will be invoked to return the new data.
You can subscribe to data changes. When the value of the subscribed key is changed and saved by **flush()**, a callback will be invoked to return the new data.
**Table 5** APIs for observing **Preferences** changes
| Class | API | Description |
| ------- | ------------------------------------------------------------ | -------------- |
| Class | API | Description |
| ----------- | ------------------------------------------------------------ | -------------- |
| Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.|
| Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes. |
......@@ -69,57 +72,58 @@ Use the following APIs to delete a **Preferences** instance or data file.
**Table 6** APIs for deleting **Preferences**
| Package | API | Description |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void>; | Deletes a **Preferences** instance from the cache and deletes its file from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory.
| Package | API | Description |
| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void> | Deletes a **Preferences** instance from the memory and its files from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void> | Removes a **Preferences** instance from the memory to release memory. |
## How to Develop
1. Import @ohos.data.preferences and related modules to the development environment.
```js
import data_preferences from '@ohos.data.preferences'
import data_preferences from '@ohos.data.preferences';
```
2. Create a **Preferences** instance.
2. Obtain a **Preferences** instance.
Read the specified file and load its data to the **Preferences** instance for data operations.
```js
let promise = data_preferences.getPreferences(this.context, 'mystore')
let promise = data_preferences.getPreferences(this.context, 'mystore');
```
3. Write data.
Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance.
Use the **preferences.put()** method to write data to the **Preferences** instance.
```js
promise.then((preferences) => {
let putPromise = preferences.put('startup', 'auto')
let putPromise = preferences.put('startup', 'auto');
putPromise.then(() => {
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
}).catch((err) => {
console.info("Failed to put the value of startup with err: " + err)
console.info("Failed to put the value of 'startup'. Cause: " + err);
})
}).catch((err) => {
console.info("Failed to get the preferences")
console.info("Failed to get the preferences.");
})
```
4. Read data.
Use the **get()** method of the **Preferences** class to read data.
Use the **preferences.get()** method to read data.
```js
promise.then((preferences) => {
let getPromise = preferences.get('startup', 'default')
let getPromise = preferences.get('startup', 'default');
getPromise.then((value) => {
console.info("The value of startup is " + value)
console.info("The value of 'startup' is " + value);
}).catch((err) => {
console.info("Failed to get the value of startup with err: " + err)
console.info("Failed to get the value of 'startup'. Cause: " + err);
})
}).catch((err) => {
console.info("Failed to get the preferences")})
console.info("Failed to get the preferences.")
});
```
5. Store data persistently.
......@@ -132,38 +136,38 @@ Use the following APIs to delete a **Preferences** instance or data file.
6. Observe data changes.
Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, the observe callback will be invoked to return the change.
Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data.
```js
var observer = function (key) {
console.info("The key of " + key + " changed.")
console.info("The key" + key + " changed.");
}
preferences.on('change', observer)
preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of startup with err: " + err)
return
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Put the value of startup successfully.")
console.info("Put the value of 'startup' successfully.");
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data to file with err: " + err)
return
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Flushed to file successfully.") // Observer will be called.
console.info("Flushed data successfully."); // The observer will be called.
})
})
```
7. Delete the specified file.
Use the **deletePreferences** method to delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored.
```js
let proDelete = data_preferences.deletePreferences(context, 'mystore')
let proDelete = data_preferences.deletePreferences(context, 'mystore');
proDelete.then(() => {
console.info("Data deleted successfully.")
console.info("Deleted data successfully.");
}).catch((err) => {
console.info("Failed to delete data with err: " + err)
console.info("Failed to delete data. Cause: " + err);
})
```
# Preferences Overview
Preferences are used for access and persistence operations on the data in the key-value structure. When an application accesses a **Preferences** instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files.
Preferences are used to implement quick access and persistence of the data in the `key-value` structure.
After an application obtains a **Preferences** instance, the data in the instance will be cached in the memory for faster access.
The cached data can also be written to a text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing files.
You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts
- **Key-value data structure**
- **Key-value structure**
A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified.
A type of data structure. The `Key` is the unique identifier for a piece of data, and the `Value` is the specific data being identified.
- **Non-relational database**
A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) database management properties of relational data transactions. The data in a non-relational database is independent.
A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) properties of relational data transactions. The data in a non-relational database is independent. The database that organizes data in the `key-value` structure is a non-relational database.
## Working Principles
When an application loads data from a **Preferences** file to a **Preferences** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** file.
When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the instance can be flushed to its **Preferences** file by calling the **flush()** method.
1. An application can load data from a **Preferences** persistent file to a **Preferences** instance. The system stores the **Preferences** instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** persistent file.
2. When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the `Preferences` instance can be flushed to its **Preferences** persistent file by calling the **flush()** method.
**Figure 1** How **Preferences** work
**Figure 1** Working mechanism
![](figures/preferences.png)
## Constraints
- **Preferences** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Preferences** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes.
- The value of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty.
- The `Key` in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes.
- The `Value` of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty.
......@@ -2,6 +2,8 @@
The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements.
You do not need to care about the implementation of the database locking mechanism.
## Basic concepts
- **RDB**
......
......@@ -2,89 +2,164 @@
## When to Use
The event logging function helps applications to log various information generated during running.
The event logging function helps applications log various information generated during running.
## Available APIs
JS application event logging APIs are provided by the **hiAppEvent** module.
**Table 1** APIs for event logging
The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiappevent.md).
| API | Return Value | Description |
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
| write(string eventName, EventType type, object keyValues, AsyncCallback\<void> callback): void | void | Logs application events in asynchronous mode. This method uses an asynchronous callback to return the result. |
| write(string eventName, EventType type, object keyValues): Promise\<void> | Promise\<void> | Logs application events in asynchronous mode. This method uses a promise to return the result. |
**Table 1** APIs for application event logging
When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes).
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| write(string eventName, EventType type, object keyValues, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result. |
| write(string eventName, EventType type, object keyValues): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. |
| write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events by domain in asynchronous mode. This API uses an asynchronous callback to return the result.|
| write(AppEventInfo info): Promise\<void> | Logs application events by domain in asynchronous mode. This API uses a promise to return the result.|
**Table 2** APIs for event logging configuration
When an asynchronous callback is used, the return value can be processed directly in the callback.
| API | Return Value | Description |
| ------------------------------ | ------------ | ------------------------------------------------------------ |
| configure(ConfigOption config) | boolean | Sets the configuration options for application event logging.<br>The value **true** indicates that the operation is successful, and value **false** indicates the opposite. |
If a promise is used, the return value can also be processed in the promise in a similar way.
## Event Verification Result Codes
For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes).
| Result Code | Cause | Check Rule | Processing Method |
| ----------- | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 0 | None | Event verification is successful. | Event logging is normal. No action is required. |
| -1 | Invalid event name | The event name is not empty and contains a maximum of 48 characters.<br/>The event name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).<br/>The event name does not start with a digit or underscore (_). | Ignore this event and do not perform logging. |
| -2 | Invalid event parameter type | The event name must be a string.<br/>The event type must be a number.<br/>The key value must be an object. | Ignore this event and do not perform logging. |
| -99 | Application event logging disabled | The application event logging function is disabled. | Ignore this event and do not perform logging. |
| -100 | Unknown error | None | Ignore this event and do not perform logging. |
| 1 | Invalid key name | The key name is not empty and contains a maximum of 16 characters.<br/>The key name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).<br/>The key name does not start with a digit or underscore (\_).<br/>The key name does not end with an underscore (_). | Ignore the key-value pair and continue to perform logging. |
| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. |
| 3 | Invalid value type | The supported value types vary depending on the programming language:<br/>boolean, number, string, or Array [basic element] | Ignore the key-value pair and continue to perform logging. |
| 4 | Value too long | The value can contain a maximum of 8*1024 characters. | Ignore the key-value pair and continue to perform logging. |
| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. |
| 6 | Excess elements in a list value | The number of elements in a list value must be less than or equal to 100. | Truncate the list with only the first 100 elements retained, and continue to perform logging. |
| 7 | Invalid list value | A list value can only be a basic element.<br/>The elements in a list value must be of the same type. | Ignore the key-value pair and continue to perform logging. |
**Table 2** APIs for event logging configuration
| API | Description |
| --------------------------------------- | ---------------------------------------------------- |
| configure(ConfigOption config): boolean | Sets the configuration options for application event logging.|
## How to Develop
**Table 3** APIs for watcher management
In this example, an application event is logged after the application startup execution page is loaded.
| API | Description |
| -------------------------------------------------- | -------------------- |
| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher.|
| removeWatcher(Watcher watcher): void | Removes an event watcher.|
1. Create a JS application project. In the displayed Project window, choose **entry > src > main** > **js** > **default** > **pages > index**, and double-click index.js. Add the code to log the initial application event after page loading. The sample code is as follows:
**Table 4** APIs for clearing logging data
```js
import hiAppEvent from '@ohos.hiAppEvent'
| API | Description |
| ----------------- | -------------------- |
| clearData(): void | Clears local logging data.|
### Event Verification Result Codes
| Result Code| Cause | Verification Rules | Handling Method |
| ------ | ----------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- |
| 0 | N/A | Event verification is successful. | Event logging is normal. No action is required. |
| -1 | Invalid event name | The name is not empty and contains a maximum of 48 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. |
| -2 | Invalid event parameter type | The event name must be a string.<br>The event type must be a number.<br>The event parameter must be an object.| Ignore this event and do not perform logging. |
| -4 | Invalid event domain name | The name is not empty and contains a maximum of 32 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. |
| -99 | Application event logging disabled | Application event logging is disabled. | Ignore this event and do not perform logging. |
| -100 | Unknown error | None. | Ignore this event and do not perform logging. |
| 1 | Invalid key name | The name is not empty and contains a maximum of 16 characters.<br>The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).<br>The name does not start with a digit or underscore \(_).<br>The name does not end with an underscore \(_).| Ignore the key-value pair and continue to perform logging. |
| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. |
| 3 | Invalid value type | The supported value types vary depending on the programming language:<br>boolean, number, string, or Array [basic element]| Ignore the key-value pair and continue to perform logging. |
| 4 | Invalid length for values of the string type| For a value of the string type, the maximum length is 8*1024 characters. | Truncate the value with the first 8*1024 characters retained, and continue to perform logging.|
| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. |
| 6 | Invalid number of elements in values of the array type | For a value of the array type, the number of elements must be less than or equal to 100. | Truncate the array with the first 100 elements retained, and continue to perform logging. |
| 7 | Invalid parameters in values of the array type | For a value of the array type, all the parameters must be of the same type, which can only be boolean, number, or string.| Ignore the key-value pair and continue to perform logging. |
## Development Procedure
The following uses a one-time event watcher as an example to illustrate the development procedure.
1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows:
```ts
import hiAppEvent from '@ohos.hiAppEvent';
export default {
data: {
title: ""
},
onInit() {
this.title = this.$t('strings.world');
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
// 1. Callback mode
hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"}, (err, value) => {
if (err) {
console.error(`failed to write event because ${err.code}`);
return;
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button("1 writeTest").onClick(()=>{
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
eventType: hiAppEvent.EventType.FAULT,
params: {
int_data: 100,
str_data: "strValue"
}
console.log(`success to write event: ${value}`);
});
}).then((value) => {
console.log(`HiAppEvent success to write event: ${value}`);
}).catch((err) => {
console.error(`HiAppEvent failed to write event because ${err.code}`);
});
})
// 2. Promise mode
hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"})
.then((value) => {
console.log(`success to write event: ${value}`);
}).catch((err) => {
console.error(`failed to write event because ${err.code}`);
});
// 3. Set the application event logging switch.
hiAppEvent.configure({
disable: true
});
Button("2 addWatcherTest").onClick(()=>{
hiAppEvent.addWatcher({
name: "watcher1",
appEventFilters: [{ domain: "test_domain" }],
triggerCondition: {
row: 2,
size: 1000,
timeOut: 2
},
onTrigger: function (curRow, curSize, holder) {
if (holder == null) {
console.error("HiAppEvent holder is null");
return;
}
let eventPkg = null;
while ((eventPkg = holder.takeNext()) != null) {
console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId);
console.info("HiAppEvent eventPkg.row=" + eventPkg.row);
console.info("HiAppEvent eventPkg.size=" + eventPkg.size);
for (const eventInfo of eventPkg.data) {
console.info("HiAppEvent eventPkg.data=" + eventInfo);
}
}
}
});
})
// 4. Set the maximum size of the event file storage directory. The default value is 10M.
hiAppEvent.configure({
maxStorage: '100M'
});
Button("3 removeWatcherTest").onClick(()=>{
hiAppEvent.removeWatcher({
name: "watcher1"
})
})
}
.width('100%')
}
.height('100%')
}
}
```
2. Tap the run button on the application UI to run the project.
2. Touch the run button on the IDE to run the project.
3. Touch button 1 on the application UI to start application event logging. If the logging is successful, you'll see the following message in the **Log** window:
```
success to write event: 0
```
4. On the application UI, touch button 2 to add an event watcher, and touch button 1 for multiple times to perform application event logging. If any callback trigger condition (event count, event data size, and timeout duration) is met, the event watcher will invoke a callback and the event package obtained through the callback will be displayed in the **Log** window.
```
HiAppEvent eventPkg.packageId=0
HiAppEvent eventPkg.row=2
HiAppEvent eventPkg.size=308
HiAppEvent eventPkg.data={"domain_":"test_domain","name_":"test_event","type_":1,"time_":1502096107556,"tz_":"+0000","pid_":4204,"tid_":4223,"int_data":100,"str_data":"strValue"}
```
5. On the application UI, touch button 3 to remove the event watcher. Then, touch button 1 for multiple times to perform application event logging. In such a case, there will be no log information about the callback invoked by the event watcher.
## Samples
The following sample is provided to help you better understand how to develop the application event logging feature:
- [`JsDotTest` (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest)
......@@ -2,10 +2,10 @@
HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application.
The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data.
The HiAppEvent module can be used to develop application event-related functions, including flushing application events to a disk and querying historical application events.
## Basic Concepts
- **Logging**
**Logging**
Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
A function that logs changes caused by user operations to provide service data for development, product, and O&M analysis.
\ No newline at end of file
# Guide to Switching to Full SDK
Both the public SDK and full SDK are toolkits for application development.
The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications.
Both the public SDK and full SDK are toolkits for application development. <br>The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications.
The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs.
The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps.
## Downloading the Full SDK (of 3.1.1 Release in this example)
Manually download the full SDK. For details, see the source code acquisition section in [OpenHarmony 3.1.1 Release](https://gitee.com/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.1.1-release.md).
![image-20220613161049897](figures/en-us_image_0000001655128646.png)
> **NOTE**
>
> The screenshots in this document are for reference only.
## Downloading the Full SDK
Manually download the system-specific full SDK package from the mirror. For details, see [Release Notes](../../release-notes/OpenHarmony-v3.2-beta2.md).
## Checking the Local SDK Location
## Checking the Local SDK Location<br>In this example, an eTS project is used. For a JS project, replace **ets** with **js**.
In this example, an eTS project is used. For a JS project, replace **ets** with **js**.
In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK.
......@@ -38,61 +37,58 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo
Note: The criteria for identifying system APIs are subject to the released API documentation.
2. Replace the SDK. The following uses full SDK 3.1.6.6 for Windows as an example.
2. Replace the SDK. The following uses public-SDK-3.x.x.x for Windows as an example.
a. Decompress the downloaded full SDK file: `ets-windows-3.1.6.5-Release.zip`
a. Decompress the downloaded full SDK file: `ets-windows-3.x.x.x-Release.zip`
![image-20220613165018184](figures/en-us_image_0000001655129264.png)
b. Replace the SDK files.
Back up the local SDK files. (Copy and rename the version number directory in the **ets** directory, or copy the entire **ets** directory to another local path.)
Back up the local SDK files. (Copy and rename the version directory in the **ets** directory, or copy the entire **ets** directory to another local path.)
Go to the obtained location of the local installed SDK and back up the files therein.
![image-20220613161352157](figures/en-us_image_0000001655129041.png)
Note: The name of the backup version number directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version number directory is **3.1.6.6_backup**.
Note: The name of the backup version directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version directory is **3.x.x.x_backup**.
![image-20220613165018184](figures/en-us_image_0000001655129398.png)
The configuration in the **oh-uni-package.json** file is as follows:
The configuration in the **oh-uni-package.json** file is as follows, where the value of `apiVersion` is subject to the API version of the SDK, and the value of `version` is subject to the version number in the SDK file.
```
{
"apiVersion": "8",
"apiVersion": "X",
"displayName": "Ets",
"meta": {
"metaVersion": "3.0.0"
},
"path": "ets",
"releaseType": "Release",
"version": "3.1.6.6"
"version": "3.x.x.x"
}
```
**Delete all files in the original SDK (3.1.6.6) directory.** Failure to do so may result in some files being unable to be overwritten.
Delete all files in the original SDK (3.x.x.x) directory. Failure to do so may result in some files being unable to be overwritten.
Copy the full SDK to the location of the local SDK.
Copy all files in the **ets** directory in the full SDK to the **ets\3.1.6.6** directory in the location of the local SDK.
Copy all files in the **ets** directory in the full SDK to the **ets\*3.x.x.x*** directory in the location of the local SDK.
Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number.
In the **3.1.6.6\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package.
In the ***3.x.x.x*\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the `npm install` command to download the **node_modules** dependency package.
![image-20220613171111405](figures/en-us_image_0000001655129333.png)
c. Check for system APIs.
![image-20220613213038104](figures/en-us_image_0000001655129372.png)
......@@ -216,6 +216,7 @@
- [@ohos.pasteboard](js-apis-pasteboard.md)
- [@ohos.screenLock](js-apis-screen-lock.md)
- [@ohos.systemTime](js-apis-system-time.md)
- [@ohos.systemTimer](js-apis-system-timer.md)
- [@ohos.wallpaper](js-apis-wallpaper.md)
- [Timer](js-apis-timer.md)
......
......@@ -89,9 +89,9 @@ Enumerates the device states.
| Name | Default Value | Description |
| ------- | ---- | --------------- |
| ONLINE | 0 | The device is online. |
| READY | 1 | The device is ready, and the device information has been synchronized.|
| OFFLINE | 2 | The device is offline. |
| ONLINE | 0 | The device is physically online. |
| READY | 1 | The information between devices has been synchronized in the Distributed Data Service (DDS) module, and the device is ready for running distributed services.|
| OFFLINE | 2 | The device is physically offline. |
| CHANGE | 3 | The device information is changed. |
## SubscribeInfo
......
# Performance Tracing
This module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis.
The Performance Tracing module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> **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.
......@@ -17,7 +18,7 @@ import hiTraceMeter from '@ohos.hiTraceMeter';
startTrace(name: string, taskId: number): void
Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace.
Starts a trace task.
If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**.
......
......@@ -676,7 +676,7 @@ Formats a phone number.
### getLocationName<sup>9+</sup>
static getLocationName(number: string, locale: string): string
getLocationName(number: string, locale: string): string
Obtains the home location of a phone number.
......
......@@ -389,7 +389,7 @@ promise.then(data => {
isNrSupported\(slotId: number\): boolean
Checks whether the current device supports 5G \(NR\).
Checks whether the current device supports 5G \(NR\) for the SIM card in the specified slot.
**System capability**: SystemCapability.Telephony.CoreService
......@@ -470,7 +470,7 @@ radio.isRadioOn(slotId, (err, data) => {
isRadioOn\(slotId?: number\): Promise<boolean\>
Checks whether the radio service is enabled. This API uses a promise to return the result.
Checks whether the radio service is enabled on the SIM card in the specified slot. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
......@@ -505,7 +505,7 @@ promise.then(data => {
getOperatorName\(slotId: number, callback: AsyncCallback<string\>\): void
Obtains the carrier name. This API uses an asynchronous callback to return the result.
Obtains the carrier name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Telephony.CoreService
......@@ -530,7 +530,7 @@ radio.getOperatorName(slotId, (err, data) => {
getOperatorName\(slotId: number\): Promise<string\>
Obtains the carrier name. This API uses a promise to return the result.
Obtains the carrier name for the SIM card in the specified slot. This API uses a promise to return the result.
**System capability**: SystemCapability.Telephony.CoreService
......@@ -905,7 +905,29 @@ sendUpdateCellLocationRequest\(callback: AsyncCallback<void\>\): void
Sends a cell location update request. This API uses an asynchronous callback to return the result.
This is a system API.
**System capability**: SystemCapability.Telephony.CoreService
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------- |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
```js
radio.sendUpdateCellLocationRequest((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## radio.sendUpdateCellLocationRequest<sup>8+</sup>
sendUpdateCellLocationRequest\(slotId: number, callback: AsyncCallback<void\>\): void
Sends a cell location update request for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......@@ -915,26 +937,34 @@ This is a system API.
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------- |
| slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
```js
radio.sendUpdateCellLocationRequest((err, data) => {
let slotId = 0;
radio.sendUpdateCellLocationRequest(slotId, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## radio.sendUpdateCellLocationRequest<sup>8+</sup>
sendUpdateCellLocationRequest\(\): Promise<void\>
sendUpdateCellLocationRequest\(slotId?: number): Promise<void\>
Sends a cell location update request. This API uses a promise to return the result.
Sends a cell location update request for the SIM card in the specified slot.This API uses a promise to return the result.
This is a system API.
**System capability**: SystemCapability.Telephony.CoreService
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------------------- |
| slotId | number | No | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2|
**Return value**
| Type | Description |
......@@ -944,7 +974,8 @@ This is a system API.
**Example**
```js
let promise = radio.sendUpdateCellLocationRequest();
let slotId = 0;
let promise = radio.sendUpdateCellLocationRequest(slotId);
promise.then(data => {
console.log(`sendUpdateCellLocationRequest success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
......@@ -983,7 +1014,7 @@ radio.getCellInformation((err, data) => {
getCellInformation(slotId: number, callback: AsyncCallback<Array<CellInformation\>\>): void
Obtains cell information. This API uses an asynchronous callback to return the result.
Obtains cell information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......@@ -1012,7 +1043,7 @@ radio.getCellInformation(slotId, (err, data) => {
getCellInformation(slotId?: number): Promise<Array<CellInformation\>\>
Obtains cell information. This API uses a promise to return the result.
Obtains cell information for the SIM card in the specified slot. This API uses a promise to return the result.
This is a system API.
......@@ -1134,7 +1165,7 @@ promise.then(data => {
getNetworkSearchInformation\(slotId: number, callback: AsyncCallback<NetworkSearchResult\>\): void
Obtains network search information. This API uses an asynchronous callback to return the result.
Obtains network search information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......@@ -1161,7 +1192,7 @@ radio.getNetworkSearchInformation(0, (err, data) => {
getNetworkSearchInformation\(slotId: number\): Promise<void\>
Obtains network search information. This API uses a promise to return the result.
Obtains network search information for the SIM card in the specified slot. This API uses a promise to return the result.
This is a system API.
......@@ -1221,7 +1252,7 @@ radio.getNrOptionMode((err, data) => {
getNrOptionMode(slotId: number, callback: AsyncCallback<NrOptionMode\>): void
Obtains the NR option mode. This API uses an asynchronous callback to return the result.
Obtains the NR option mode for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......@@ -1248,7 +1279,7 @@ radio.getNrOptionMode(slotId, (err, data) => {
getNrOptionMode(slotId?: number): Promise<NrOptionMode\>
Obtains the NR option mode. This API uses a promise to return the result.
Obtains the NR option mode for the SIM card in the specified slot. This API uses a promise to return the result.
This is a system API.
......@@ -1466,7 +1497,7 @@ promise.then(data => {
setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback: AsyncCallback<void\>\): void
Sets the preferred network. This API uses an asynchronous callback to return the result.
Sets the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......@@ -1494,7 +1525,7 @@ radio.setPreferredNetwork(0, 1, (err, data) => {
setPreferredNetwork(slotId: number, networkMode: PreferredNetworkMode): Promise<void\>
Sets the preferred network. This API uses a promise to return the result.
Sets the preferred network for the SIM card in the specified slot. This API uses a promise to return the result.
This is a system API.
......@@ -1530,7 +1561,7 @@ promise.then(data => {
getPreferredNetwork\(slotId: number, callback: AsyncCallback<PreferredNetworkMode\>\): void
Obtains the preferred network. This API uses an asynchronous callback to return the result.
Obtains the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......@@ -1557,7 +1588,7 @@ radio.getPreferredNetwork(0, (err, data) => {
getPreferredNetwork(slotId: number): Promise<void\>
Obtains the preferred network. This API uses a promise to return the result.
Obtains the preferred network for the SIM card in the specified slot. This API uses a promise to return the result.
This is a system API.
......@@ -1592,7 +1623,7 @@ promise.then(data => {
getImsRegInfo(slotId: number, imsType: ImsServiceType, callback: AsyncCallback<ImsRegInfo\>): void
Obtains the IMS registration status of the specified IMS service type. This API uses an asynchronous callback to return the result.
Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......@@ -1620,7 +1651,7 @@ radio.getImsRegInfo(0, 1, (err, data) => {
getImsRegInfo(slotId: number, imsType: ImsServiceType): Promise<ImsRegInfo\>
Obtains the IMS registration status of the specified IMS service type. This API uses a promise to return the result.
Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses a promise to return the result.
This is a system API.
......@@ -1656,7 +1687,7 @@ promise.then(data => {
on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Callback<ImsRegInfo\>): void
Enables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result.
Enables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......@@ -1685,7 +1716,7 @@ radio.on('imsRegStateChange', 0, 1, (err, data) => {
off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback?: Callback<ImsRegInfo\>): void
Disables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result.
Disables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result.
This is a system API.
......
# Setting the System Time
# System Time and Time Zone
This module provides the time, time zone, and timing services. Use the time and time zone services to set and obtain the system time and time zone, and use the timing service to manage and use the system time and time zone to implement alarms or other timing functions.
> **NOTE**<br>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone.
> **NOTE**
>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>- The APIs of this module are system APIs and cannot be called by third-party applications.
## Modules to Import
......@@ -25,15 +26,15 @@ Sets the system time. This API uses an asynchronous callback to return the resul
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| time | number | Yes| Timestamp to set, in milliseconds.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to process the received return value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------ |
| time | number | Yes | Timestamp to set, in milliseconds. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```js
// Set the system time to 2021-01-20 02:36:25.
// Set the system time to 2021-01-20 02:36:25.
var time = 1611081385000;
systemTime.setTime(time, (error, data) => {
if (error) {
......@@ -57,26 +58,26 @@ Sets the system time. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| time | number | Yes| Timestamp to set, in milliseconds.|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| time | number | Yes | Timestamp to set, in milliseconds. |
**Return value**
| Type| Description|
| -------- | -------- |
| Type | Description |
| ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
// Set the system time to 2021-01-20 02:36:25.
var time = 1611081385000;
systemTime.setTime(time).then((data) => {
console.log(`systemTime.setTime success data : ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to systemTime.setTime because ` + JSON.stringify(error));
});
// Set the system time to 2021-01-20 02:36:25.
var time = 1611081385000;
systemTime.setTime(time).then((data) => {
console.log(`systemTime.setTime success data : ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to systemTime.setTime because ` + JSON.stringify(error));
});
```
......@@ -90,10 +91,10 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the time.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time. |
**Example**
......@@ -118,14 +119,14 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.|
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds. |
**Return value**
| Type| Description|
| -------- | -------- |
| Type | Description |
| --------------------- | ------------------------------------------------------------ |
| Promise&lt;number&gt; | Promise used to return the time.|
**Example**
......@@ -149,10 +150,10 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the time.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time.|
**Example**
......@@ -177,14 +178,14 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.|
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds. |
**Return value**
| Type| Description|
| -------- | -------- |
| Type | Description |
| --------------------- | ------------------------------------------------------------ |
| Promise&lt;number&gt; | Promise used to return the time.|
**Example**
......@@ -208,10 +209,10 @@ Obtains the time elapsed since system start, including the deep sleep time. This
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the time.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time. |
**Example**
......@@ -236,14 +237,14 @@ Obtains the time elapsed since system start, including the deep sleep time. This
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.|
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds. |
**Return value**
| Type| Description|
| -------- | -------- |
| Type | Description |
| --------------------- | ------------------------------------------------------------ |
| Promise&lt;number&gt; | Promise used to return the time.|
**Example**
......@@ -269,10 +270,10 @@ Sets the system date. This API uses an asynchronous callback to return the resul
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| date | Date | Yes| Target date to set.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to process the received return value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------ |
| date | Date | Yes | Target date to set. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
......@@ -300,14 +301,14 @@ Sets the system date. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| date | Date | Yes| Target date to set.|
| Name| Type| Mandatory| Description |
| ------ | ---- | ---- | ---------- |
| date | Date | Yes | Target date to set.|
**Return value**
| Type| Description|
| -------- | -------- |
| Type | Description |
| ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
......@@ -332,9 +333,9 @@ Obtains the current system date. This API uses an asynchronous callback to retur
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Date&gt; | Yes| Callback used to return the current system date.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------------------------- |
| callback | AsyncCallback&lt;Date&gt; | Yes | Callback used to return the current system date.|
**Example**
......@@ -359,8 +360,8 @@ Obtains the current system date. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Type | Description |
| ------------------- | ----------------------------------------- |
| Promise&lt;Date&gt; | Promise used to return the current system date.|
**Example**
......@@ -386,10 +387,10 @@ Sets the system time zone. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| timezone | string | Yes| System time zone to set.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to process the received return value.|
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------ |
| timezone | string | Yes | System time zone to set. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
......@@ -416,14 +417,14 @@ Sets the system time zone. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| timezone | string | Yes| System time zone to set.|
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ---------- |
| timezone | string | Yes | System time zone to set.|
**Return value**
| Type| Description|
| -------- | -------- |
| Type | Description |
| ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
......@@ -447,9 +448,9 @@ Obtains the system time zone. This API uses an asynchronous callback to return t
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the system time zone.|
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------ |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the system time zone.|
**Example**
......@@ -474,8 +475,8 @@ Obtains the system time zone. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Type | Description |
| --------------------- | ------------------------------------- |
| Promise&lt;string&gt; | Promise used to return the system time zone.|
**Example**
......
# System Timer
The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services.
> **NOTE**<br/>
>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>- The APIs of this module are system APIs and cannot be called by third-party applications.
## Modules to Import
```
import systemTimer from '@ohos.systemTimer';
```
## systemTime.createTimer
createTimer(options: TimerOptions, callback: AsyncCallback&lt;number&gt;): void
Creates a timer. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.Time
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- |
| options | TimerOptions | Yes | Timer options.<br>**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.<br>**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.<br>**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.<br>**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).|
| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. |
| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. |
| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) |
**Return value**
| Type | Description |
| ------------------------- | ------------------------------------------------------------ |
| syncCallback&lt;number&gt;| Callback used to return the timer ID. |
**Example**
```js
export default {
systemTimer () {
var options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat: false
}
systemTimer.createTimer(options, (error, data) => {
if (error) {
console.error(`failed to systemTime.createTimer ` + JSON.stringify(error));
return;
}
console.log(`systemTime.createTimer success data : ` + JSON.stringify(data));
});
}
}
```
## systemTime.createTimer
createTimer(options: TimerOptions): Promise&lt;number&gt;
Creates a timer. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.Time
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- |
| options | TimerOptions | Yes | Timer options.<br>**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.<br>**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.<br>**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.<br>**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).|
| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. |
| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. |
| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) |
**Return value**
| Type | Description |
| --------------------- | ------------------------------------------------------------ |
| Promise&lt;number&gt; | Promise used to return the timer ID. |
**Example**
```js
export default {
systemTimer () {
var options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
systemTimer.createTimer(options).then((data) => {
console.log(`systemTime.createTimer success data : ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to systemTime.createTimer because ` + JSON.stringify(error));
});
}
}
```
## systemTime.startTimer
startTimer(timer: number, triggerTime: number, callback: AsyncCallback&lt;void&gt;): void
Starts a timer. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.Time
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | --------------------------- | ---- | ------------------------------------------------------------ |
| timer | number | Yes | ID of the timer. |
| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. |
**Example**
```js
export default {
systemTimer () {
var options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = systemTimer.Timer(options)
systemTimer.startTimer(timerId, 10000, (error, data) => {
if (error) {
console.error(`failed to systemTime.startTimer ` + JSON.stringify(error));
return;
}
console.log(`systemTime.startTimer success data : ` + JSON.stringify(data));
});
}
}
```
## systemTime.startTimer
startTimer(timer: number, triggerTime: number): Promise&lt;void&gt;
Starts a timer. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.Time
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | --------------------------- | ---- | ------------------------------------------------------------ |
| timer | number | Yes | ID of the timer. |
| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. |
**Example**
```js
export default {
systemTimer (){
var options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = systemTimer.Timer(options)
systemTimer.startTimer(timerId, 10000).then((data) => {
console.log(`systemTime.startTimer success data : ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error));
});
}
}
```
## systemTime.stopTimer
stopTimer(timer: number, callback: AsyncCallback&lt;void&gt;): void
Stops a timer. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.Time
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| timer | number | Yes | ID of the timer. |
**Example**
```js
export default {
systemTimer () {
var options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = systemTimer.Timer(options)
systemTimer.startTimer(timerId, 100000)
systemTimer.stoptTimer(timerId, 10000, (error, data) => {
if (error) {
console.error(`failed to systemTime.startTimer ` + JSON.stringify(error));
return;
}
console.log(`systemTime.startTimer success data : ` + JSON.stringify(data));
});
}
}
```
## systemTime.stopTimer
stopTimer(timer: number): Promise&lt;void&gt;
Stops a timer. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.Time
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| timer | number | Yes | ID of the timer. |
**Example**
```js
export default {
systemTimer (){
var options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = systemTimer.Timer(options)
systemTimer.startTimer(timerId, 100000)
systemTimer.stoptTimer(timerId, 10000).then((data) => {
console.log(`systemTime.startTimer success data : ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error));
});
}
}
```
## systemTime.destroyTimer
destroyTimer(timer: number, callback: AsyncCallback&lt;void&gt;): void
Destroys a timer. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.Time
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| timer | number | Yes | ID of the timer. |
**Example**
```js
export default {
systemTimer () {
var options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = systemTimer.Timer(options)
systemTimer.startTimer(timerId, 100000)
systemTimer.stopTimer(timerId)
systemTimer.destroyTimer(timerId, (error, data) => {
if (error) {
console.error(`failed to systemTime.startTimer ` + JSON.stringify(error));
return;
}
console.log(`systemTime.startTimer success data : ` + JSON.stringify(data));
});
}
}
```
## systemTime.destroyTimer
destroyTimer(timer: number): Promise&lt;void&gt;
Destroys a timer. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.Time
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------------------------------------ |
| timer | number | Yes | ID of the timer. |
**Example**
```js
export default {
systemTimer (){
var options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = systemTimer.Timer(options)
systemTimer.startTimer(timerId, 100000)
systemTimer.stopTimer(timerId)
systemTimer.destroytTimer(timerId, 10000).then((data) => {
console.log(`systemTime.startTimer success data : ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error));
});
}
}
```
......@@ -32,16 +32,17 @@ Text(content?: string)
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| textAlign | [TextAlign](ts-appendix-enums.md) | TextAlign.Start | Text alignment mode of multiple lines of text.|
| textOverflow | {overflow:&nbsp;[TextOverflow](ts-appendix-enums.md)} | {overflow:&nbsp;TextOverflow.Clip} | Display mode when the text is too long.<br>**NOTE**<br/><br>Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.<br>This attribute must be used with `maxLines` to take effect.|
| maxLines | number | Infinity | Maximum number of lines in the text.<br>**NOTE**<br/><br>By default, text is automatically folded. If this parameter is specified, the text does not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode.|
| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md)} | {overflow: TextOverflow.Clip} | Display mode when the text is too long.<br>**NOTE**<br/>Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.<br>This attribute must be used with `maxLines` to take effect. |
| maxLines | number | Infinity | Maximum number of lines in the text.<br>**NOTE**<br/>By default, text is automatically folded. If this parameter is specified, the text does not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode. |
| lineHeight | Length | - | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.|
| decoration | {<br>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br>color?:&nbsp;Color<br>} | {<br>type:&nbsp;TextDecorationType.None,<br>color: Color.Black<br>} | Style and color of the text decorative line.|
| decoration | {<br>type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br>color?: Color<br>} | {<br>type: TextDecorationType.None,<br>color: Color.Black<br>} | Style and color of the text decorative line.|
| baselineOffset | Length | - | Offset of the text baseline.|
| textCase | [TextCase](ts-appendix-enums.md#textcase) | TextCase.Normal | Text case.|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md) | CopyOptions.None | Whether copy and paste is allowed.|
> **NOTE**<br/>
> The **\<Text>** component cannot contain both the text and the child component **\<Span>**. If both of them exist, only the content in **\<Span>** is displayed.
> **NOTE**
>
> The **\<Text>** component cannot contain both the text and the child component **\<Span>**. If both of them exist, only the content in **\<Span>** is displayed.
## Example
......
# Video
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Video>** component is used to play a video and control its playback.
The **\<Video>** component provides a video player.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
To use online videos, you need to add the **ohos.permission.INTERNET** permission to the corresponding **abilities** in the **config.json** or **module.json** file, whichever is appropriate.
```
```js
"abilities":[
{
...
......@@ -20,55 +20,58 @@ To use online videos, you need to add the **ohos.permission.INTERNET** permissio
]
```
## Child Components
Not supported
## APIs
Video(value: VideoOptions)
- VideoOptions attributes
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| src | string \| [Resource](../../ui/ts-types.md) | No| - | Path of the video source, which can be a local path or a URL.<br>The video resources can be stored in the **video** or **rawfile** folder under **resources**.<br>The path can include a **dataability://** prefix, which is used to access the video path provided by a Data ability. For details about the path, see [Data Ability Development](../../ability/fa-dataability.md).|
| currentProgressRate | number \| PlaybackSpeed<sup>8+</sup> | No| 1.0 \| PlaybackSpeed.<br>Speed_Forward_1_00_X | Video playback speed.<br>**NOTE**<br>The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**. |
| previewUri | string \| PixelMap<sup>8+</sup> \| [Resource](../../ui/ts-types.md) | No| - | Path of the preview image.|
| controller | [VideoController](#videocontroller) | No| - | Controller.|
| Name | Type | Mandatory | Default Value | Description |
| ------------------- | ---------------------------------------- | ---- | ---------------------------------------- | ---------------------------------------- |
| src | string \| [Resource](../../ui/ts-types.md) | No | - | Path of the video source, which can be a local path or a URL.<br>The video resources can be stored in the **video** or **rawfile** folder under **resources**.<br>The path can include a **dataability://** prefix, which is used to access the video path provided by a Data ability. For details about the path, see [Data Ability Development](../../ability/fa-dataability.md).|
| currentProgressRate | number \| string \| PlaybackSpeed<sup>8+</sup> | No | 1.0 \| PlaybackSpeed.<br>Speed_Forward_1_00_X | Video playback speed.<br>> **NOTE**<br>> The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**. |
| previewUri | string \| PixelMap<sup>8+</sup> \| [Resource](../../ui/ts-types.md) | No | - | Path of the preview image. |
| controller | [VideoController](#videocontroller) | No | - | Controller. |
- PlaybackSpeed<sup>8+</sup>
| Name | Description |
| -------------------- | --------------------- |
| Speed_Forward_0_75_X | 0.75x playback speed. |
| Speed_Forward_1_00_X | 1x playback speed. |
| Speed_Forward_1_25_X | 1.25x playback speed. |
| Speed_Forward_1_75_X | 1.75x playback speed. |
| Speed_Forward_2_00_X | 2x playback speed. |
| Name | Description |
| -------------------- | --------- |
| Speed_Forward_0_75_X | 0.75x playback speed.|
| Speed_Forward_1_00_X | 1x playback speed. |
| Speed_Forward_1_25_X | 1.25x playback speed.|
| Speed_Forward_1_75_X | 1.75x playback speed.|
| Speed_Forward_2_00_X | 2x playback speed. |
## Attributes
| Name | Type | Default Value | Description |
| --------- | ---------------------------------------- | ------------- | -------------------------------------------------- |
| muted | boolean | false | Whether the video is muted. |
| autoPlay | boolean | false | Whether to enable auto play. |
| controls | boolean | true | Whether to display the video playback control bar. |
| objectFit | [ImageFit](ts-basic-components-image.md) | Cover | Video scale type. |
| loop | boolean | false | Whether to repeat the video. |
| Name | Type | Default Value | Description |
| --------- | ---------------------------------------- | ----- | --------------- |
| muted | boolean | false | Whether to mute the video. |
| autoPlay | boolean | false | Whether to enable auto play. |
| controls | boolean | true | Whether to display the video playback control bar.|
| objectFit | [ImageFit](ts-basic-components-image.md) | Cover | Video scale type. |
| loop | boolean | false | Whether to repeat the video. |
## Events
| Name| Description|
| -------- | -------- |
| onStart() =&gt; void | Triggered when the video is played.|
| onPause() =&gt; void | Triggered when the video playback is paused.|
| onFinish() =&gt; void | Triggered when the video playback is finished.|
| onError() =&gt; void | Triggered when the video playback fails.|
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onStart() =&gt; void | Triggered when the video is played. |
| onPause() =&gt; void | Triggered when the video playback is paused. |
| onFinish() =&gt; void | Triggered when the video playback is finished. |
| onError() =&gt; void | Triggered when the video playback fails. |
| onPrepared(event?: { duration: number }) =&gt; void | Triggered when video preparation is complete. The video duration (in seconds) is obtained from **duration**.|
| onSeeking(event?: { time: number }) =&gt; void | Triggered to report the time (in seconds) when the progress bar is being dragged.|
| onSeeked(event?: { time: number }) =&gt; void | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar.|
| onUpdate(event?: { time: number }) =&gt; void | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second.|
| onSeeking(event?: { time: number }) =&gt; void | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| onSeeked(event?: { time: number }) =&gt; void | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. |
| onUpdate(event?: { time: number }) =&gt; void | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
## VideoController
......@@ -78,7 +81,7 @@ A **VideoController** object can control one or more videos.
### Objects to Import
```
```ts
controller: VideoController = new VideoController();
```
......@@ -107,11 +110,10 @@ setCurrentTime(value: number)
Sets the video playback position.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | --------- | ------------- | ------------------------ |
| value | number | Yes | - | Video playback position. |
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | --------- |
| value | number | Yes | - | Video playback position.|
### requestFullscreen
......@@ -119,11 +121,10 @@ requestFullscreen(value: boolean)
Requests full-screen mode.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | --------- | ------------- | -------------------------------------------- |
| value | boolean | Yes | false | Whether the playback is in full-screen mode. |
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ----- | ------- |
| value | boolean | Yes | false | Whether the playback is in full-screen mode.|
### exitFullscreen
......@@ -137,20 +138,21 @@ setCurrentTime(value: number, seekMode: SeekMode)
Sets the video playback position with the specified seek mode.
**Parameters**
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | ---- | ---- | --------- |
| value | number | Yes | - | Video playback position.|
| seekMode | SeekMode | Yes | - | Seek mode. |
- SeekMode<sup>8+</sup>
| Name | Description |
| ---------------- | -------------- |
| PreviousKeyframe | Seeks to the nearest previous keyframe. |
| NextKeyframe | Seeks to the nearest next keyframe. |
| ClosestKeyframe | Seeks to the nearest keyframe. |
| Accurate | Seeks to a specific frame, regardless of whether the frame is a keyframe.|
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | --------- | ------------- | ----------------------- |
| value | number | Yes | - | Video playback position. |
| seekMode | SeekMode | Yes | - | Seek mode. |
SeekMode<sup>8+</sup>
| Name | Description |
| ---------------- | ------------------------------------------------------------------------- |
| PreviousKeyframe | Seeks to the nearest previous keyframe. |
| NextKeyframe | Seeks to the nearest next keyframe. |
| ClosestKeyframe | Seeks to the nearest keyframe. |
| Accurate | Seeks to a specific frame, regardless of whether the frame is a keyframe. |
## Example
......@@ -165,6 +167,7 @@ struct VideoCreateComponent {
@State autoPlays: boolean = false;
@State controlsss: boolean = true;
controller: VideoController = new VideoController();
build() {
Column() {
Video({
......@@ -231,4 +234,4 @@ struct VideoCreateComponent {
}
}
}
```
\ No newline at end of file
```
# Security
- Access Control
- [Access Control Overview](accesstoken-overview.md)
- [Access Control Development](accesstoken-guidelines.md)
- [Permission List](permission-list.md)
- [Access Control (Permission) Overview](accesstoken-overview.md)
- [Access Control (Permission) Development](accesstoken-guidelines.md)
- [Application Permission List](permission-list.md)
- User Authentication
- [User Authentication Overview](userauth-overview.md)
- [User Authentication Development](userauth-guidelines.md)
......
# Access Control Development
# Access Control (Permission) Development
## When to Use
......@@ -8,7 +8,7 @@ In this example, the app requires the **ohos.permission.PERMISSION1** and **ohos
- The level of **ohos.permission.PERMISSION1** is **normal**, and the authorization mode is **system_grant**.
- The level of **ohos.permission.PERMISSION2** is **system_basic**, and the authorization mode is **user_grant**.
> **NOTICE**
> **CAUTION**
>
> In this scenario, the required permissions include a **user_grant** permission. You can check whether the caller has the required permission through permission verification.
>
......@@ -28,48 +28,49 @@ Declare the permissions required by the app one by one in the project configurat
Note that the app bundle structure and configuration file vary with the ability framework model.
### FA Model
For the apps based on the FA model, declare the required permissions in the **config.json** file.
**Description of config.json**
The following table describes the tags in the configuration file.
| Field | Description |
| --------- | ------------------------------------------------------------ |
| name | Name of the permission. |
| reason | Reason for requesting the permission. This field is mandatory for a user_grant permission.|
| usedScene | Scenario of the permission. This field is mandatory for a user_grant permission.|
| abilities | Abilities that use the permission. The value is an array.|
| ability | Abilities that use the permission. The value is an array.<br>**Applicable model**: FA |
| abilities | Abilities that use the permission. The value is an array.<br>**Applicable model**: stage |
| when | Time when the permission is used. The value can be **inuse** (the permission can be used only in the foreground) or **always** (the permission can be used in foreground and background).|
### FA Model
For the apps based on the FA model, declare the required permissions in the **config.json** file.
**Example**
```json
{
"module" : {
"reqPermissions":[
{
"name" : "ohos.permission.PERMISSION1",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"inuse"
}
},
{
"name" : "ohos.permission.PERMISSION2",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"always"
}
}
],
}
"module" : {
"reqPermissions":[
{
"name" : "ohos.permission.PERMISSION1",
"reason": "$string:reason",
"usedScene": {
"ability": [
"FormAbility"
],
"when":"inuse"
}
},
{
"name" : "ohos.permission.PERMISSION2",
"reason": "$string:reason",
"usedScene": {
"ability": [
"FormAbility"
],
"when":"always"
}
}
]
}
}
```
......@@ -81,30 +82,30 @@ For the apps based on the stage model, declare the required permissions in the *
```json
{
"module" : {
"requestPermissions":[
{
"name" : "ohos.permission.PERMISSION1",
"reason": "$string:reason",
"usedScene": {
"module" : {
"requestPermissions":[
{
"name" : "ohos.permission.PERMISSION1",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"inuse"
}
},
{
"name" : "ohos.permission.PERMISSION2",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"always"
}
}
],
}
}
},
{
"name" : "ohos.permission.PERMISSION2",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"always"
}
}
]
}
}
```
......@@ -112,34 +113,17 @@ For the apps based on the stage model, declare the required permissions in the *
The permission level of **ohos.permission.PERMISSION2** is **system_basic**, which is higher than the app's APL. In this case, use the ACL.
In addition to declaring all the permissions in the configuration file, you must declare the permissions whose levels are higher than the app's APL in the app's [profile](../quick-start/app-provision-structure.md). In this example, declare the permission under the **acls** field:
In addition to declaring all the permissions in the configuration file, you must declare the permissions whose levels are higher that the app's APL in the app's profile. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md).
In this example, declare the permission under the **acls** field:
```json
{
"version-name": "1.0.0",
"version-code": 1,
"app-distribution-type": "os_integration",
"uuid": "5027b99e-5f9e-465d-9508-a9e0134ffe18",
"validity": {
"not-before": 1594865258,
"not-after": 1689473258
},
"type": "release",
"bundle-info": {
"developer-id": "OpenHarmony",
"distribution-certificate": "-----BEGIN CERTIFICATE-----\nMIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO\nMRQwEgYDVQQKEwtPcGVuSGFybW9ueTEZMBcGA1UECxMQT3Blbkhhcm1vbnkgVGVh\nbTEjMCEGA1UEAxMaT3Blbkhhcm1vbnkgQXBwbGljYXRpb24gQ0EwHhcNMjEwMjAy\nMTIxOTMxWhcNNDkxMjMxMTIxOTMxWjBoMQswCQYDVQQGEwJDTjEUMBIGA1UEChML\nT3Blbkhhcm1vbnkxGTAXBgNVBAsTEE9wZW5IYXJtb255IFRlYW0xKDAmBgNVBAMT\nH09wZW5IYXJtb255IEFwcGxpY2F0aW9uIFJlbGVhc2UwWTATBgcqhkjOPQIBBggq\nhkjOPQMBBwNCAATbYOCQQpW5fdkYHN45v0X3AHax12jPBdEDosFRIZ1eXmxOYzSG\nJwMfsHhUU90E8lI0TXYZnNmgM1sovubeQqATo1IwUDAfBgNVHSMEGDAWgBTbhrci\nFtULoUu33SV7ufEFfaItRzAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFPtxruhl\ncRBQsJdwcZqLu9oNUVgaMAwGCCqGSM49BAMDBQADaAAwZQIxAJta0PQ2p4DIu/ps\nLMdLCDgQ5UH1l0B4PGhBlMgdi2zf8nk9spazEQI/0XNwpft8QAIwHSuA2WelVi/o\nzAlF08DnbJrOOtOnQq5wHOPlDYB4OtUzOYJk9scotrEnJxJzGsh/\n-----END CERTIFICATE-----\n",
"bundle-name": "com.ohos.permissionmanager",
"apl": "system_core",
"app-feature": "hos_system_app"
},
"acls": {
"allowed-acls": [
"ohos.permission.PERMISSION2"
]
},
"permissions": {
"restricted-permissions": []
},
"issuer": "pki_internal"
"acls": {
"allowed-acls": [
"ohos.permission.PERMISSION2"
]
},
}
```
......@@ -151,7 +135,7 @@ Therefore, before allowing the app to call the API protected by the **ohos.permi
If the verification result indicates that the app has the permission, the app can access the target API. Otherwise, the app needs to request user authorization and then proceeds based on the authorization result. For details, see [Access Control Overview](accesstoken-overview.md).
> **Precautions**
> **CAUTION**
>
> The permissions authorized by user are not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to an app, the app's permission must be verified before the app calls an API protected by the permission.
......@@ -170,12 +154,12 @@ The procedure is as follows:
let array:Array<string> = ["ohos.permission.PERMISSION2"];
// requestPermissionsFromUser determines whether to invoke a pop-up window based on the permission authorization status.
context.requestPermissionsFromUser(array).then(function(data) {
console.log("data type:" + typeof(data));
console.log("data:" + data);
console.log("data permissions:" + data.permissions);
console.log("data result:" + data.authResults);
console.log("data type:" + typeof(data));
console.log("data:" + data);
console.log("data permissions:" + data.permissions);
console.log("data result:" + data.authResults);
}, (err) => {
console.error('Failed to start ability', err.code);
console.error('Failed to start ability', err.code);
});
}
......
# Access Control Overview
# Access Control (Permission) Overview
AccessTokenManager (ATM) implements unified app permission management based on access tokens on OpenHarmony.
......@@ -108,7 +108,7 @@ The permissions open to apps vary with the permission level. The permission leve
The system_core permission allows access to core resources of the operating system. These resources are the underlying core services of the system. If these resources are corrupted, the OS cannot run properly.
The permissions of this type are not open to any app currently.
The permissions of this type are not open to third-party apps currently.
## Permission Authorization Modes
......
......@@ -65,7 +65,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -keyAlias # Key alias. It is mandatory.
├── -keyPwd # Key password. It is optional.
├── -subject # Certificate subject. It is mandatory.
├── -signAlg # Signature algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory.
├── -signAlg # Signing algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory.
├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory.
├── -keystorePwd # KS password. It is optional.
├── -outFile # CSR to generate. It is optional. If you do not specify this parameter, the CSR is output to the console.
......@@ -84,7 +84,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -issuerKeyPwd # Key password of the issuer. It is optional.
├── -subject # Certificate subject. It is mandatory.
├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days.
├── -signAlg # Signature algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory.
├── -signAlg # Signing algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory.
├── -basicConstraintsPathLen # Path length. It is optional. The default value is 0.
├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory.
├── -keystorePwd # KS password. It is optional.
......@@ -104,7 +104,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -issuerKeyPwd # Key password of the issuer. It is optional.
├── -subject # Certificate subject. It is mandatory.
├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days.
├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA.
├── -signAlg # Signing algorithm, which can be SHA256withECDSA or SHA384withECDSA.
├── -issuerKeystoreFile # KS file of the issuer, in JKS or P12 format. It is optional.
├── -issuerKeystorePwd # KS password of the issuer. It is optional.
├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory.
......@@ -126,7 +126,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -issuerKeyPwd # Key password of the issuer. It is optional.
├── -subject # Certificate subject. It is mandatory.
├── -validity # Validity period of the certificate. It is optional. The default value is 3650 days.
├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA.
├── -signAlg # Signing algorithm, which can be SHA256withECDSA or SHA384withECDSA.
├── -issuerKeystoreFile # KS file of the issuer, in JKS or P12 format. It is optional.
├── -issuerKeystorePwd # KS password of the issuer. It is optional.
├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory.
......@@ -155,7 +155,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -extKeyUsage # Extended key usages. It is optional. The extended key usages include clientAuthentication, serverAuthentication,
├ codeSignature, emailProtection, smartCardLogin, timestamp, and ocspSignature.
├── -extKeyUsageCritical # Whether extKeyUsage is a critical option. It is optional. The default value is false.
├── -signAlg # Signature algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory.
├── -signAlg # Signing algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory.
├── -basicConstraints # Whether basicConstraints is contained. It is optional. The default value is false.
├── -basicConstraintsCritical # Whether basicConstraints is a critical option. It is optional. The default value is false.
├── -basicConstraintsCa # Whether it is CA. It is optional. The default value is false.
......@@ -176,7 +176,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -keyPwd # Key password. It is optional.
├── -profileCertFile # Profile signing certificate (certificate chain, in the end-entity certificate, intermediate CA certificate, and root certificate order). It is mandatory.
├── -inFile # Raw profile template in JSON format (developtools_hapsigner/autosign/UnsgnedReleasedProfileTemplate.json). It is mandatory.
├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -signAlg # Signing algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory if the signing mode is localSign.
├── -keystorePwd # KS password. It is optional.
├── -outFile # Signed profile to generate, in p7b format. This parameter is mandatory.
......@@ -186,13 +186,12 @@ The usage of hapsigner varies depending on whether an application signing certif
```
verify-profile: Verify the profile signature.
├── -inFile # Signed profile in p7b format. This parameter is mandatory.
├── -outFile # Verification result file (including the verification result and profile content), in json format. It is optional. The file is output to the console if this parameter is not specified.
├── -inFile # Signed profile in p7b format. This parameter is mandatory.
├── -outFile # Verification result file (including the verification result and profile content), in json format. It is optional. The file is output to the console if this parameter is not specified.
```
11. Sign a HAP.
```
sign-app: Sign a HAP.
├── -mode # Signing mode, which can be localSign, remoteSign, or remoteResign. It is mandatory.
......@@ -203,7 +202,7 @@ The usage of hapsigner varies depending on whether an application signing certif
├── -profileSigned # Whether the profile is signed. The value 1 means signed, and value 0 means unsigned. The default value is 1. This parameter is optional.
├── -inForm # Raw file, in .zip (default) or .bin format. It is optional.
├── -inFile # Raw application package, in HAP or .bin format. It is mandatory.
├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -signAlg # Signing algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory if the signing mode is localSign.
├── -keystorePwd # KS password. It is optional.
├── -outFile # Signed HAP file to generate. It is mandatory.
......@@ -277,7 +276,7 @@ The process of signing a HAP is as follows:
```
generate-app-cert: Generate an application signing certificate.
├── -keyAlias # Key alias, which must be the same as that in the previous step.
├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -signAlg # Signing algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -issuer # Issuer of the certificate. Enter the issuer of the intermediate CA certificate. It is mandatory and cannot be changed.
├── -issuerKeyAlias # Key alias of the issuer. Enter the key alias of the intermediate CA certificate. This parameter is mandatory and cannot be changed.
├── -subject # Subject of the certificate. Enter the subject in the same sequence specified in the command. This parameter is mandatory.
......@@ -307,7 +306,7 @@ The process of signing a HAP is as follows:
```
sign-profile: Sign a profile.
├── -keyAlias # Alias of the key for generating the profile certificate. It is mandatory and cannot be changed.
├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -signAlg # Signing algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -mode # Signing mode, which must be localSign. It is mandatory.
├── -profileCertFile # Profile signing certificate. Use the certificate provided. It is mandatory and cannot be changed.
├── -inFile # Raw profile template in JSON format (developtools_hapsigner/autosign/UnsgnedReleasedProfileTemplate.json). It is mandatory.
......@@ -334,12 +333,12 @@ The process of signing a HAP is as follows:
> - **keyPwd**: Enter the key password in the KS file.
> - **keystorePwd**: Enter the KS password in the KS file.
The command parameters are described as follows:
The command parameters are described as follows:
```
sign-app: Sign a HAP.
├──-keyAlias # Key alias, which must be the same as the alias of the key pair generated. This parameter is mandatory.
├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -signAlg # Signing algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory.
├── -mode # Signing mode, which must be localSign. It is mandatory.
├── -appCertFile # Application signing certificate (certificate chain, in the end-entity certificate, intermediate CA certificate, and root certificate order). Enter the application signing certificate generated in step 2. This parameter is mandatory.
├── -profileFile # Signed profile in p7b format. Enter the profile generated. This parameter is mandatory.
......@@ -403,8 +402,8 @@ The command parameters are described as follows:
- **Possible Causes**
The signature algorithm is not supported. Check the value of **signAlg**.
The signing algorithm is not supported. Check the value of **signAlg**.
- **Solution**
Use ECC to generate the key pair for the application or profile signing certificate. Use SHA256withECDSA or SHA384withECDSA as the HAP signature algorithm.
Use ECC to generate the key pair for the application or profile signing certificate. Use SHA256withECDSA or SHA384withECDSA as the HAP signing algorithm.
# hapsigner Overview
## Introduction
To ensure the integrity and secure source of OpenHarmony applications, the applications must be signed during the build process. Only signed applications can be installed, run, and debugged on real devices. [developtools_hapsigner](https://gitee.com/openharmony/developtools_hapsigner) provides the source code of the OpenHarmony Ability Package (HAP) signing tool - hapsigner. This tool can be used to generate key pairs, certificate signing requests (CSRs), certificates, profile signatures, and HAP signatures.
> **NOTE**<br>For applications that do not need to apply for permissions using the ACL, DevEco Studio provides an auto signing solution to implement one-click signing of applications or services. For details, see [Having Your App Automatically Signed](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465).
## Basic Concepts
The hapsigner tool is implemented based on the Public Key Infrastructure (PKI). Before using this tool, you should understand the following concepts:
......@@ -26,7 +26,7 @@ The hapsigner tool is implemented based on the Public Key Infrastructure (PKI).
- Profile
HarmonyAppProvision configuration file in a HAP contains information such as the authorized application permissions and device ID.
[HarmonyAppProvision configuration file](../quick-start/app-provision-structure.md) provides information such as the authorized application permissions and device ID.
## Constraints
......
......@@ -21,7 +21,7 @@ The procedure below uses these two mechanisms for redirection between the page l
1. Click FoodListItem. The FoodDetail page is displayed. Create a Navigator component in FoodListItem to enable its child components to have the routing function. The target page is 'pages/FoodDetail'.
```
```ts
@Component
struct FoodListItem {
private foodItem: FoodData
......@@ -51,8 +51,8 @@ The procedure below uses these two mechanisms for redirection between the page l
2. Click FoodGridItem. The FoodDetail page is displayed. Import the router module, and then call the push API of this module to push the FoodDetail page to the route stack to implement page redirection.
```
import router from '@system.router'
```ts
import router from '@ohos.router'
@Component
struct FoodGridItem {
......@@ -64,7 +64,7 @@ The procedure below uses these two mechanisms for redirection between the page l
.height(184)
.width('100%')
.onClick(() => {
router.push({ uri: 'pages/FoodDetail' })
router.push({ url: 'pages/FoodDetail' })
})
}
}
......@@ -74,9 +74,9 @@ The procedure below uses these two mechanisms for redirection between the page l
3. Add the icon for returning from the FoodDetail page to the food list page. Save the Back.png file to the resources > base > media directory. Create a custom component PageTitle, which contains the back icon and Food Detail text. Call the router.back() API of the router to display the top page of the route stack, that is, the upper-level page.
```
```ts
// FoodDetail.ets
import router from '@system.router'
import router from '@ohos.router'
@Component
struct PageTitle {
......@@ -101,7 +101,7 @@ The procedure below uses these two mechanisms for redirection between the page l
4. Create the Stack component in the FoodDetail component, including the FoodImageDisplay and PageTitle child components. Set the alignment mode to TopStart.
```
```ts
@Entry
@Component
struct FoodDetail {
......@@ -127,7 +127,7 @@ We have implemented the redirection and going back of the FoodCategoryList and F
1. Set the params attribute in the Navigator of the FoodListItem component. The params attribute accepts the key-value object.
```
```ts
// FoodList.ets
@Component
struct FoodListItem {
......@@ -144,16 +144,16 @@ We have implemented the redirection and going back of the FoodCategoryList and F
The router API called by FoodGridItem also has the capability of redirection with parameters. The method of using the router API is similar to that of using the Navigator.
```
```ts
router.push({
uri: 'pages/FoodDetail',
url: 'pages/FoodDetail',
params: { foodData: this.foodItem }
})
```
2. Import the FoodData class to the FoodDetail page and add the foodItem member variable to the FoodDetail component.
```
```ts
// FoodDetail.ets
import { FoodData } from '../model/FoodData'
......@@ -169,7 +169,7 @@ We have implemented the redirection and going back of the FoodCategoryList and F
3. Obtain the value of foodData. Call router.getParams().foodData to obtain the data corresponding to foodData carried when the FoodCategoryList page is displayed.
```
```ts
@Entry
@Component
struct FoodDetail {
......@@ -183,7 +183,7 @@ We have implemented the redirection and going back of the FoodCategoryList and F
4. Re-build the components on the FoodDetail page. During building, the food information on the FoodDetail page is all directly declared constants. You need to use the passed FoodData data to assign a new value to the constants. The code is as follows:
```
```ts
@Component
struct PageTitle {
build() {
......
......@@ -2,7 +2,9 @@
* Window
* [Window Overview](window-overview.md)
* [Window Development](window-guidelines.md)
* [System Window Development (Stage Model Only)](application-window-stage.md)
* [Application Window Development (FA Model)](application-window-fa.md)
* [Application Window Development (Stage Mode)](system-window-stage.md)
* Display
* [Display Overview](display-overview.md)
* [Display Development](display-guidelines.md)
......
# Application Window Development (FA Model)
## Basic Concepts
Immersive window: System windows such as the status bar and navigation bar are controlled in such a way that they are unobtrusive and natural looking in the entire screen, thereby engaging users more deeply with the content displayed.
The immersive window feature is valid only when the main window of an application is displayed in full-screen mode. It does not apply to a main window in free window mode or a subwindow (for example, a dialog box or a floating window).
## When to Use
In the FA model, you can perform the following operations during application window development:
- Setting the properties and content of the subwindow of an application
- Experiencing the immersive window feature
## Available APIs
The table below lists the common APIs used for application window development. For details about more APIs, see [Window](../reference/apis/js-apis-window.md).
| Instance| API| Description|
| -------- | -------- | -------- |
| Window static method| create(id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void | Creates a subwindow.<br>This API can be used only in the FA model.|
| Window static method| getTopWindow(callback: AsyncCallback&lt;Window&gt;): void | Obtains the top window of the current application.<br>This API can be used only in the FA model.|
| Window static method| find(id: string, callback: AsyncCallback&lt;Window&gt;): void | Finds a window based on the ID.|
| Window | loadContent(path: string, callback: AsyncCallback&lt;void&gt;): void | Loads the page content to this window.|
| Window | moveTo(x: number, y: number, callback: AsyncCallback&lt;void&gt;): void | Moves this window.|
| Window | setBackgroundColor(color: string, callback: AsyncCallback&lt;void&gt;): void | Sets the background color for this window.|
| Window | setBrightness(brightness: number, callback: AsyncCallback&lt;void&gt;): void | Sets the brightness for this window.|
| Window | resetSize(width: number, height: number, callback: AsyncCallback&lt;void&gt;): void | Changes the window size.|
| Window | setFullScreen(isFullScreen: boolean, callback: AsyncCallback&lt;void&gt;): void | Sets whether to enable the full-screen mode for this window.|
| Window | setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback&lt;void&gt;): void | Sets whether to enable the full-screen mode for the window layout. |
| Window | setSystemBarEnable(names: Array&lt;'status'\|'navigation'&gt;): Promise&lt;void&gt; | Sets whether to display the status bar and navigation bar in this window.|
| Window | setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback&lt;void&gt;): void | Sets the properties of the status bar and navigation bar in this window.<br>`systemBarProperties`: properties of the status bar and navigation bar.|
| Window | show(callback: AsyncCallback\<void>): void | Shows this window.|
| Window | on(type: 'touchOutside', callback: Callback&lt;void&gt;): void | Enables listening for click events outside this window.|
| Window | destroy(callback: AsyncCallback&lt;void&gt;): void | Destroys this window.|
## Setting the Subwindow of an Application
You can create a subwindow, such as a dialog box, and set its properties.
### How to Develop
1. Create or obtain a subwindow.
- Call `window.create` to create a subwindow.
- Call `window.getTopWindow` to obtain the top window – subwindow.
- Call `window.find` to find an available subwindow.
```js
import window from '@ohos.window';
var windowClass = null;
// 1. Method 1: Create a subwindow.
window.create("subWindow", window.WindowType.TYPE_APP, (err, data) => {
if (err.code) {
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
// 1. Method 2: Obtain a subwindow.
window.getTopWindow((err, data) => {
if (err.code) {
console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in getting subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
// 1. Method 3: Find a subwindow.
window.find("subWindow", (err, data) => {
if (err.code) {
console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
```
2. Set the properties of the subwindow.
After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness.
```js
// 2. Move the subwindow.
windowClass.moveTo(300, 300, (err, data) => {
if (err.code) {
console.error('Failed to move the window. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data));
});
// 2. Change the size of the subwindow.
windowClass.resetSize(500, 1000, (err, data) => {
if (err.code) {
console.error('Failed to change the window size. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data));
});
```
3. Load content for the subwindow and show it.
Call `loadContent` and `show` to load and display the content in the subwindow.
```js
// 3. Load the page content to the subwindow.
windowClass.loadContent("pages/page2", (err, data) => {
if (err.code) {
console.error('Failed to load the content. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
// 3. Show the subwindow.
windowClass.show((err, data) => {
if (err.code) {
console.error('Failed to show the window. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data));
});
});
```
4. Destroy the subwindow.
When the subwindow is no longer needed, you can call `destroy` to destroy it.
```js
// 4. Destroy the subwindow when a click event outside the window is detected.
windowClass.on('touchOutside', () => {
console.info('touch outside');
windowClass.destroy((err, data) => {
if (err.code) {
console.error('Failed to destroy the subwindow. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in destroying the subwindow. Data: ' + JSON.stringify(data));
});
});
```
## Experiencing the Immersive Window Feature
To create a better video watching and gaming experience, you can use the immersive window feature to hide the system windows, including the status bar and navigation bar. To achieve this effect, you can use the immersive window feature, which is available only for the main window of an application.
### How to Develop
1. Obtain the main window.
The immersive window feature can be implemented only after the main window is obtained. You can call `window.getTopWindow` to obtain the main window.
```js
import window from '@ohos.window';
var mainWindowClass = null;
// 1. Obtain the main window.
window.getTopWindow((err, data) => {
if (err.code) {
console.error('Failed to get the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in getting subWindow. Data: ' + JSON.stringify(data));
mainWindowClass = data;
});
```
2. Implement the immersive effect. You can use any of the following methods:
- Method 1: Call `setFullScreen` to set the main window to be displayed in full screen. In this case, the navigation bar and status bar are hidden.
- Method 2: Call `setSystemBarEnable` to hide the navigation bar and status bar.
- Method 3: Call `setLayoutFullScreen` to enable the full-screen mode for the main window layout. Call `setSystemPropertites` to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window.
```js
// 2. Use method 1 to implement the immersive effect.
var isFullScreen = true;
mainWindowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) {
console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
});
// 2. Use method 2 to implement the immersive effect.
var names = [];
mainWindowClass.setSystemBarEnable(names, (err, data) => {
if (err.code) {
console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data));
});
// 2. Use method 3 to implement the immersive effect.
var isLayoutFullScreen = true;
mainWindowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => {
if (err.code) {
console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data));
});
var SystemBarProperties = {
statusBarColor: '#ff00ff',
navigationBarColor: '#00ff00',
// The following properties are supported since API version 7.
isStatusBarLightIcon: false,
isNavigationBarLightIcon: false,
// The following properties are supported since API version 8.
statusBarContentColor: '#ffffff',
navigationBarContentColor: '#ffffff'
};
mainWindowClass.setSystemBarProperties(SystemBarProperties, (err, data) => {
if (err.code) {
console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data));
});
```
3. Load content for the immersive window and show it.
Call `loadContent` and `show` to load and display the content in the immersive window.
```js
// 3. Load the page content to the immersive window.
mainWindowClass.loadContent("pages/page3", (err, data) => {
if (err.code) {
console.error('Failed to load the content. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
// 3. Show the immersive window.
mainWindowClass.show((err, data) => {
if (err.code) {
console.error('Failed to show the window. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data));
});
});
```
此差异已折叠。
......@@ -358,7 +358,7 @@ In addition, you need to add the hardware configuration description file of the
#### GPIO Adaptation
1. The chip driver adaptation file is stored in the `//drivers/adapter/platform` directory. Add the `gpio_asr.c` and `gpio_asr.h` files to the `gpio` directory, and add the compilation conditions of the new driver file to `BUILD.gn`.
1. The chip driver adaptation file is stored in the `//drivers/hdf_core/adapter/platform` directory. Add the `gpio_asr.c` file to the `gpio` directory, and add the compilation conditions of the new driver file to `BUILD.gn`.
```
if (defined(LOSCFG_SOC_COMPANY_ASRMICRO)) {
......@@ -473,7 +473,7 @@ The compilation option entry of the subsystem is in the `config.json` file of th
The source code of the lwIP component is stored in `//third_party/lwip`. The kernel in OpenHarmony is customized in `//kernel/liteos_m/components/net/lwip-2.1`, including the redefinition of some interfaces and structures.
For details about the porting process, see [lwIP Module Adaptation](porting-chip-board-lwip.md ).
For details about the porting process, see [lwIP Module Adaptation](porting-chip-board-lwip.md).
In this example, the path for setting lwip in the `config.json` file is as follows:
......
......@@ -72,7 +72,13 @@
- [Development on Device Security Level Management](subsys-security-devicesecuritylevel.md)
- Startup
- [Startup](subsys-boot-overview.md)
- [init Module](subsys-boot-init.md)
- init Module
- [init Configuration File](subsys-boot-init-cfg.md)
- [Job Management](subsys-boot-init-jobs.md)
- [Service Management](subsys-boot-init-service.md)
- [Parameter Management](subsys-boot-init-sysparam.md)
- [Sandbox Management](subsys-boot-init-sandbox.md)
- [Plug-in Management](subsys-boot-init-plugin.md)
- [appspawn Module](subsys-boot-appspawn.md)
- [bootstrap Module](subsys-boot-bootstrap.md)
- [FAQs](subsys-boot-faqs.md)
......
此差异已折叠。
此差异已折叠。
......@@ -2813,6 +2813,7 @@ IP多媒体系统调用模式。
| DEVICE_SPEAKER | 1 | 扬声器设备 |
| DEVICE_WIRED_HEADSET | 2 | 有线耳机设备 |
| DEVICE_BLUETOOTH_SCO | 3 | 蓝牙SCO设备 |
| DEVICE_MIC | 4 | 麦克风设备 |
## CallRestrictionType<sup>8+</sup>
......
......@@ -89,7 +89,7 @@ write(info: SysEventInfo): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ----------------------- | ---- | --------------- |
| eventType | [EventType](#eventtype) | 是 | 应用事件类型。 |
| info | [SysEventInfo](#syseventinfo) | 是 | 系统事件。 |
**返回值:**
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册