提交 f2240744 编写于 作者: X xinking129

merge master

Signed-off-by: Nxinking129 <xinxin13@huawei.com>
...@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by ...@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by
- master: the latest version. - master: the latest version.
- OpenHarmony 3.2 Beta5. [Learn more](en/release-notes/OpenHarmony-v3.2-beta5.md) - OpenHarmony 3.2 Release. [Learn more](en/release-notes/OpenHarmony-v3.2-release.md)
- OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md)
......
...@@ -24,6 +24,12 @@ ...@@ -24,6 +24,12 @@
- [Multi-HAP Usage Rules](quick-start/multi-hap-rules.md) - [Multi-HAP Usage Rules](quick-start/multi-hap-rules.md)
- [Multi-HAP Operation Mechanism and Data Communication Modes](quick-start/multi-hap-principles.md) - [Multi-HAP Operation Mechanism and Data Communication Modes](quick-start/multi-hap-principles.md)
- [Application Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md) - [Application Installation and Uninstallation Process](quick-start/application-package-install-uninstall.md)
- Shared Package
- [Shared Package Overview](quick-start/shared-guide.md)
- [HAR](quick-start/har-package.md)
- HSP
- [In-Application HSP Development](quick-start/in-app-hsp.md)
- [Inter-Application HSP Development (for System Applications Only)](quick-start/cross-app-hsp.md)
- Application Configuration Files in Stage Model - Application Configuration Files in Stage Model
- [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md) - [Application Configuration File Overview (Stage Model)](quick-start/application-configuration-file-overview-stage.md)
- [app.json5 Configuration File](quick-start/app-configuration-file.md) - [app.json5 Configuration File](quick-start/app-configuration-file.md)
...@@ -36,18 +42,44 @@ ...@@ -36,18 +42,44 @@
- [Resource Categories and Access](quick-start/resource-categories-and-access.md) - [Resource Categories and Access](quick-start/resource-categories-and-access.md)
- Learning ArkTS - Learning ArkTS
- [Getting Started with ArkTS](quick-start/arkts-get-started.md) - [Getting Started with ArkTS](quick-start/arkts-get-started.md)
- ArkTS Syntax (Declarative UI) - Basic Syntax
- [Basic UI Description](quick-start/arkts-basic-ui-description.md) - [Basic Syntax Overview](quick-start/arkts-basic-syntax-overview.md)
- [Declarative UI Description](quick-start/arkts-declarative-ui-description.md)
- Custom Component
- [Creating a Custom Component](quick-start/arkts-create-custom-components.md)
- [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md)
- [\@Builder: Custom Builder Function](quick-start/arkts-builder.md)
- [\@BuilderParam: @Builder Function Reference](quick-start/arkts-builderparam.md)
- [\@Styles: Definition of Resusable Styles](quick-start/arkts-style.md)
- [\@Extend: Extension of Built-in Components](quick-start/arkts-extend.md)
- [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md)
- State Management - State Management
- [Basic Concepts](quick-start/arkts-state-mgmt-concepts.md) - [State Management Overview](quick-start/arkts-state-management-overview.md)
- [State Management with Page-level Variables](quick-start/arkts-state-mgmt-page-level.md) - Component State Management
- [State Management with Application-level Variables](quick-start/arkts-state-mgmt-application-level.md) - [\@State: State Owned by Component](quick-start/arkts-state.md)
- [Dynamic UI Element Building](quick-start/arkts-dynamic-ui-elememt-building.md) - [\@Prop: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md)
- [Rendering Control](quick-start/arkts-rendering-control.md) - [\@Link: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md)
- [Restrictions and Extensions](quick-start/arkts-restrictions-and-extensions.md) - [\@Provide and \@Consume: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md)
- [\@Observed and \@ObjectLink: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md)
- Application State Management
- [Application State Management Overview](quick-start/arkts-application-state-management-overview.md)
- [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md)
- [AppStorage: Application-wide UI State Storage](quick-start/arkts-appstorage.md)
- [PersistentStorage: Application State Persistence](quick-start/arkts-persiststorage.md)
- [Environment: Device Environment Query](quick-start/arkts-environment.md)
- Other State Management Features
- [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md)
- [\@Watch: Getting Notified of State Variable Changes](quick-start/arkts-watch.md)
- [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md)
- Rendering Control
- [Rendering Control Overview](quick-start/arkts-rendering-control-overview.md)
- [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md)
- [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md)
- [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md)
- Development - Development
- [Application Models](application-models/Readme-EN.md) - [Application Models](application-models/Readme-EN.md)
- [UI Development](ui/Readme-EN.md) - [UI Development](ui/Readme-EN.md)
- [Web](web/Readme-EN.md)
- [Notification](notification/Readme-EN.md) - [Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md) - [WebGL](webgl/Readme-EN.md)
...@@ -81,8 +113,10 @@ ...@@ -81,8 +113,10 @@
- [ArkTS and JS APIs](reference/apis/Readme-EN.md) - [ArkTS and JS APIs](reference/apis/Readme-EN.md)
- [Error Codes](reference/errorcodes/Readme-EN.md) - [Error Codes](reference/errorcodes/Readme-EN.md)
- Native APIs - Native APIs
- [Native APIs](reference/native-apis/Readme-EN.md)
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Node_API](reference/native-lib/third_party_napi/napi.md)
- [FAQs](faqs/Readme-EN.md) - [FAQs](faqs/Readme-EN.md)
- Contribution - Contribution
- [How to Contribute](../contribute/documentation-contribution.md) - [How to Contribute](../contribute/documentation-contribution.md)
<!--no_check-->
\ No newline at end of file
...@@ -25,7 +25,8 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab ...@@ -25,7 +25,8 @@ An [ExtensionAbilityType](../reference/apis/js-apis-bundleManager.md#extensionab
- [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts. - [EnterpriseAdminExtensionAbility](../reference/apis/js-apis-EnterpriseAdminExtensionAbility.md): ExtensionAbility component of the enterprise_admin type, which provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.
> **NOTE**<br> > **NOTE**
>
> 1. Third-party applications cannot implement ServiceExtensionAbility, DataShareExtensionAbility, StaticSubscriberExtensionAbility, or WindowExtensionAbility. > 1. Third-party applications cannot implement ServiceExtensionAbility, DataShareExtensionAbility, StaticSubscriberExtensionAbility, or WindowExtensionAbility.
> >
> 2. To implement transaction processing in the background for a third-party application, use background tasks rather than ServiceExtensionAbility. For details, see [Background Task](../task-management/background-task-overview.md). > 2. To implement transaction processing in the background for a third-party application, use background tasks rather than ServiceExtensionAbility. For details, see [Background Task](../task-management/background-task-overview.md).
...@@ -45,7 +46,7 @@ The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-input ...@@ -45,7 +46,7 @@ The following uses [InputMethodExtensionAbility](../reference/apis/js-apis-input
## Implementing ExtensionAbility of the Specified Type ## Implementing ExtensionAbility of the Specified Type
The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You derive this base class to create your own class (such as **MyFormExtensionAbility**), implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget functionalities. For details, see [FormExtensionAbility](Widget-development-stage.md). The following uses [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) as an example. The widget framework provides the base class [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md). You derive this base class to create your own class (such as **MyFormExtensionAbility**), implement the callbacks, such as **onCreate()** and **onUpdateForm()**, to provide specific widget functionalities. For details, see [FormExtensionAbility](service-widget-overview.md).
You do not need to care when to add or delete a widget. The lifecycle of the FormExtensionAbility instance and the lifecycle of the ExtensionAbility process where the FormExtensionAbility instance is located are scheduled and managed by FormManagerService. You do not need to care when to add or delete a widget. The lifecycle of the FormExtensionAbility instance and the lifecycle of the ExtensionAbility process where the FormExtensionAbility instance is located are scheduled and managed by FormManagerService.
...@@ -63,3 +64,5 @@ You do not need to care when to add or delete a widget. The lifecycle of the For ...@@ -63,3 +64,5 @@ You do not need to care when to add or delete a widget. The lifecycle of the For
> - The two FormExtensionAbility components run in an independent process. > - The two FormExtensionAbility components run in an independent process.
> >
> - The two ImeExtensionAbility components run in an independent process. > - The two ImeExtensionAbility components run in an independent process.
<!--no_check-->
\ No newline at end of file
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
- [Network Sharing](net-sharing.md) - [Network Sharing](net-sharing.md)
- [Ethernet Connection](net-ethernet.md) - [Ethernet Connection](net-ethernet.md)
- [Network Connection Management](net-connection-manager.md) - [Network Connection Management](net-connection-manager.md)
- [mDNS Management](net-mdns.md)
- IPC & RPC - IPC & RPC
- [IPC & RPC Overview](ipc-rpc-overview.md) - [IPC & RPC Overview](ipc-rpc-overview.md)
- [IPC & RPC Development](ipc-rpc-development-guideline.md) - [IPC & RPC Development](ipc-rpc-development-guideline.md)
......
# MDNS Management
## Introduction
Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN.
- Local service: a service provider on a LAN, for example, a printer or scanner.
Typical MDNS management scenarios include:
- Managing local services on a LAN, such as adding, removing, and resolving local services.
- Discovering local services and listening to the status changes of local services of the specified type through the **DiscoveryService** object.
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [mDNS Management](../reference/apis/js-apis-net-mdns.md).
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [mDNS Management](../reference/apis/js-apis-net-mdns.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.mdns | addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\<LocalServiceInfo>): void | Adds an mDNS service. This API uses an asynchronous callback to return the result.|
| ohos.net.mdns | removeLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\<LocalServiceInfo>): void | Removes an mDNS service. This API uses an asynchronous callback to return the result.|
| ohos.net.mdns | createDiscoveryService(context: Context, serviceType: string): DiscoveryService | Creates a **DiscoveryService** object, which is used to discover mDNS services of the specified type.|
| ohos.net.mdns | resolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\<LocalServiceInfo>): void | Resolves an mDNS service. This API uses an asynchronous callback to return the result.|
| ohos.net.mdns.DiscoveryService | startSearchingMDNS(): void | Searches for mDNS services on the LAN.|
| ohos.net.mdns.DiscoveryService | stopSearchingMDNS(): void | Stops searching for mDNS services on the LAN.|
| ohos.net.mdns.DiscoveryService | on(type: 'discoveryStart', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | Enables listening for **discoveryStart** events.|
| ohos.net.mdns.DiscoveryService | on(type: 'discoveryStop', callback: Callback<{serviceInfo: LocalServiceInfo, errorCode?: MdnsError}>): void | Enables listening for **discoveryStop** events.|
| ohos.net.mdns.DiscoveryService | on(type: 'serviceFound', callback: Callback\<LocalServiceInfo>): void | Enables listening for **serviceFound** events.|
| ohos.net.mdns.DiscoveryService | on(type: 'serviceLost', callback: Callback\<LocalServiceInfo>): void | Enables listening for **serviceLost** events.|
## Managing Local Services
1. Connect the device to the Wi-Fi network.
2. Import the **mdns** namespace from **@ohos.net.mdns**.
3. Call **addLocalService** to add a local service.
4. (Optional) Call **resolveLocalService** to resolve the local service for the IP address of the local network.
5. Call **removeLocalService** to remove the local service.
```js
// Import the mdns namespace from @ohos.net.mdns.
import mdns from '@ohos.net.mdns'
// Obtain the context of the FA model.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
// Obtain the context of the stage model.
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
globalThis.context = this.context;
}
}
let context = globalThis.context;
// Create a LocalService object.
let localServiceInfo = {
serviceType: "_print._tcp",
serviceName: "servicename",
port: 5555,
host: {
address: "10.14.**.***",
},
serviceAttribute: [{
key: "111",
value: [1]
}]
}
// Call addLocalService to add a local service.
mdns.addLocalService(context, localServiceInfo, function (error, data) {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// (Optional) Call resolveLocalService to resolve the local service.
mdns.resolveLocalService(context, localServiceInfo, function (error, data) {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
// Call removeLocalService to remove the local service.
mdns.removeLocalService(context, localServiceInfo, function (error, data) {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
```
## Discovering Local Services
1. Connect the device to the Wi-Fi network.
2. Import the **mdns** namespace from **@ohos.net.mdns**.
3. Create a **DiscoveryService** object, which is used to discover mDNS services of the specified type.
4. Subscribe to mDNS service discovery status changes.
5. Enable discovery of mDNS services on the LAN.
6. Stop searching for mDNS services on the LAN.
```js
// Import the mdns namespace from @ohos.net.mdns.
import mdns from '@ohos.net.mdns'
// Obtain the context of the FA model.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
// Obtain the context of the stage model.
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
globalThis.context = this.context;
}
}
let context = globalThis.context;
// Create a LocalService object.
let localServiceInfo = {
serviceType: "_print._tcp",
serviceName: "servicename",
port: 5555,
host: {
address: "10.14.**.***",
},
serviceAttribute: [{
key: "111",
value: [1]
}]
}
// Create a DiscoveryService object, which is used to discover mDNS services of the specified type.
let serviceType = "_print._tcp";
let discoveryService = mdns.createDiscoveryService(context, serviceType);
// Subscribe to mDNS service discovery status changes.
discoveryService.on('discoveryStart', (data) => {
console.log(JSON.stringify(data));
});
discoveryService.on('discoveryStop', (data) => {
console.log(JSON.stringify(data));
});
discoveryService.on('serviceFound', (data) => {
console.log(JSON.stringify(data));
});
discoveryService.on('serviceLost', (data) => {
console.log(JSON.stringify(data));
});
// Enable discovery of mDNS services on the LAN.
discoveryService.startSearchingMDNS();
// Stop searching for mDNS services on the LAN.
discoveryService.stopSearchingMDNS();
```
...@@ -2,13 +2,14 @@ ...@@ -2,13 +2,14 @@
Network management functions include: Network management functions include:
- [HTTP data request](http-request.md): Initiates a data request through HTTP. - [HTTP data request](http-request.md): initiates a data request through HTTP.
- [WebSocket connection](websocket-connection.md): Establishes a bidirectional connection between the server and client through WebSocket. - [WebSocket connection](websocket-connection.md): establishes a bidirectional connection between the server and client through WebSocket.
- [Socket connection](socket-connection.md): Transmits data through Socket. - [Socket connection](socket-connection.md): transmits data through Socket.
- [Network policy management](net-policy-management.md): Restricts network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and resets network policies as needed. - [Network policy management](net-policy-management.md): restricts network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and resets network policies as needed.
- [Network sharing](net-sharing.md): Shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume. - [Network sharing](net-sharing.md): shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume.
- [Ethernet connection](net-ethernet.md): Provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. - [Ethernet connection](net-ethernet.md): provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
- [Network connection management](net-connection-manager.md): Provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. - [Network connection management](net-connection-manager.md): provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
- [mDNS management](net-mdns.md): provides Multicast DNS (mDNS) management capabilities, such as adding, removing, discovering, and resolving local services on a LAN.
## Constraints ## Constraints
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
- [Overview of Application Data Persistence](app-data-persistence-overview.md) - [Overview of Application Data Persistence](app-data-persistence-overview.md)
- [Persisting Preferences Data](data-persistence-by-preferences.md) - [Persisting Preferences Data](data-persistence-by-preferences.md)
- [Persisting KV Store Data](data-persistence-by-kv-store.md) - [Persisting KV Store Data](data-persistence-by-kv-store.md)
- [Persisting RDB Store Data] (data-persistence-by-rdb-store.md) - [Persisting RDB Store Data](data-persistence-by-rdb-store.md)
- Distributed Application Data Synchronization - Distributed Application Data Synchronization
- [Distributed Application Data Synchronization Overview](sync-app-data-across-devices-overview.md) - [Distributed Application Data Synchronization Overview](sync-app-data-across-devices-overview.md)
- [Cross-Device Synchronization of KV Stores](data-sync-of-kv-store.md) - [Cross-Device Synchronization of KV Stores](data-sync-of-kv-store.md)
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
- [Database Backup and Restoration](data-backup-and-restore.md) - [Database Backup and Restoration](data-backup-and-restore.md)
- [Database Encryption](data-encryption.md) - [Database Encryption](data-encryption.md)
- [Access Control by Device and Data Level](access-control-by-device-and-data-level.md) - [Access Control by Device and Data Level](access-control-by-device-and-data-level.md)
- Cross-Application Data Sharing (Available Only for System Applications) - Cross-Application Data Sharing (for System Applications Only)
- [Cross-Application Data Sharing Overview](share-device-data-across-apps-overview.md) - [Cross-Application Data Sharing Overview](share-device-data-across-apps-overview.md)
- [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) - [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md)
- [Sharing Data in Silent Access](share-data-by-silent-access.md) - [Sharing Data in Silent Access](share-data-by-silent-access.md)
...@@ -32,7 +32,9 @@ The following table lists the APIs used for KV data persistence. Most of the API ...@@ -32,7 +32,9 @@ The following table lists the APIs used for KV data persistence. Most of the API
## How to Develop ## How to Develop
1. Create a **KvManager** instance to manage database objects. Example: 1. Create a **KvManager** instance to manage database objects.
Example:
Stage model: Stage model:
...@@ -90,7 +92,9 @@ The following table lists the APIs used for KV data persistence. Most of the API ...@@ -90,7 +92,9 @@ The following table lists the APIs used for KV data persistence. Most of the API
} }
``` ```
2. Create and obtain a KV store. Example: 2. Create and obtain a KV store.
Example:
```js ```js
try { try {
...@@ -116,7 +120,9 @@ The following table lists the APIs used for KV data persistence. Most of the API ...@@ -116,7 +120,9 @@ The following table lists the APIs used for KV data persistence. Most of the API
} }
``` ```
3. Use **put()** to add data to the KV store. Example: 3. Use **put()** to add data to the KV store.
Example:
```js ```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
...@@ -138,7 +144,9 @@ The following table lists the APIs used for KV data persistence. Most of the API ...@@ -138,7 +144,9 @@ The following table lists the APIs used for KV data persistence. Most of the API
> >
> The **put()** method adds a KV pair if the specified key does not exists and changes the value if the the specified key already exists. > The **put()** method adds a KV pair if the specified key does not exists and changes the value if the the specified key already exists.
4. Use **get()** to obtain the value of a key. Example: 4. Use **get()** to obtain the value of a key.
Example:
```js ```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
...@@ -163,7 +171,9 @@ The following table lists the APIs used for KV data persistence. Most of the API ...@@ -163,7 +171,9 @@ The following table lists the APIs used for KV data persistence. Most of the API
} }
``` ```
5. Use **delete()** to delete the data of the specified key. Example: 5. Use **delete()** to delete the data of the specified key.
Example:
```js ```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
......
...@@ -10,7 +10,9 @@ The **Preferences** module provides APIs for processing data in the form of key- ...@@ -10,7 +10,9 @@ The **Preferences** module provides APIs for processing data in the form of key-
User applications call **Preference** through the JS interface to read and write data files. You can load the data of a **Preferences** persistence file to a **Preferences** instance. Each file uniquely corresponds to an instance. The system stores the instance in memory through a static container until the instance is removed from the memory or the file is deleted. The following figure illustrates how **Preference** works. User applications call **Preference** through the JS interface to read and write data files. You can load the data of a **Preferences** persistence file to a **Preferences** instance. Each file uniquely corresponds to an instance. The system stores the instance in memory through a static container until the instance is removed from the memory or the file is deleted. The following figure illustrates how **Preference** works.
**Figure 1** Preferences working mechanism The preference persistent file of an application is stored in the application sandbox. You can use **context** to obtain the file path. For details, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path).
**Figure 1** Preferences working mechanism
![preferences](figures/preferences.jpg) ![preferences](figures/preferences.jpg)
...@@ -28,7 +30,7 @@ User applications call **Preference** through the JS interface to read and write ...@@ -28,7 +30,7 @@ User applications call **Preference** through the JS interface to read and write
The following table lists the APIs used for preferences data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md). The following table lists the APIs used for preferences data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [User Preferences](../reference/apis/js-apis-data-preferences.md).
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void | Obtain a **Preferences** instance.| | getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void | Obtain a **Preferences** instance.|
| put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data.| | put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void | Writes data to the Preferences instance. You can use **flush()** to persist the **Preferences** instance data.|
...@@ -157,7 +159,7 @@ The following table lists the APIs used for preferences data persistence. Most o ...@@ -157,7 +159,7 @@ The following table lists the APIs used for preferences data persistence. Most o
} }
``` ```
5. Deletes data. 5. Delete data.
Use delete() to delete a KV pair.<br>Example: Use delete() to delete a KV pair.<br>Example:
......
...@@ -142,7 +142,9 @@ The following table lists the APIs used for RDB data persistence. Most of the AP ...@@ -142,7 +142,9 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
3. Modify or delete data based on the specified **Predicates** instance. 3. Modify or delete data based on the specified **Predicates** instance.
Use **update()** to modify data and **delete()** to delete data. Example: Use **update()** to modify data and **delete()** to delete data.
Example:
```js ```js
// Modify data. // Modify data.
...@@ -176,7 +178,9 @@ The following table lists the APIs used for RDB data persistence. Most of the AP ...@@ -176,7 +178,9 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
4. Query data based on the conditions specified by **Predicates**. 4. Query data based on the conditions specified by **Predicates**.
Use **query()** to query data. The data obtained is returned in a **ResultSet** object. Example: Use **query()** to query data. The data obtained is returned in a **ResultSet** object.
Example:
```js ```js
let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
...@@ -197,7 +201,9 @@ The following table lists the APIs used for RDB data persistence. Most of the AP ...@@ -197,7 +201,9 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
5. Delete the RDB store. 5. Delete the RDB store.
Use **deleteRdbStore()** to delete the RDB store and related database files. Example: Use **deleteRdbStore()** to delete the RDB store and related database files.
Example:
Stage model: Stage model:
...@@ -215,7 +221,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP ...@@ -215,7 +221,7 @@ The following table lists the APIs used for RDB data persistence. Most of the AP
console.info('Succeeded in deleting RdbStore.'); console.info('Succeeded in deleting RdbStore.');
}); });
} }
} }
``` ```
FA model: FA model:
......
...@@ -68,7 +68,7 @@ When data is added, deleted, or modified, a notification is sent to the subscrib ...@@ -68,7 +68,7 @@ When data is added, deleted, or modified, a notification is sent to the subscrib
- The KV stores do not support custom conflict resolution policies for applications. - The KV stores do not support custom conflict resolution policies for applications.
- A maximum of 16 distributed KV stores can be opened simultaneously for an application. - A maximum of 16 KV stores can be opened simultaneously for an application.
- Each KV store supports a maximum of eight callbacks for subscription of data change notifications. - Each KV store supports a maximum of eight callbacks for subscription of data change notifications.
...@@ -91,7 +91,7 @@ The following table lists the APIs for cross-device data synchronization of the ...@@ -91,7 +91,7 @@ The following table lists the APIs for cross-device data synchronization of the
## How to Develop ## How to Develop
The following uses a single KV store as an example to describe how to implement cross-device data synchronization. The following describes the development process. The following uses a single KV store as an example to describe how to implement cross-device data synchronization. The development process is as follows.
![kvStore_development_process](figures/kvStore_development_process.png) ![kvStore_development_process](figures/kvStore_development_process.png)
......
...@@ -17,6 +17,7 @@ There are two roles in **DataShare**: ...@@ -17,6 +17,7 @@ There are two roles in **DataShare**:
- Data consumer: accesses the data provided by the provider using [createDataShareHelper()](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper). - Data consumer: accesses the data provided by the provider using [createDataShareHelper()](../reference/apis/js-apis-data-dataShare.md#datasharecreatedatasharehelper).
**Figure 1** Data sharing mechanism **Figure 1** Data sharing mechanism
![dataShare](figures/dataShare.jpg) ![dataShare](figures/dataShare.jpg)
- The **DataShareExtensionAbility** module, as the data provider, implements services related to data sharing between applications. - The **DataShareExtensionAbility** module, as the data provider, implements services related to data sharing between applications.
......
...@@ -9,7 +9,7 @@ Application recovery helps to restore the application state and save temporary d ...@@ -9,7 +9,7 @@ Application recovery helps to restore the application state and save temporary d
In API version 9, application recovery is supported only for a single ability of the application developed using the stage model. Application state saving and automatic restart are performed when a JsError occurs. In API version 9, application recovery is supported only for a single ability of the application developed using the stage model. Application state saving and automatic restart are performed when a JsError occurs.
In API version 10, application recovery is also supported for multiple abilities of the application developed using the stage model. Application state storage and restore are performed when an AppFreeze occurs. If an application is killed in control mode, the application state will be restored upon next startup. In API version 10, application recovery is applicable to multiple abilities of an application developed using the stage model. Application state storage and restore are performed when an AppFreeze occurs. If an application is killed in control mode, the application state will be restored upon next startup.
## Available APIs ## Available APIs
...@@ -221,3 +221,20 @@ export default class EntryAbility extends Ability { ...@@ -221,3 +221,20 @@ export default class EntryAbility extends Ability {
} }
} }
``` ```
#### Restart Flag for the Failed Ability
If the failed ability is restarted again, the [ABILITY_RECOVERY_RESTART](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams) flag will be added as a **parameters** member for the **want** parameter in **onCreate** and its value is **true**.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import wantConstant from '@ohos.app.ability.wantConstant';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
if (want.parameters[wantConstant.Params.ABILITY_RECOVERY_RESTART] != undefined &&
want.parameters[wantConstant.Params.ABILITY_RECOVERY_RESTART] == true) {
console.log("This ability need to recovery");
}
}
}
```
...@@ -23,7 +23,8 @@ When an asynchronous callback is used, the return value can be processed directl ...@@ -23,7 +23,8 @@ When an asynchronous callback is used, the return value can be processed directl
| API | Description | | API | Description |
| ------------------------------ | ------------------------------------------------------------ | | ------------------------------ | ------------------------------------------------------------ |
| onUnhandledException(errMsg: string): void | Called when an application generates an uncaught exception after being registered.| | onUnhandledException(errMsg: string): void | Called when an uncaught exception is reported after the application is registered.|
| onException?(errObject: Error): void | Called when an application exception is reported to the JavaScript layer after the application is registered.|
### Result Codes for Unregistering an Observer ### Result Codes for Unregistering an Observer
...@@ -43,6 +44,13 @@ let registerId = -1; ...@@ -43,6 +44,13 @@ let registerId = -1;
let callback = { let callback = {
onUnhandledException: function (errMsg) { onUnhandledException: function (errMsg) {
console.log(errMsg); console.log(errMsg);
},
onException: function (errorObj) {
console.log('onException, name: ', errorObj.name);
console.log('onException, message: ', errorObj.message);
if (typeof(errorObj.stack) === 'string') {
console.log('onException, stack: ', errorObj.stack);
}
} }
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
- [Programming Languages](faqs-language.md) - [Programming Languages](faqs-language.md)
- [Ability Framework Development](faqs-ability.md) - [Ability Framework Development](faqs-ability.md)
- [Bundle Management Development](faqs-bundle.md) - [Resource Manager Development](faqs-globalization.md)
- [ArkUI (ArkTS) Development](faqs-ui-ets.md) - [ArkUI (ArkTS) Development](faqs-ui-ets.md)
- [ArkUI Web Component (ArkTS) Development](faqs-web-arkts.md) - [ArkUI Web Component (ArkTS) Development](faqs-web-arkts.md)
- [ArkUI (JavaScript) Development](faqs-ui-js.md) - [ArkUI (JavaScript) Development](faqs-ui-js.md)
...@@ -10,12 +10,9 @@ ...@@ -10,12 +10,9 @@
- [Graphics and Image Development](faqs-graphics.md) - [Graphics and Image Development](faqs-graphics.md)
- [File Management Development](faqs-file-management.md) - [File Management Development](faqs-file-management.md)
- [Media Development](faqs-media.md) - [Media Development](faqs-media.md)
- [Network and Connection Development](faqs-connectivity.md) - [Network Management Development](faqs-network-management.md)
- [Data Management Development](faqs-data-management.md)
- [Device Management Development](faqs-device-management.md)
- [DFX Development](faqs-dfx.md) - [DFX Development](faqs-dfx.md)
- [Intl Development](faqs-international.md)
- [Native API Usage](faqs-native.md) - [Native API Usage](faqs-native.md)
- [Startup Development](faqs-startup.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md)
- [IDE Usage](faqs-ide.md) - [IDE Usage](faqs-ide.md)
- [Development Board](faqs-development-board.md)
\ No newline at end of file
# Network and Connection Development
## What are the data formats supported by extraData in an HTTP request?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
**extraData** indicates additional data in an HTTP request. It varies depending on the HTTP request method.
- If the HTTP request uses a POST or PUT method, **extraData** serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, **extraData** serves as a supplement to the HTTP request parameters and will be added to the URL when the request is sent.
- If you pass in a string object, **extraData** contains the string encoded on your own.
## What does error code 28 mean for an HTTP request?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available.
Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
## What does error code 6 mean for the response of \@ohos.net.http.d.ts?
Applicable to: OpenHarmony SDK 3.2.3.5
Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible.
Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
# Data Management Development
## How Do I Save PixelMap Data to a Database?
Applicable to: OpenHarmony SDK 3.2.3.5
You can convert a **PixelMap** into an **ArrayBuffer** and save the **ArrayBuffer** to your database.
Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1)
## How Do I Obtain RDB Store Files?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Run the hdc_std command to copy the .db, .db-shm, and .db-wal files in **/data/app/el2/100/database/*bundleName*/entry/db/**, and then use the SQLite tool to open the files.
Example:
```
hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db
```
## Does the Database Has a Lock Mechanism?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
The distributed data service (DDS), relational database (RDB) store, and preferences provided OpenHarmony have a lock mechanism. You do not need to bother with the lock mechanism during the development.
## What Is a Transaction in an RDB Store?
Applicable to: all versions
When a large number of operations are performed in an RDB store, an unexpected exception may cause a failure of some data operations and loss of certain data. As a result, the application may become abnormal or even crash.
A transaction is a group of tasks serving as a single logical unit. It eliminates the failure of some of the operations and loss of associated data.
## What Data Types Does an RDB Store Support?
Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9
An RDB store supports data of the number, string, and Boolean types. The number array supports data of the Double, Long, Float, Int, or Int64 type, with a maximum precision of 17 decimal digits.
## How Do I View Database db Files?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
1. Run the **hdc_std shell** command.
2. Obtain the absolute path or sandbox path of the database.
The absolute path is **/data/app/el2/<userId>/database/<bundleName>**. The default **<userId>** is **100**.
To obtain the sandbox path, run the **ps -ef | grep hapName** command to obtain the process ID of the application.
The database sandbox path is **/proc/<Application process ID>/root/data/storage/el2/database/**.
3. Run the **find ./ -name "\*.db"** command in the absolute path or sandbox path of the database.
## How Do I Store Long Text Data?
Applicable to: OpenHarmony SDK 3.2.5.5, API version 9
- Preferences support a string of up to 8192 bytes.
- The KV store supports a value of up to 4 MB.
Reference: [Preference Overview](../database/database-preference-overview.md) and [Distributed Data Service Overview](../database/database-mdds-overview.md)
## How Do I Develop DataShare on the Stage Model
Applicable to: OpenHarmony SDK 3.2.5.5, API version 9
The DataShare on the stage model cannot be used with the **DataAbility** for the FA model. The connected server application must be implemented by using **DataShareExtensionAbility**.
Reference: [DataShare Development](../database/database-datashare-guidelines.md)
# Development Board Usage
## How do I take screenshots on a development board?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
- Method 1: Click the screenshot button in the Control Panel from the development board UI. The screenshot is displayed in Gallery.
- Method 2: Run the screenshot script. Connect to the development board to a computer running Windows. Create a text file on the computer, copy the following script content to the file, change the file name extension to **.bat** (the HDC environment variables must be configured in advance), and click **Run**. The screenshot is saved to the same directory as the **.bat** script file.
Example:
```
set filepath=/data/%date:~0,4%%date:~5,2%%date:~8,2%%time:~1,1%%time:~3,2%%time:~6,2%.png
echo %filepath%
: pause
hdc_std shell snapshot_display -f %filepath%
: pause
hdc_std file recv %filepath% .
: pause
```
## How do I adjust Previewer in DevEco Studio so that the preview looks the same as what's displayed on a real RK3568 development board?
Applicable to: DevEco Studio 3.0.0.991
1. Create a profile in Previewer.
![en-us_image_0000001361254285](figures/en-us_image_0000001361254285.png)
2. Set the profile parameters as follows:
Device type : default
Resolution: 720\*1280
DPI: 240
## What should I do if Device Manager incorrectly identifies a development board as FT232R USB UART even when the development board already has a driver installed?
Possible cause: The USB serial driver of the development version is not installed.
Solution: Search for **FT232R USB UART**, and download and install the driver.
## How do I complete authentication when logging in to the development board?
Applicable to: OpenHarmony SDK 3.2.2.5
When connecting to the network that requires authentication, open any web page in the browser to access the authentication page.
If there is no browser on the development board, you can install the [sample browser application](https://gitee.com/openharmony/app_samples/tree/master/device/Browser).
# Device Management Development
## How do I obtain the DPI of a device?
Applicable to: OpenHarmony 3.2 Beta5, stage model of API version 9
Import the **@ohos.display** module and call the **getDefaultDisplaySync** API.
**Example**
```
import display from '@ohos.display';
let displayClass = null;
try {
displayClass = display.getDefaultDisplaySync();
console.info('Test densityDPI:' + JSON.stringify(data.densityDPI));
} catch (exception) {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception));
}
```
## How do I obtain the type of the device where the application is running?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Import the **\@ohos.deviceInfo** module and call the **deviceInfo.deviceType** API.
For details, see [Device Information](../reference/apis/js-apis-device-info.md).
## How do I obtain the system version of a device?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Use the **osFullName** attribute of the [deviceInfo](../reference/apis/js-apis-device-info.md) object.
## How do I obtain the UDID of an OpenHarmony device?
Applicable to: OpenHarmony SDK3.0, stage model of API version 9
- To obtain the UDID of the connected device, run the **hdc shell bm get --udid** command.
- For details about how to obtain the UDID from code, see [udid](../reference/apis/js-apis-device-info.md).
## How do I develop a shortcut key function?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
To develop a shortcut key function, use the APIs in [Input Consumer](../reference/apis/js-apis-inputconsumer.md).
# DFX Development # DFX Development
## How do I locate the fault when the application crashes? ## How do I flush HiLog information to disks?
Applicable to: OpenHarmony SDK 3.2.5.5 Applicable to: OpenHarmony 3.2 Beta (API version 9)
1. Locate the crash-related code based on the service log. **Symptom**
2. View the error information in the crash file, which is located at **/data/log/faultlog/faultlogger/**. How do I flush HiLog information to disks?
## Why cannot access controls in the UiTest test framework? **Solution**
Applicable to: OpenHarmony SDK 3.2.5.5 Run the **hilog -w start -f ckTest -l 1M -n 5 -m zlib -j 11** command.
Check whether **persist.ace.testmode.enabled** is turned on. The log file is saved in the **/data/log/hilog/** directory.
Run **hdc\_std shell param get persist.ace.testmode.enabled**. Parameter description:
If the value is **0**, run the **hdc\_std shell param set persist.ace.testmode.enabled 1** to enable the test mode. ```
-**-w**: Starts a log flushing task. **start** means to start the task, and **stop** means to stop the task.
-**-f**: Sets the log file name.
## Why is private displayed in logs when the format parameter type of HiLog in C++ code is %d or %s? -**-l**: Sets the size of a single log file. The unit can be B, KB, MB, or GB.
-**-n**: Sets the maximum number of log files. When the number of log files exceeds the specified value, the earliest log file will be overwritten. The value range is [2,1000].
When format parameters such as **%d** and **%s** are directly used, the standard system uses **private** to replace the actual data for printing by default to prevent data leakage. To print the actual data, replace **%d** with **%{public}d** or replace **%s** with **%{public}s**. -**-m**: Specifies the log file compression algorithm.
-**-j**: Specifies the task ID. The value ranges from **10** to **0xffffffffff**.
## What should I do if the hilog.debug log cannot be printed? For more details about parameters, run the **hilog --help** command.
```
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Run **hdc_std shell hilog -b D** to turn on the debugging switch.
## Is HiLog or console recommended for log printing? How do I set the domain if HiLog is used?
Applicable to: OpenHarmony SDK 3.2.2.5
You are advised to use the [HiLog](../reference/apis/js-apis-hilog.md) for log printing. For details about how to set the **domain** parameter, see the [Development Guide](../reference/apis/js-apis-hilog.md#hilogisloggable).
## What is the maximum length of a log record when HiLog is used? Is it configurable?
Applicable to: OpenHarmony SDK 3.2.2.5
The maximum length of a log record is 1,024 characters, and it is not changeable.
## Can I separate multiple strings by spaces in the tag parameter of the HiLog API?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
No. Separating multiple strings by spaces is not allowed.
## How do I print real data if HiLog does not contain data labeled by {public}?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
Run **hdc\_std shell hilog -p off** to disable logging of data labeled by {public}.
# Resource Manager Development
## How do I read an XML file in rawfile and convert the data in it to the string type?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Call **getRawFileContent** of the **ResourceManager** module to obtain the data in the XML file, and then use **String.fromCharCode** to convert the data to the string type.
**Sample Code**
```
resourceManager.getRawFileContent('test.xml', (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let rawFile = value;
let xml = String.fromCharCode.apply(null, rawFile)
}
});
```
**Reference**
[Resource Manager](../reference/apis/js-apis-resource-manager.md)
## How do I obtain resources in the stage model?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
**Solution**
The stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This mode does not apply to the FA model.
**Sample Code**
```
const context = getContext(this) as any
context
.resourceManager
.getString($r('app.string.entry_desc').id)
.then(value => {
this.message = value.toString()
})
```
## How do I obtain the path of the resource directory by using an API?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
**Symptom**
How do I obtain the path of the **resource** directory so that I can manage the files in it by using the file management API?
**Solution**
Because the application is installed in HAP mode and the HAP package is not decompressed after the installation is complete, the resource path cannot be obtained when the program is running.
To obtain the path of the **resource** directory, try either of the following ways:
1. Use **\$r** or **\$rawfile** for access. This method applies to static access, during which the **resource** directory remains unchanged when the application is running.
2. Use **ResourceManager** for access. This method applies to dynamic access, during which the **resource** directory dynamically changes when the application is running.
**Reference**
[Resource Categories and Access](../quick-start/resource-categories-and-access.md) and [Resource Manager](../reference/apis/js-apis-resource-manager.md)
## Why does getPluralString return an incorrect value?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
The value obtained by the **getPluralString** is **other**, which is incorrect.
**Solution**
The **getPluralString** API is effective only when the system language is English.
## How do I obtain the customized string fields in the resources directory?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Use **getStringValue** of the **ResourceManager** module.
**Reference**
[Resource Manager](../reference/apis/js-apis-resource-manager.md#getstringvalue9)
## How do I reference resources such as images and text in AppScope?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Reference resources in the **\$r\('app.type.name'\)** format. Wherein, **type** indicates the resource type, such as color, string, and media, and **name** indicates the resource name.
## How do I convert resources to strings?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
For a qualifier directory, use **this.context.resourceManager.getStringSync\(\$r\('app.string.test'\).id\)** to covert resources to strings synchronously. Note that the **\$r\('app.string.test', 2\)** mode is not supported.
**Reference**
[Resource Manager](../reference/apis/js-apis-resource-manager.md#getstringsync9)
## Can $ be used to reference constants in the form\_config.json file?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**\$** cannot be used to reference constants in the **form\_config.json** file.
# Intl Development
## How resources in AppScope, such as images and text, are referenced?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Resources are referenced in the **$r('app.type.name')** format. Where, **type** indicates the resource type, such as color, string, and media, and **name** indicates the resource name.
## How do I convert the resource type to string?
Applicable to: OpenHarmony SDK3.0, stage model of API version 9
If the resource type is set to **string**, the qualifier directory can be set as **this.context.resourceManager.getStringSync(\\$r('app.string.test').id)** and can be converted synchronously. The **\$r('app.string.test', 2)** mode is not supported. For more usage methods, see [Resource Manager](../reference/apis/js-apis-resource-manager.md#getstringsync9).
## Why should I do if the constants referenced by $ in the form_config.json file does not take effect?
Applicable to: OpenHarmony SDK 3.2.6.5, API9 Stage model
In the **form\_config.json** file, **$** cannot be used to reference constants.
...@@ -85,8 +85,6 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 ...@@ -85,8 +85,6 @@ Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Objects imported to abilities and pages are packaged into two different closures, that is, two global objects. In this case, a static variable referenced by the abilities is not the same object as that referenced by the pages. Therefore, global variables cannot be defined by defining static variables in the class. You are advised to use AppStorage to manage global variables. Objects imported to abilities and pages are packaged into two different closures, that is, two global objects. In this case, a static variable referenced by the abilities is not the same object as that referenced by the pages. Therefore, global variables cannot be defined by defining static variables in the class. You are advised to use AppStorage to manage global variables.
Reference: [State Management with Application-level Variables](../quick-start/arkts-state-mgmt-application-level.md)
## How do I obtain resources in the stage model? ## How do I obtain resources in the stage model?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
...@@ -181,7 +179,7 @@ Similar to **new Date().getTime()**, **systemTime.getCurrentTime(false)** return ...@@ -181,7 +179,7 @@ Similar to **new Date().getTime()**, **systemTime.getCurrentTime(false)** return
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
If no parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, **content: this.specificParam**), define the type of the attribute as a function without a return value (for example, **@BuilderParam content: () =&gt; voi**). If any parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, **callContent: this.specificParam1("111")**), define the type of the attribute as **any** (for example, **@BuilderParam callContent: any**). For details, see [BuilderParam](../quick-start/arkts-dynamic-ui-elememt-building.md#builderparam8). If no parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, **content: this.specificParam**), define the type of the attribute as a function without a return value (for example, **@BuilderParam content: () =&gt; voi**). If any parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, **callContent: this.specificParam1("111")**), define the type of the attribute as **any** (for example, **@BuilderParam callContent: any**).
## How does ArkTS convert a string into a byte array? ## How does ArkTS convert a string into a byte array?
...@@ -251,7 +249,6 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 ...@@ -251,7 +249,6 @@ Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
To listen for in-depth changes of **@State** decorated variables, you can use **@Observed** and **@ObjectLink** decorators. To listen for in-depth changes of **@State** decorated variables, you can use **@Observed** and **@ObjectLink** decorators.
## How do I implement character string encoding and decoding? ## How do I implement character string encoding and decoding?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
......
# Network Management Development
## What are the data formats supported by extraData in an HTTP request?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
**extraData** indicates additional data in an HTTP request. It varies depending on the HTTP request method.
- If the HTTP request uses a POST or PUT method, **extraData** serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, **extraData** serves as a supplement to the HTTP request parameters and will be added to the URL when the request is sent.
- If you pass in a string object, **extraData** contains the string encoded on your own.
## What does error code 28 mean in the response to an HTTP request?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
Error code 28 is reported after an HTTP request is initiated.
**Solution**
Error code 28 indicates **CURLE\_OPERATION\_TIMEDOUT**, which means a libcurl library operation timeout. For details, see any HTTP status code description available.
**Reference**
[Common HTTP Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
## What does error code 6 mean in the response to an HTTP request?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
Error code 6 is reported after an HTTP request is initiated.
**Solution**
Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible.
**Reference**
[Common HTTP Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
## How are parameters passed to queryParams of the POST request initiated by @ohos/axios?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
How are parameters passed to **queryParams** when the third-party component @ohos/axios initiates a POST request?
**Solution**
- Method 1: Have the **axios.post** API receive only one parameter. The **Url.URLSearchParams** parameter needs to be converted into a string and appended to the end of the URL.
```
let params:Url.URLSearchParams = new Url.URLSearchParams()
params.append('ctl', 'sug')
params.append('query', 'wangjunkai')
params.append('cfrom', '1099a')
axios.post('http://10.100.195.234:3000/save?' + params.toString()).then(res => {
this.message = "request result: " + JSON.stringify(res.data);
}).catch(err => {
this.message = "request error: " + err.message;
})
```
- Method 2: Have the **axios** API receive only one **config** object. The request parameters are written in **params** of the **config** object.
```
axios({
url: 'http://10.100.195.234:3000/save',
method: 'post',
params: {
ctl: 'sug',
query: 'wangjunkai',
cfrom: '1099a'
}
}).then(res => {
this.message = "request result: " + JSON.stringify(res.data);
}).catch(err => {
this.message = "request error: " + err.message;
})
```
## What should I do if no data is returned after connection.getNetCapabilities\(mNetHandle\) is called?
Applicable to: OpenHarmony 3.2 Beta 2 (API version 9)
**Symptom**
No data is returned after **connection.getNetCapabilities\(\)** is called. What should I do?
**Possible Cause**
This problem is due to incorrect pointing of the **this** object. You are expected to use **\(err,data\)=\>\{\}** instead of **function\(err,data\)** to access the callback function to obtain the return result. The reason is that the function declared by **function** has its own **this** object and therefore cannot point to the **globalThis** object.
**Solution**
Change **function\(err,data\)** to **\(err,data\)** for the second parameter of **getNetCapabilities**.
## How is data in HTTP requests transmitted in JSON format?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
In the HTTP message header, **Content-Type** is used to indicate the media type information. It tells the server how to process the requested data and tells the client (usually a browser) how to parse the response data, for example, displaying an image, parsing HTML, or displaying only the text.
To transmit data in HTTP requests in JSON format, set **Content-Type** to **application/json**.
```
this.options = {
method: http.RequestMethod.GET,
extraData: this.extraData,
header: { 'Content-Type': 'application/json' },
readTimeout: 50000,
connectTimeout: 50000
}
```
## How do I upload photos taken by a camera to the server?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
After an application calls the camera to take a photo, how do I upload the photo to the server?
**Solution**
After the application is started and the permission is obtained, have the system access the remote server and transfer the locally saved photos to the remote server through the upload API.
**Reference**
[Upload and Download](../reference/apis/js-apis-request.md)
## What should I do if calling connection.hasDefaultNet\(\) fails even when the network is normal?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
The network connection is normal, and web pages can be opened properly on the browser. However, calling the **hasDefaultNet** fails, and the callback function returns an error.
**Solution**
Declare the **ohos.permission.GET\_NETWORK\_INFO** permission when calling **connection.hasDefaultNet**.
For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
## What does netId mean in the netHandle object returned by connection.getDefaultNet?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
What are the meanings of the values of **netId**, such as **0** and **100**?
**Solution**
If the value of **netId** is **0**, no network connection is available. In such a case, check and rectify network faults. If the value is greater than or equal to **100**, the network connection is normal.
## How do I use HTTP requests to obtain data from the network?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
Use the **@ohos.net.http** module to initiate an HTTP request.
1. Import the **http** module and create an HTTP request.
2. Set the request URL and parameters and initiate the HTTP request.
3. Obtain the response and parse the data.
**Reference**
[HTTP Data Request](../connectivity/http-request.md)
## How do I encapsulate network requests by using JavaScript?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
OpenHarmony supports the JavaScript development mode. You can directly use JavaScript to encapsulate network requests. For details, see [Network Connection](../reference/apis/js-apis-http.md).
## How do I write network requests when developing a JavaScript-based application for smart watches?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Solution**
OpenHarmony supports the JavaScript development mode. You can directly use JavaScript to encapsulate network requests. For details, see [Network Connection](../reference/apis/js-apis-http.md).
## Why does an application fail to start after the ohos.permission.NOTIFICATION\_CONTROLLER permission is declared?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
When an application is started, the following error message is reported w: error: install failed due to grant request permissions failed.
**Solution**
The **ohos.permission.NOTIFICATION\_CONTROLLER** permission is a **system core** permission and is not available for third-party applications.
## What should I do if an error is reported when wifi.getIpInfo\(\).ipAddress is used in the Wi-Fi module?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
When **wifi.getIpInfo\(\).ipAddress** is used in the Wi-Fi module, the following error message is reported: Error: assertion \(wifiDevicePtr != nullptr\) failed: Wifi device instance is null.
**Solution**
This problem is due to insufficient permissions. Check whether you have applied for the required permissions. For details, see [Permission Management](../security/accesstoken-overview.md).
# Startup Development
## How do I obtain the system version of a device?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
You can obtain the system version of a device through the **osFullName** attribute of the [deviceInfo](../reference/apis/js-apis-device-info.md) object.
**Sample Code**
```
import deviceInfo from '@ohos.deviceInfo'
let v = deviceInfo.osFullName
```
## How do I obtain the UDID of a device?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
- Method 1: Run the **hdc shell bm get --udid** command.
- Method 2: Obtain the value from the code. For details, see [udid](../reference/apis/js-apis-device-info.md).
## How do I obtain device information?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
You can call **deviceInfo** to obtain device information, such as the device model.
**Reference**
[Device Information](../reference/apis/js-apis-device-info.md)
## How do I prevent application development from being interrupted by screen saving?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
Run the **hdc shell "power-shell setmode 602"** command to turn off screen saving.
# File # File Management
- [File Management Overview](file-management-overview.md) - [File Management Overview](file-management-overview.md)
- Application File - Application File
...@@ -20,4 +20,4 @@ ...@@ -20,4 +20,4 @@
- Distributed File System - Distributed File System
- [Distributed File System Overview](distributed-fs-overview.md) - [Distributed File System Overview](distributed-fs-overview.md)
- [Setting the Security Level of a Distributed File](set-security-label.md) - [Setting the Security Level of a Distributed File](set-security-label.md)
- [Access Files Across Devices](file-access-across-devices.md) - [Accessing Files Across Devices](file-access-across-devices.md)
...@@ -73,7 +73,7 @@ The following figure shows the application file directories. The path of a file ...@@ -73,7 +73,7 @@ The following figure shows the application file directories. The path of a file
| distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices.<br>This directory is cleared when the application is uninstalled.| | distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices.<br>This directory is cleared when the application is uninstalled.|
| files | filesDir | Application file directory| Directory for saving the application's persistent files on the device.<br>This directory is cleared when the application is uninstalled.| | files | filesDir | Application file directory| Directory for saving the application's persistent files on the device.<br>This directory is cleared when the application is uninstalled.|
| cache | cacheDir | Application cache file directory| Directory for caching the downloaded files of the application or saving the cache files regenerated on the device.<br>This directory is automatically cleared when the size of the **cache** directory reaches the quota or the system storage space reaches a certain threshold. The user can also clear this directory by using a system space management application. <br>The application needs to check whether the file still exists and determine whether to cache the file again.| | cache | cacheDir | Application cache file directory| Directory for caching the downloaded files of the application or saving the cache files regenerated on the device.<br>This directory is automatically cleared when the size of the **cache** directory reaches the quota or the system storage space reaches a certain threshold. The user can also clear this directory by using a system space management application. <br>The application needs to check whether the file still exists and determine whether to cache the file again.|
| preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Data Persistence by User Preferences](../database/data-persistence-by-preferences.md).| | preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).|
| temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device. <br>This directory is cleared when the application exits.| | temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device. <br>This directory is cleared when the application exits.|
The application file paths are used in the following scenarios: The application file paths are used in the following scenarios:
...@@ -92,5 +92,3 @@ The following figure shows the application file directories. The path of a file ...@@ -92,5 +92,3 @@ The following figure shows the application file directories. The path of a file
Used to store application preferences data, including preference files and configuration files. This directory applied to storing only a small amount of data. Used to store application preferences data, including preference files and configuration files. This directory applied to storing only a small amount of data.
- Temporary file directory<br> - Temporary file directory<br>
Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package files. The data stored in this directory is deleted after being used. Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package files. The data stored in this directory is deleted after being used.
<!--no_check-->
\ No newline at end of file
# Access Files Across Devices # Accessing Files Across Devices
The distributed file system provides cross-device file access capabilities for applications. For the same application installed on multiple devices, you can implement read and write of the files in the application's distributed directory (**/data/storage/el2/distributedfiles/**) across devices by using [ohos.file.fs](app-file-access.md). For example, device A and device B are installed with the same application. After device A and device B are connected to form a Virtual Device, the application on device A can access the files of the same application on Device B. What you need to do is place the files to the distributed directory. The distributed file system provides cross-device file access capabilities for applications. For the same application installed on multiple devices, you can implement read and write of the files in the application's distributed directory (**/data/storage/el2/distributedfiles/**) across devices by using [ohos.file.fs](app-file-access.md). For example, device A and device B are installed with the same application. After device A and device B are connected to form a Virtual Device, the application on device A can access the files of the same application on Device B. What you need to do is place the files to the distributed directory.
......
...@@ -23,6 +23,3 @@ The file systems can be classified into the following types based on the file st ...@@ -23,6 +23,3 @@ The file systems can be classified into the following types based on the file st
**Figure 1** Files in an OS **Figure 1** Files in an OS
![File classification model](figures/file-classification-model.png) ![File classification model](figures/file-classification-model.png)
<!--no_check-->
\ No newline at end of file
# Setting the Security Level of a Distributed File # Setting the Security Level of a Distributed File
The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data and Device Security Classification](../database/access-control-by-device-and-data-level.md). The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data Security Labels and Device Security Levels](../database/access-control-by-device-and-data-level.md).
## Available APIs ## Available APIs
...@@ -39,4 +39,3 @@ securityLabel.setSecurityLabel(filePath, 's0').then(() => { ...@@ -39,4 +39,3 @@ securityLabel.setSecurityLabel(filePath, 's0').then(() => {
console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to setSecurityLabel. Code: ${err.code}, message: ${err.message}`);
}); });
``` ```
<!--no_check-->
\ No newline at end of file
...@@ -45,11 +45,11 @@ ...@@ -45,11 +45,11 @@
- [Session Management](camera-session-management.md) - [Session Management](camera-session-management.md)
- [Camera Preview](camera-preview.md) - [Camera Preview](camera-preview.md)
- [Camera Photographing](camera-shooting.md) - [Camera Photographing](camera-shooting.md)
- [Video Recording](camera-recording.md) - [Camera Recording](camera-recording.md)
- [Camera Metadata](camera-metadata.md) - [Camera Metadata](camera-metadata.md)
- Best Practices - Best Practices
- [Camera Photographing Sample](camera-shooting-case.md) - [Camera Photographing Sample](camera-shooting-case.md)
- [Video Recording Sample](camera-recording-case.md) - [Camera Recording Sample](camera-recording-case.md)
- Image - Image
- [Image Overview](image-overview.md) - [Image Overview](image-overview.md)
- [Image Decoding](image-decoding.md) - [Image Decoding](image-decoding.md)
......
# Video Recording Sample # Camera Recording Sample
## Development Process ## Development Process
......
# Video Recording # Camera Recording
Video recording is also an important function of the camera application. Video recording is the process of cyclic capturing of frames. To smooth videos, you can follow step 4 in [Camera Photographing](camera-shooting.md) to set the resolution, flash, focal length, photo quality, and rotation angle. Video recording is also an important function of the camera application. Video recording is the process of cyclic capturing of frames. To smooth videos, you can follow step 4 in [Camera Photographing](camera-shooting.md) to set the resolution, flash, focal length, photo quality, and rotation angle.
......
# Raw File Development # Raw File Development
## When to Use ## When to Use
This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use the APIs to traverse, open, search for, read, and close raw files. This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use Rawfile APIs to perform operations such as traversing the file list, opening, searching for, reading, and closing raw files.
## Available APIs ## Available APIs
| API | Description | | Name | Description |
| :----------------------------------------------------------- | :--------------------------------------- | | :----------------------------------------------------------- | :--------------------------------------- |
| NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | Initializes the native resource manager. | | NativeResourceManager *OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr) | Initializes the native resource manager. |
| RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | Opens a raw file directory. | | RawDir *OH_ResourceManager_OpenRawDir(const NativeResourceManager *mgr, const char *dirName) | Opens a raw file directory. |
...@@ -27,60 +25,289 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -27,60 +25,289 @@ This document describes how to use the native Rawfile APIs to manage raw file di
## How to Develop ## How to Develop
1. Add the header file. The following describes how to obtain the raw file list, raw file content, and raw file descriptor on the JavaScript side as an example.
1. Create a project.
![Creating a C++ application](figures/rawfile1.png)
2. Add dependencies.
After a project is created, the **cpp** directory is created under the project. The directory contains files such as **libentry/index.d.ts**, **hello.cpp**, and **CMakeLists.txt**.
1. Open the **src/main/cpp/CMakeLists.txt** file, and add **librawfile.z.so** and **libhilog_ndk.z.so** to **target_link_libraries**.
```c++ ```c++
#include "raw_file_manager.h" target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so)
``` ```
2. Open the **src/main/cpp/types/libentry/index.d.ts** file, and declare the application functions **getFileList**, **getRawFileContent**, and **getRawFileDescriptor**.
```c++
import resourceManager from '@ohos.resourceManager';
export const getFileList: (resmgr: resourceManager.ResourceManager, path: string) => Array<String>;
export const getRawFileContent: (resmgr: resourceManager.ResourceManager, path: string) => Uint8Array;
export const getRawFileDescriptor: (resmgr: resourceManager.ResourceManager, path: string) => resourceManager.RawFileDescriptor;
```
2. Call **OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)** to obtain a **NativeResourceManager** instance. 3. Modify the source file.
```js 1. Open the **src/main/cpp/hello.cpp** file. During initialization, the file maps the external JavaScript APIs **getFileList**, **getRawFileContent**, and **getRawFileDescriptor** to C++ native APIs **GetFileList**, **GetRawFileContent**, and **GetRawFileDescriptor**.
// Import the JS resource manager from the JS head file and pass it to the C++ file.
import resManager from '@ohos.resourceManager'
import rawfileTest from 'librawFileTest.so'
resManager.getResourceManager().then(resmgr => {
rawfileTest.testRawFile("test", resmgr, (error, value) => {
console.log("test rawFile");
})
});
```
```c++ ```c++
// Obtain and parse the parameters in the C++ file. EXTERN_C_START
NativeResourceManager* nativeResourceManager = nullptr; static napi_value Init(napi_env env, napi_value exports)
std::string path; {
if (i == 0 && valueType == napi_string) { napi_property_descriptor desc[] = {
// Parse the first parameter, which is the file or directory path relative to the raw file directory. { "getFileList", nullptr, GetFileList, nullptr, nullptr, nullptr, napi_default, nullptr },
...... { "getRawFileContent", nullptr, GetRawFileContent, nullptr, nullptr, nullptr, napi_default, nullptr },
path = buf.data(); { "getRawFileDescriptor", nullptr, GetRawFileDescriptor, nullptr, nullptr, nullptr, napi_default, nullptr }
} else if (i == 1 && valueType == napi_object) { };
// Parse the second parameter, which is the JS resource manager.
nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]); napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
} }
EXTERN_C_END
``` ```
2. Add the three functions to the **src/main/cpp/hello.cpp** file.
```c++
static napi_value GetFileList(napi_env env, napi_callback_info info)
static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)
```
3. Call **OH_ResourceManager_OpenRawDir** to obtain a **RawDir** instance based on the **NativeResourceManager** instance. 3. Obtain JavaScript resource objects from the **hello.cpp** file, and convert them to native resource objects. Then, call the native APIs to obtain the raw file list, raw file content, and raw file descriptor {fd, offset, length}. The sample code is as follows:
```c++ ```c++
RawDir* rawDir = OH_ResourceManager_OpenRawDir(nativeResourceManager, path.c_str()); // Example 1: Use GetFileList to obtain the raw file list.
static napi_value GetFileList(napi_env env, napi_callback_info info)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest Begin");
size_t requireArgc = 3;
size_t argc = 2;
napi_value argv[2] = { nullptr };
// Obtain arguments of the native API.
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
// Obtain argv[0], which specifies conversion of the JavaScript resource object (that is, OH_ResourceManager_InitNativeResourceManager) to a native object.
NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
// Obtain argv[1], which specifies the relative path of the raw file.
size_t strSize;
char strBuf[256];
napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
std::string dirName(strBuf, strSize);
// Obtain the corresponding rawDir pointer object.
RawDir* rawDir = OH_ResourceManager_OpenRawDir(mNativeResMgr, dirName.c_str());
// Obtain the number of files and folders in rawDir.
int count = OH_ResourceManager_GetRawFileCount(rawDir);
// Traverse rawDir to obtain the list of file names and save it.
std::vector<std::string> tempArray;
for(int i = 0; i < count; i++) {
std::string filename = OH_ResourceManager_GetRawFileName(rawDir, i);
tempArray.emplace_back(filename);
}
napi_value fileList;
napi_create_array(env, &fileList);
for (size_t i = 0; i < tempArray.size(); i++) {
napi_value jsString;
napi_create_string_utf8(env, tempArray[i].c_str(), NAPI_AUTO_LENGTH, &jsString);
napi_set_element(env, fileList, i, jsString);
}
// Close the rawDir pointer object.
OH_ResourceManager_CloseRawDir(rawDir);
OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
return fileList;
}
// Example 2: Use rawDir pointer object to obtain the content of the raw file.
napi_value CreateJsArrayValue(napi_env env, std::unique_ptr<uint8_t[]> &data, long length)
{
napi_value buffer;
napi_status status = napi_create_external_arraybuffer(env, data.get(), length,
[](napi_env env, void *data, void *hint) {
delete[] static_cast<char*>(data);
}, nullptr, &buffer);
if (status != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create external array buffer");
return nullptr;
}
napi_value result = nullptr;
status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result);
if (status != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "Failed to create media typed array");
return nullptr;
}
data.release();
return result;
}
static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "GetFileContent Begin");
size_t requireArgc = 3;
size_t argc = 2;
napi_value argv[2] = { nullptr };
// Obtain arguments of the native API.
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
// Obtain argv[0], which specifies conversion of the JavaScript resource object (that is, OH_ResourceManager_InitNativeResourceManager) to a native object.
NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
size_t strSize;
char strBuf[256];
napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
std::string filename(strBuf, strSize);
// Obtain the raw file pointer object.
RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
if (rawFile != nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success");
}
// Obtain the size of the raw file and apply for memory.
long len = OH_ResourceManager_GetRawFileSize(rawFile);
std::unique_ptr<uint8_t[]> data= std::make_unique<uint8_t[]>(len);
// Read the raw file.
int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len);
// Close the raw file pointer object.
OH_ResourceManager_CloseRawFile(rawFile);
OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
// Convert the native object to a JavaScript object.
return CreateJsArrayValue(env, data, len);
}
// Example 3: Use GetRawFileDescriptor to obtain the FD of the raw file.
napi_value createJsFileDescriptor(napi_env env, RawFileDescriptor &descriptor)
{
napi_value result;
napi_status status = napi_create_object(env, &result);
if (status != napi_ok) {
return result;
}
napi_value fd;
status = napi_create_int32(env, descriptor.fd, &fd);
if (status != napi_ok) {
return result;
}
status = napi_set_named_property(env, result, "fd", fd);
if (status != napi_ok) {
return result;
}
napi_value offset;
status = napi_create_int64(env, descriptor.start, &offset);
if (status != napi_ok) {
return result;
}
status = napi_set_named_property(env, result, "offset", offset);
if (status != napi_ok) {
return result;
}
napi_value length;
status = napi_create_int64(env, descriptor.length, &length);
if (status != napi_ok) {
return result;
}
status = napi_set_named_property(env, result, "length", length);
if (status != napi_ok) {
return result;
}
return result;
}
static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "NDKTest GetRawFileDescriptor Begin");
size_t requireArgc = 3;
size_t argc = 2;
napi_value argv[2] = { nullptr };
// Obtain arguments of the native API.
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
napi_valuetype valueType;
napi_typeof(env, argv[0], &valueType);
// Obtain the native resourceManager object.
NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
size_t strSize;
char strBuf[256];
napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
std::string filename(strBuf, strSize);
// Obtain the raw file pointer object.
RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str());
if (rawFile != nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "OH_ResourceManager_OpenRawFile success");
}
// Obtain the FD of the raw file, that is, RawFileDescriptor {fd, offset, length}.
RawFileDescriptor descriptor;
OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
// Close the raw file pointer object.
OH_ResourceManager_CloseRawFile(rawFile);
OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
// Convert the native object to a JavaScript object.
return createJsFileDescriptor(env,descriptor);
}
``` ```
4. Call APIs on the JavaScript side.
1. Open **src\main\ets\pages\index.ets**, and import **libentry.so**.
2. Obtain the JavaScript resource object, that is, **resourceManager**.
4. Call **OH_ResourceManager_GetRawFileCount** to obtain the total number of raw files in the directory based on the **RawDir** instance. 3. Call **getFileList**, that is, the native API declared in **src/main/cpp/types/libentry/index.d.ts**. When calling the API, pass the JavaScript resource object and the relative path of the raw file. The sample code is as follows:
```js
import hilog from '@ohos.hilog';
import testNapi from 'libentry.so' // Import the libentry.so file.
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
private resmgr = getContext().resourceManager; // Obtain the JavaScript resource object.
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
let rawfilelist = testNapi.getFileList(this.resmgr, ""); // Pass the JavaScript resource object and the relative path of the raw file.
console.log("rawfilelist" + rawfilelist);
let rawfileContet = testNapi.getRawFileContent(this.resmgr, "rawfile1.txt");
console.log("rawfileContet" + rawfileContet);
let rawfileDescriptor = testNapi.getRawFileDescriptor(this.resmgr, "rawfile1.txt");
console.log("getRawFileDescriptor" + rawfileDescriptor.fd, rawfileDescriptor.offset, rawfileDescriptor.length);
})
}
.width('100%')
}
.height('100%')
}
}
```
## Using C++ Functions
1. Call **OH_ResourceManager_OpenRawDir** to obtain a **RawDir** instance based on the **NativeResourceManager** instance.
```c++ ```c++
int count = OH_ResourceManager_GetRawFileCount(rawDir); RawDir* rawDir = OH_ResourceManager_OpenRawDir(nativeResourceManager, path.c_str());
``` ```
2. Call **OH_ResourceManager_GetRawFileCount** to obtain the total number of raw files in the directory based on the **RawDir** instance.
```c++
int count = OH_ResourceManager_GetRawFileCount(rawDir);
```
5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index. 3. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index.
```c++ ```c++
for (int index = 0; index < count; index++) { for (int index = 0; index < count; index++) {
...@@ -88,25 +315,19 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -88,25 +315,19 @@ This document describes how to use the native Rawfile APIs to manage raw file di
} }
``` ```
4. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name.
6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name.
```c++ ```c++
RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str()); RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str());
``` ```
5. Call **OH_ResourceManager_GetRawFileSize** to obtain the size of the raw file.
7. Call **OH_ResourceManager_GetRawFileSize** to obtain the size of the raw file.
```c++ ```c++
long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile); long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile);
``` ```
6. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset.
8. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset.
```c++ ```c++
int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0); int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0);
...@@ -114,59 +335,45 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -114,59 +335,45 @@ This document describes how to use the native Rawfile APIs to manage raw file di
int position = OH_ResourceManager_SeekRawFile(rawFile, -10, 2); int position = OH_ResourceManager_SeekRawFile(rawFile, -10, 2);
``` ```
7. Call **OH_ResourceManager_GetRawFileOffset** to obtain the raw file offset.
9. Call **OH_ResourceManager_GetRawFileOffset** to obtain the raw file offset.
```c++ ```c++
long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile) long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile)
``` ```
8. Call **OH_ResourceManager_ReadRawFile** to read the raw file.
10. Call **OH_ResourceManager_ReadRawFile** to read the raw file.
```c++ ```c++
std::unique_ptr<char[]> mediaData = std::make_unique<char[]>(rawFileSize); std::unique_ptr<char[]> mediaData = std::make_unique<char[]>(rawFileSize);
long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, mediaData.get(), rawFileSize); long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, mediaData.get(), rawFileSize);
``` ```
9. Call **OH_ResourceManager_CloseRawFile** to close the file to release resources.
11. Call **OH_ResourceManager_CloseRawFile** to close the file to release resources.
```c++ ```c++
OH_ResourceManager_CloseRawFile(rawFile); OH_ResourceManager_CloseRawFile(rawFile);
``` ```
10. Call **OH_ResourceManager_CloseRawDir** to close the raw file directory.
12. Call **OH_ResourceManager_CloseRawDir** to close the raw file directory.
```c++ ```c++
OH_ResourceManager_CloseRawDir(rawDir); OH_ResourceManager_CloseRawDir(rawDir);
``` ```
11. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file.
13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file.
```c++ ```c++
RawFileDescriptor descriptor; RawFileDescriptor descriptor;
bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor); bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);
``` ```
12. Call **OH_ResourceManager_ReleaseRawFileDescriptor** to release the FD of the raw file.
14. Call **OH_ResourceManager_ReleaseRawFileDescriptor** to release the FD of the raw file.
```c++ ```c++
OH_ResourceManager_ReleaseRawFileDescriptor(descriptor); OH_ResourceManager_ReleaseRawFileDescriptor(descriptor);
``` ```
13. Call **OH_ResourceManager_ReleaseNativeResourceManager** to release the native resource manager.
15. Call **OH_ResourceManager_ReleaseNativeResourceManager** to release the native resource manager.
```c++ ```c++
OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager); OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager);
......
...@@ -237,7 +237,7 @@ ...@@ -237,7 +237,7 @@
- [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md) - [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md)
- [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md) - [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md)
- [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md) - [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md)
- [@ohos.file.fileUri (File URI)](js-apis-file-fileUri.md) - [@ohos.file.fileuri (File URI)](js-apis-file-fileuri.md)
- [@ohos.file.fs (File Management)](js-apis-file-fs.md) - [@ohos.file.fs (File Management)](js-apis-file-fs.md)
- [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md) - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md)
- [@ohos.file.picker (File Picker)](js-apis-file-picker.md) - [@ohos.file.picker (File Picker)](js-apis-file-picker.md)
......
...@@ -53,10 +53,10 @@ let want = { ...@@ -53,10 +53,10 @@ let want = {
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}; };
abilityDelegator.startAbility(want, (err) => { abilityDelegator.startAbility(want, (err) => {
if (!err || err.code === 0) { if (err) {
console.log('Success start ability.');
} else {
console.error('Failed start ability, error: ${JSON.stringify(err)}'); console.error('Failed start ability, error: ${JSON.stringify(err)}');
} else {
console.log('Success start ability.');
} }
}); });
``` ```
......
...@@ -40,7 +40,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -40,7 +40,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager'; import appManager from '@ohos.app.ability.appManager';
appManager.isRunningInStabilityTest((err, flag) => { appManager.isRunningInStabilityTest((err, flag) => {
if (err && err.code !== 0) { if (err) {
console.error('isRunningInStabilityTest fail, err: ${JSON.stringify(err)}'); console.error('isRunningInStabilityTest fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}'); console.log('The result of isRunningInStabilityTest is: ${JSON.stringify(flag)}');
...@@ -146,7 +146,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -146,7 +146,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager'; import appManager from '@ohos.app.ability.appManager';
appManager.isRamConstrainedDevice((err, data) => { appManager.isRamConstrainedDevice((err, data) => {
if (err && err.code !== 0) { if (err) {
console.error('isRamConstrainedDevice fail, err: ${JSON.stringify(err)}'); console.error('isRamConstrainedDevice fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}'); console.log('The result of isRamConstrainedDevice is: ${JSON.stringify(data)}');
...@@ -216,7 +216,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -216,7 +216,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager'; import appManager from '@ohos.app.ability.appManager';
appManager.getAppMemorySize((err, data) => { appManager.getAppMemorySize((err, data) => {
if (err && err.code !== 0) { if (err) {
console.error('getAppMemorySize fail, err: ${JSON.stringify(err)}'); console.error('getAppMemorySize fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('The size of app memory is: ${JSON.stringify(data)}'); console.log('The size of app memory is: ${JSON.stringify(data)}');
...@@ -290,7 +290,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -290,7 +290,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager'; import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation((err, data) => { appManager.getRunningProcessInformation((err, data) => {
if (err && err.code !== 0) { if (err) {
console.error('getRunningProcessInformation fail, err: ${JSON.stringify(err)}'); console.error('getRunningProcessInformation fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('The process running information is: ${JSON.stringify(data)}'); console.log('The process running information is: ${JSON.stringify(data)}');
...@@ -489,7 +489,7 @@ try { ...@@ -489,7 +489,7 @@ try {
// 2. Deregister the application state observer. // 2. Deregister the application state observer.
function unregisterApplicationStateObserverCallback(err) { function unregisterApplicationStateObserverCallback(err) {
if (err && err.code !== 0) { if (err) {
console.error('unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}'); console.error('unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('unregisterApplicationStateObserverCallback success.'); console.log('unregisterApplicationStateObserverCallback success.');
...@@ -612,7 +612,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error ...@@ -612,7 +612,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
import appManager from '@ohos.app.ability.appManager'; import appManager from '@ohos.app.ability.appManager';
function getForegroundApplicationsCallback(err, data) { function getForegroundApplicationsCallback(err, data) {
if (err && err.code !== 0) { if (err) {
console.error('getForegroundApplicationsCallback fail, err: ${JSON.stringify(err)}'); console.error('getForegroundApplicationsCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('getForegroundApplicationsCallback success, data: ${JSON.stringify(data)}'); console.log('getForegroundApplicationsCallback success, data: ${JSON.stringify(data)}');
...@@ -745,7 +745,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -745,7 +745,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName'; let bundleName = 'bundleName';
let accountId = 0; let accountId = 0;
function killProcessWithAccountCallback(err, data) { function killProcessWithAccountCallback(err, data) {
if (err && err.code !== 0) { if (err) {
console.error('killProcessWithAccountCallback fail, err: ${JSON.stringify(err)}'); console.error('killProcessWithAccountCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('killProcessWithAccountCallback success.'); console.log('killProcessWithAccountCallback success.');
...@@ -788,7 +788,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -788,7 +788,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName'; let bundleName = 'bundleName';
function killProcessesByBundleNameCallback(err, data) { function killProcessesByBundleNameCallback(err, data) {
if (err && err.code !== 0) { if (err) {
console.error('killProcessesByBundleNameCallback fail, err: ${JSON.stringify(err)}'); console.error('killProcessesByBundleNameCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('killProcessesByBundleNameCallback success.'); console.log('killProcessesByBundleNameCallback success.');
...@@ -884,7 +884,7 @@ import appManager from '@ohos.app.ability.appManager'; ...@@ -884,7 +884,7 @@ import appManager from '@ohos.app.ability.appManager';
let bundleName = 'bundleName'; let bundleName = 'bundleName';
function clearUpApplicationDataCallback(err, data) { function clearUpApplicationDataCallback(err, data) {
if (err && err.code !== 0) { if (err) {
console.error('clearUpApplicationDataCallback fail, err: ${JSON.stringify(err)}'); console.error('clearUpApplicationDataCallback fail, err: ${JSON.stringify(err)}');
} else { } else {
console.log('clearUpApplicationDataCallback success.'); console.log('clearUpApplicationDataCallback success.');
......
...@@ -23,7 +23,7 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; ...@@ -23,7 +23,7 @@ import distributedKVStore from '@ohos.data.distributedKVStore';
## KVManagerConfig ## KVManagerConfig
Defines the **KVManager** instance configuration, including the bundle name of the invoker and the application context. Provides the **KVManager** instance configuration, including the bundle name of the invoker and the application context.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core **System capability**: SystemCapability.DistributedDataManager.KVStore.Core
...@@ -127,7 +127,7 @@ Enumerates the distributed KV store types. ...@@ -127,7 +127,7 @@ Enumerates the distributed KV store types.
| Name | Description | | Name | Description |
| -------------------- | ------------------------------------------------------------ | | -------------------- | ------------------------------------------------------------ |
| DEVICE_COLLABORATION | Device KV store.<br>The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | | DEVICE_COLLABORATION | Device KV store.<br>The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
| SINGLE_VERSION | Single KV store.<br>The single KV store does not differentiate data by device. If entries with the same key are modified on different devices, the value will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | SINGLE_VERSION | Single KV store.<br>The single KV store does not differentiate data by device. If entries with the same key are modified on different devices, the value will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
## SecurityLevel ## SecurityLevel
...@@ -2028,7 +2028,7 @@ try { ...@@ -2028,7 +2028,7 @@ try {
deviceId(deviceId:string):Query deviceId(deviceId:string):Query
Creates a **Query** object with the device ID as the key prefix. Creates a **Query** object with the device ID as the key prefix.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -2817,7 +2817,7 @@ try { ...@@ -2817,7 +2817,7 @@ try {
removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void
Deletes data of a device. This API uses an asynchronous callback to return the result. Deletes data of a device. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -2869,7 +2869,7 @@ try { ...@@ -2869,7 +2869,7 @@ try {
removeDeviceData(deviceId: string): Promise&lt;void&gt; removeDeviceData(deviceId: string): Promise&lt;void&gt;
Deletes data of a device. This API uses a promise to return the result. Deletes data of a device. This API uses a promise to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -4548,7 +4548,7 @@ try { ...@@ -4548,7 +4548,7 @@ try {
sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md).
> **NOTE**<br/> > **NOTE**
> >
> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
...@@ -4617,7 +4617,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => { ...@@ -4617,7 +4617,7 @@ deviceManager.createDeviceManager('bundleName', (err, value) => {
sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void
Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md).
> **NOTE**<br/> > **NOTE**
> >
> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
...@@ -4735,7 +4735,7 @@ Subscribes to synchronization complete events. ...@@ -4735,7 +4735,7 @@ Subscribes to synchronization complete events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ |
| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| | event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.|
| syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes | Callback invoked to return the synchronization complete event. | | syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes | Callback invoked to return the synchronization complete event.|
**Example** **Example**
...@@ -4769,7 +4769,7 @@ Unsubscribes from data changes. ...@@ -4769,7 +4769,7 @@ Unsubscribes from data changes.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | | -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- |
| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| | event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.|
| listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | No | Callback for data changes. | | listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | No | Callback for the data change event. |
**Error codes** **Error codes**
...@@ -5044,7 +5044,7 @@ try { ...@@ -5044,7 +5044,7 @@ try {
get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void
Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -5099,7 +5099,7 @@ try { ...@@ -5099,7 +5099,7 @@ try {
get(deviceId: string, key: string): Promise&lt;boolean | string | number | Uint8Array&gt; get(deviceId: string, key: string): Promise&lt;boolean | string | number | Uint8Array&gt;
Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -5279,7 +5279,7 @@ try { ...@@ -5279,7 +5279,7 @@ try {
getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void
Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -5346,7 +5346,7 @@ try { ...@@ -5346,7 +5346,7 @@ try {
getEntries(deviceId: string, keyPrefix: string): Promise&lt;Entry[]&gt; getEntries(deviceId: string, keyPrefix: string): Promise&lt;Entry[]&gt;
Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -5542,7 +5542,7 @@ try { ...@@ -5542,7 +5542,7 @@ try {
getEntries(deviceId: string, query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void getEntries(deviceId: string, query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void
Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -5614,7 +5614,7 @@ try { ...@@ -5614,7 +5614,7 @@ try {
getEntries(deviceId: string, query: Query): Promise&lt;Entry[]&gt; getEntries(deviceId: string, query: Query): Promise&lt;Entry[]&gt;
Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -5822,7 +5822,7 @@ try { ...@@ -5822,7 +5822,7 @@ try {
getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void
Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -5877,7 +5877,7 @@ try { ...@@ -5877,7 +5877,7 @@ try {
getResultSet(deviceId: string, keyPrefix: string): Promise&lt;KVStoreResultSet&gt; getResultSet(deviceId: string, keyPrefix: string): Promise&lt;KVStoreResultSet&gt;
Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -5933,7 +5933,7 @@ try { ...@@ -5933,7 +5933,7 @@ try {
getResultSet(deviceId: string, query: Query, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void getResultSet(deviceId: string, query: Query, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void
Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -6009,7 +6009,7 @@ try { ...@@ -6009,7 +6009,7 @@ try {
getResultSet(deviceId: string, query: Query): Promise&lt;KVStoreResultSet&gt; getResultSet(deviceId: string, query: Query): Promise&lt;KVStoreResultSet&gt;
Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -6152,7 +6152,7 @@ try { ...@@ -6152,7 +6152,7 @@ try {
getResultSet(query: Query, callback:AsyncCallback&lt;KVStoreResultSet&gt;): void getResultSet(query: Query, callback:AsyncCallback&lt;KVStoreResultSet&gt;): void
Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result. Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -6341,7 +6341,7 @@ try { ...@@ -6341,7 +6341,7 @@ try {
getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void
Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -6402,7 +6402,7 @@ try { ...@@ -6402,7 +6402,7 @@ try {
getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise&lt;KVStoreResultSet&gt; getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise&lt;KVStoreResultSet&gt;
Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -6583,7 +6583,7 @@ try { ...@@ -6583,7 +6583,7 @@ try {
getResultSize(deviceId: string, query: Query, callback: AsyncCallback&lt;number&gt;): void; getResultSize(deviceId: string, query: Query, callback: AsyncCallback&lt;number&gt;): void;
Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -6650,7 +6650,7 @@ try { ...@@ -6650,7 +6650,7 @@ try {
getResultSize(deviceId: string, query: Query): Promise&lt;number&gt; getResultSize(deviceId: string, query: Query): Promise&lt;number&gt;
Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result.
> **NOTE**<br/> > **NOTE**
> >
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. > **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync). > For details about how to obtain **deviceId**, see [sync()](#sync).
...@@ -6712,4 +6712,3 @@ try { ...@@ -6712,4 +6712,3 @@ try {
console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`); console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`);
} }
``` ```
<!--no_check-->
\ No newline at end of file
...@@ -29,7 +29,7 @@ Creates a **Filter** instance based on the pixel map. ...@@ -29,7 +29,7 @@ Creates a **Filter** instance based on the pixel map.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ----------------- | ---- | -------- | | ------- | ----------------- | ---- | -------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module. | | source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module. An instance can be obtained by decoding an image or directly created. For details, see [Image Overview](../../media/image-overview.md). |
**Return value** **Return value**
...@@ -61,7 +61,7 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses a promi ...@@ -61,7 +61,7 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses a promi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | -------------------------- | | -------- | ----------- | ---- | -------------------------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module.| | source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | **PixelMap** instance created by the image module. An instance can be obtained by decoding an image or directly created. For details, see [Image Overview](../../media/image-overview.md).|
**Return value** **Return value**
...@@ -95,7 +95,7 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses an asyn ...@@ -95,7 +95,7 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses an asyn
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | -------------------------- | | -------- | ------------------ | ---- | -------------------------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes |**PixelMap** instance created by the image module. | | source | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes |**PixelMap** instance created by the image module. An instance can be obtained by decoding an image or directly created. For details, see [Image Overview](../../media/image-overview.md). |
| callback | AsyncCallback\<[ColorPicker](#colorpicker)> | Yes | Callback used to return the **ColorPicker** instance created.| | callback | AsyncCallback\<[ColorPicker](#colorpicker)> | Yes | Callback used to return the **ColorPicker** instance created.|
**Example** **Example**
......
# @ohos.enterprise.accountManager (Account Management) # @ohos.enterprise.accountManager (Account Management)
The **accountManager** module provides account management capabilities for enterprise devices. Only the enterprise device administrator applications can call the APIs provided by this module. The **accountManager** module provides APIs for account management of enterprise devices. Only the device administrator applications can call the APIs provided by this module.
> **NOTE** > **NOTE**
> >
...@@ -16,7 +16,7 @@ import accountManager from '@ohos.enterprise.accountManager'; ...@@ -16,7 +16,7 @@ import accountManager from '@ohos.enterprise.accountManager';
disallowAddLocalAccount(admin: Want, disallow: boolean, callback: AsyncCallback&lt;void&gt;): void disallowAddLocalAccount(admin: Want, disallow: boolean, callback: AsyncCallback&lt;void&gt;): void
Disallows local accounts. This API uses an asynchronous callback to return the result. Forbids a device administrator application to create local user accounts. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY **Required permissions**: ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY
...@@ -28,8 +28,8 @@ Disallows local accounts. This API uses an asynchronous callback to return the r ...@@ -28,8 +28,8 @@ Disallows local accounts. This API uses an asynchronous callback to return the r
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------- | | -------- | ---------------------------------------- | ---- | ------------------------------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | | admin | [Want](js-apis-app-ability-want.md) | Yes | Enterprise device administrator application. |
| disallow | boolean | Yes | Whether to disallow local accounts. The value **true** means disallow local accounts; the value **false** means the opposite. | | disallow | boolean | Yes | Whether to forbid the creation of local user accounts. The value **true** means that local user accounts cannot be created; the value **false** means the opposite. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. |
**Error codes** **Error codes**
...@@ -59,7 +59,7 @@ accountManager.disallowAddLocalAccount(admin, true, (error) => { ...@@ -59,7 +59,7 @@ accountManager.disallowAddLocalAccount(admin, true, (error) => {
disallowAddLocalAccount(admin: Want, disallow: boolean): Promise&lt;void&gt; disallowAddLocalAccount(admin: Want, disallow: boolean): Promise&lt;void&gt;
Disallows local accounts. This API uses a promise to return the result. Forbids a device administrator application to create local user accounts. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY **Required permissions**: ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY
...@@ -71,14 +71,14 @@ Disallows local accounts. This API uses a promise to return the result. ...@@ -71,14 +71,14 @@ Disallows local accounts. This API uses a promise to return the result.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- | | ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| | admin | [Want](js-apis-app-ability-want.md) | Yes | Enterprise device administrator application.|
| disallow | boolean | Yes | Whether to disallow local accounts. The value **true** means disallow local accounts; the value **false** means the opposite. | | disallow | boolean | Yes | Whether to forbid the creation of local user accounts. The value **true** means that local user accounts cannot be created; the value **false** means the opposite. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------------------- | | --------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. | | Promise&lt;void&gt; | Promise that returns no value. An error object will be thrown if the operation fails.|
**Error codes** **Error codes**
...@@ -86,8 +86,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes ...@@ -86,8 +86,8 @@ For details about the error codes, see [Enterprise Device Management Error Codes
| ID| Error Message | | ID| Error Message |
| ------- | ---------------------------------------------------------------------------- | | ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. | | 9200001 | The application is not an administrator application of the device. |
| 9200002 | the administrator application does not have permission to manage the device. | | 9200002 | The administrator application does not have permission to manage the device.|
**Example** **Example**
......
# @ohos.enterprise.dateTimeManager (System Time Management) # @ohos.enterprise.dateTimeManager (System Time Management)
The **dateTimeManager** module provides APIs for system time management, which can only be called by device administrator applications. The **dateTimeManager** module provides APIs for system time management. Only the enterprise device administrator applications can call the APIs provided by this module.
> **NOTE** > **NOTE**
> >
...@@ -30,7 +30,7 @@ Sets the system time. This API uses an asynchronous callback to return the resul ...@@ -30,7 +30,7 @@ Sets the system time. This API uses an asynchronous callback to return the resul
| ----- | ----------------------------------- | ---- | ------- | | ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| | admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| time | number | Yes| Timestamp (ms).| | time | number | Yes| Timestamp (ms).|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the setting is successful, **err** is **null**. Otherwise, **err** is an error object.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -101,3 +101,181 @@ dateTimeManager.setDateTime(wantTemp, 1526003846000).then(() => { ...@@ -101,3 +101,181 @@ dateTimeManager.setDateTime(wantTemp, 1526003846000).then(() => {
console.log("error code:" + error.code + " error message:" + error.message); console.log("error code:" + error.code + " error message:" + error.message);
}) })
``` ```
## dateTimeManager.disallowModifyDateTime<sup>10+</sup>
disallowModifyDateTime(admin: Want, disallow: boolean, callback: AsyncCallback\<void>): void
Disables modification of the system time. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| disallow | boolean | Yes| Whether to disable modification of the system time. The value **true** means to disable modification of the system time, and **false** means the opposite.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
dateTimeManager.disallowModifyDateTime(wantTemp, true, (error) => {
if (error) {
console.log("error code:" + error.code + " error message:" + error.message);
}
})
```
## dateTimeManager.disallowModifyDateTime<sup>10+</sup>
disallowModifyDateTime(admin: Want, disallow: boolean): Promise\<void>
Disables modification of the system time. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| disallow | boolean | Yes| Whether to disable modification of the system time. The value **true** means to disable modification of the system time, and **false** means the opposite.|
**Return value**
| Type | Description |
| ----- | ----------------------------------- |
| Promise\<void> | that returns no value. If the operation fails, an error object is thrown.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
dateTimeManager.disallowModifyDateTime(wantTemp, true).then(() => {
}).catch((error) => {
console.log("error code:" + error.code + " error message:" + error.message);
})
```
## dateTimeManager.isModifyDateTimeDisallowed<sup>10+</sup>
isModifyDateTimeDisallowed(admin: Want, callback: AsyncCallback\<boolean>): void
Checks whether modification of the system time is disabled. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| callback | AsyncCallback\<boolean> | Yes| Callback used to return the result. The value **true** means that modification of the system time is disabled, and **false** means the opposite.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
dateTimeManager.isModifyDateTimeDisallowed(wantTemp, (error) => {
if (error) {
console.log("error code:" + error.code + " error message:" + error.message);
}
})
```
## dateTimeManager.isModifyDateTimeDisallowed<sup>10+</sup>
isModifyDateTimeDisallowed(admin: Want): Promise\<boolean>
Checks whether modification of the system time is disabled. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
**Return value**
| Type | Description |
| ----- | ----------------------------------- |
| Promise\<boolean> | Promise Promise used to return the result. The value **true** means that modification of the system time is disabled, and **false** means the opposite.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
dateTimeManager.disallowModifyDateTime(wantTemp).then(() => {
}).catch((error) => {
console.log("error code:" + error.code + " error message:" + error.message);
})
```
# @ohos.enterprise.networkManager (Network Management) # @ohos.enterprise.networkManager (Network Management)
The **networkManager** module provides network management capabilities for enterprise devices, including obtaining the device IP address and MAC address. Only the enterprise device administrator applications can call the APIs provided by this module. The **networkManager** module provides APIs for network management of enterprise devices, including obtaining the device IP address and MAC address. Only the device administrator applications can call the APIs provided by this module.
> **NOTE** > **NOTE**
> >
...@@ -16,7 +16,7 @@ import networkManager from '@ohos.enterprise.networkManager'; ...@@ -16,7 +16,7 @@ import networkManager from '@ohos.enterprise.networkManager';
getAllNetworkInterfaces(admin: Want, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void getAllNetworkInterfaces(admin: Want, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Obtains all active network interfaces. This API uses an asynchronous callback to return the result. Obtains all active network interfaces through a device administrator application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_NETWORK_INFO **Required permissions**: ohos.permission.GET_NETWORK_INFO
...@@ -28,8 +28,8 @@ Obtains all active network interfaces. This API uses an asynchronous callback to ...@@ -28,8 +28,8 @@ Obtains all active network interfaces. This API uses an asynchronous callback to
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------- | | -------- | ---------------------------------------- | ---- | ------------------------------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | | admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application that obtains the information. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the active network interfaces obtained. | | callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is an array of network interfaces obtained. If the operation fails, **err** is an error object. |
**Error codes** **Error codes**
...@@ -60,7 +60,7 @@ networkManager.getAllNetworkInterfaces(admin, (error, result) => { ...@@ -60,7 +60,7 @@ networkManager.getAllNetworkInterfaces(admin, (error, result) => {
getAllNetworkInterfaces(admin: Want): Promise&lt;Array&lt;string&gt;&gt; getAllNetworkInterfaces(admin: Want): Promise&lt;Array&lt;string&gt;&gt;
Obtains all active network interfaces. This API uses a promise to return the result. Obtains all active network interfaces through a device administrator application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO **Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO
...@@ -72,13 +72,13 @@ Obtains all active network interfaces. This API uses a promise to return the res ...@@ -72,13 +72,13 @@ Obtains all active network interfaces. This API uses a promise to return the res
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- | | ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| | admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application that obtains the information.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------------------- | | --------------------- | ------------------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the active network interfaces obtained. | | Promise&lt;Array&lt;string&gt;&gt; | Promise used to return an array of network interfaces obtained. |
**Error codes** **Error codes**
...@@ -107,7 +107,7 @@ networkManager.getAllNetworkInterfaces(wantTemp).then((result) => { ...@@ -107,7 +107,7 @@ networkManager.getAllNetworkInterfaces(wantTemp).then((result) => {
getIpAddress(admin: Want, networkInterface: string, callback: AsyncCallback&lt;string&gt;): void getIpAddress(admin: Want, networkInterface: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the IP address of a device. This API uses an asynchronous callback to return the result. Obtains the device IP address based on the given network interface through a device administrator application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_NETWORK_INFO **Required permissions**: ohos.permission.GET_NETWORK_INFO
...@@ -119,9 +119,9 @@ Obtains the IP address of a device. This API uses an asynchronous callback to re ...@@ -119,9 +119,9 @@ Obtains the IP address of a device. This API uses an asynchronous callback to re
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------- | | -------- | ---------------------------------------- | ---- | ------------------------------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | | admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application that obtains the information. |
| networkInterface | string | Yes | Network interface. | | networkInterface | string | Yes | Network interface. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the device IP address obtained. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the IP address obtained. If the operation fails, **err** is an error object. |
**Error codes** **Error codes**
...@@ -152,7 +152,7 @@ networkManager.getIpAddress(wantTemp, "eth0", (error, result) => { ...@@ -152,7 +152,7 @@ networkManager.getIpAddress(wantTemp, "eth0", (error, result) => {
getIpAddress(admin: Want, networkInterface: string): Promise&lt;string&gt; getIpAddress(admin: Want, networkInterface: string): Promise&lt;string&gt;
Obtains the IP address of a device. This API uses a promise to return the result. Obtains the device IP address based on the given network interface through a device administrator application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO **Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO
...@@ -164,7 +164,7 @@ Obtains the IP address of a device. This API uses a promise to return the result ...@@ -164,7 +164,7 @@ Obtains the IP address of a device. This API uses a promise to return the result
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- | | ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| | admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application that obtains the information.|
| networkInterface | string | Yes | Network interface. | | networkInterface | string | Yes | Network interface. |
**Return value** **Return value**
...@@ -200,7 +200,7 @@ networkManager.getIpAddress(wantTemp, "eth0").then((result) => { ...@@ -200,7 +200,7 @@ networkManager.getIpAddress(wantTemp, "eth0").then((result) => {
getMac(admin: Want, networkInterface: string, callback: AsyncCallback&lt;string&gt;): void getMac(admin: Want, networkInterface: string, callback: AsyncCallback&lt;string&gt;): void
Obtains the MAC address of a device. This API uses an asynchronous callback to return the result. Obtains the device MAC address based on the given network interface through a device administrator application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO **Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO
...@@ -212,9 +212,9 @@ Obtains the MAC address of a device. This API uses an asynchronous callback to r ...@@ -212,9 +212,9 @@ Obtains the MAC address of a device. This API uses an asynchronous callback to r
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------- | | -------- | ---------------------------------------- | ---- | ------------------------------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | | admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application that obtains the information. |
| networkInterface | string | Yes | Network interface. | | networkInterface | string | Yes | Network interface. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the device MAC address obtained. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the MAC address obtained. If the operation fails, **err** is an error object. |
**Error codes** **Error codes**
...@@ -245,7 +245,7 @@ networkManager.getMac(wantTemp, "eth0", (error, result) => { ...@@ -245,7 +245,7 @@ networkManager.getMac(wantTemp, "eth0", (error, result) => {
getIpAddress(admin: Want, networkInterface: string): Promise&lt;string&gt; getIpAddress(admin: Want, networkInterface: string): Promise&lt;string&gt;
Obtains the MAC address of a device. This API uses a promise to return the result. Obtain the device MAC address based on the given network interface through a device administrator application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO **Required permissions**: ohos.permission.ENTERPRISE_GET_NETWORK_INFO
...@@ -257,7 +257,7 @@ Obtains the MAC address of a device. This API uses a promise to return the resul ...@@ -257,7 +257,7 @@ Obtains the MAC address of a device. This API uses a promise to return the resul
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- | | ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| | admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application that obtains the information.|
| networkInterface | string | Yes | Network interface. | | networkInterface | string | Yes | Network interface. |
**Return value** **Return value**
......
# @ohos.enterprise.wifiManager (Wi-Fi Management) # @ohos.enterprise.wifiManager (Wi-Fi Management)
The **wifiManager** module provides Wi-Fi management capabilities for enterprise devices. Only the enterprise device administrator applications can call the APIs provided by this module. The **wifiManager** module provides APIs for Wi-Fi management of enterprise devices. Only the device administrator applications can call the APIs provided by this module.
> **NOTE** > **NOTE**
> >
...@@ -16,7 +16,7 @@ import wifiManager from '@ohos.enterprise.wifiManager'; ...@@ -16,7 +16,7 @@ import wifiManager from '@ohos.enterprise.wifiManager';
isWifiActive(admin: Want, callback: AsyncCallback&lt;boolean&gt;): void isWifiActive(admin: Want, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether Wi-Fi is active. This API uses an asynchronous callback to return the result. Checks whether Wi-Fi is active through a device administrator application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_WIFI **Required permissions**: ohos.permission.ENTERPRISE_SET_WIFI
...@@ -60,7 +60,7 @@ wifiManager.isWifiActive(wantTemp, (error, result) => { ...@@ -60,7 +60,7 @@ wifiManager.isWifiActive(wantTemp, (error, result) => {
isWifiActive(admin: Want): Promise&lt;boolean&gt; isWifiActive(admin: Want): Promise&lt;boolean&gt;
Checks whether Wi-Fi is active. This API uses a promise to return the result. Checks whether Wi-Fi is active through a device administrator application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_SET_WIFI **Required permissions**: ohos.permission.ENTERPRISE_SET_WIFI
...@@ -176,7 +176,7 @@ Sets Wi-Fi to connect to the specified network. This API uses a promise to retur ...@@ -176,7 +176,7 @@ Sets Wi-Fi to connect to the specified network. This API uses a promise to retur
| Type | Description | | Type | Description |
| --------------------- | ------------------------- | | --------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value. If the operation fails, an error object is thrown.| | Promise&lt;void&gt; | Promise that returns no value. If the operation fails, an error object will be thrown.|
**Error codes** **Error codes**
......
# Geolocation # @ohos.geolocation (Geolocation)
The **geolocation** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing. The **geolocation** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing.
......
...@@ -6,6 +6,12 @@ The **AbilityMonitor** module provides monitors for abilities that meet specifie ...@@ -6,6 +6,12 @@ The **AbilityMonitor** module provides monitors for abilities that meet specifie
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
## Usage ## Usage
**AbilityMonitor** can be used as an input parameter of [addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9) in **abilityDelegator** to listen for lifecycle changes of an ability. **AbilityMonitor** can be used as an input parameter of [addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9) in **abilityDelegator** to listen for lifecycle changes of an ability.
...@@ -43,9 +49,9 @@ let monitor = { ...@@ -43,9 +49,9 @@ let monitor = {
onAbilityCreate: onAbilityCreateCallback onAbilityCreate: onAbilityCreateCallback
}; };
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor, (error : any) => { abilityDelegator.addAbilityMonitor(monitor, (error : any) => {
if (error && error.code !== 0) { if (error) {
console.error('addAbilityMonitor fail, error: ${JSON.stringify(error)}'); console.error('addAbilityMonitor fail, error: ${JSON.stringify(error)}');
} }
}); });
......
...@@ -6,6 +6,12 @@ The **AbilityRunningInfo** module defines the running information and state of a ...@@ -6,6 +6,12 @@ The **AbilityRunningInfo** module defines the running information and state of a
> >
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import abilitymanager from '@ohos.app.ability.abilityManager';
```
## Usage ## Usage
The ability running information is obtained by calling [getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos) in **abilityManager**. The ability running information is obtained by calling [getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos) in **abilityManager**.
...@@ -31,7 +37,7 @@ The ability running information is obtained by calling [getAbilityRunningInfos]( ...@@ -31,7 +37,7 @@ The ability running information is obtained by calling [getAbilityRunningInfos](
import abilitymanager from '@ohos.app.ability.abilityManager'; import abilitymanager from '@ohos.app.ability.abilityManager';
abilitymanager.getAbilityRunningInfos((error, data) => { abilitymanager.getAbilityRunningInfos((error, data) => {
if (error && error.code !== 0) { if (error) {
console.error('getAbilityRunningInfos fail, error: ${JSON.stringify(error)}'); console.error('getAbilityRunningInfos fail, error: ${JSON.stringify(error)}');
} else { } else {
console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}'); console.log('getAbilityRunningInfos success, data: ${JSON.stringify(data)}');
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance. The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
...@@ -20,7 +21,7 @@ let monitor = { ...@@ -20,7 +21,7 @@ let monitor = {
let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => { abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => {
if (error && error.code !== 0) { if (error) {
console.error('waitAbilityStageMonitor fail, error: ${JSON.stringify(error)}'); console.error('waitAbilityStageMonitor fail, error: ${JSON.stringify(error)}');
} else { } else {
console.log('waitAbilityStageMonitor success, data: ${JSON.stringify(data)}'); console.log('waitAbilityStageMonitor success, data: ${JSON.stringify(data)}');
......
...@@ -6,6 +6,12 @@ The **ProcessInformation** module defines the running information of a process. ...@@ -6,6 +6,12 @@ The **ProcessInformation** module defines the running information of a process.
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import appManager from '@ohos.app.ability.appManager';
```
## How to Use ## How to Use
The process information is obtained by calling [getRunningProcessInformation](js-apis-app-ability-appManager.md#appmanagergetrunningprocessinformation9) of the **appManager** module. The process information is obtained by calling [getRunningProcessInformation](js-apis-app-ability-appManager.md#appmanagergetrunningprocessinformation9) of the **appManager** module.
...@@ -14,7 +20,7 @@ The process information is obtained by calling [getRunningProcessInformation](js ...@@ -14,7 +20,7 @@ The process information is obtained by calling [getRunningProcessInformation](js
import appManager from '@ohos.app.ability.appManager'; import appManager from '@ohos.app.ability.appManager';
appManager.getRunningProcessInformation((error, data) => { appManager.getRunningProcessInformation((error, data) => {
if (error && error.code !== 0) { if (error) {
console.error('getRunningProcessInformation fail, error: ${JSON.stringify(error)}'); console.error('getRunningProcessInformation fail, error: ${JSON.stringify(error)}');
} else { } else {
console.log('getRunningProcessInformation success, data: ${JSON.stringify(data)}'); console.log('getRunningProcessInformation success, data: ${JSON.stringify(data)}');
......
...@@ -6,6 +6,12 @@ The **ShellCmdResult** module provides the shell command execution result. ...@@ -6,6 +6,12 @@ The **ShellCmdResult** module provides the shell command execution result.
> >
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
```
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
...@@ -20,12 +26,12 @@ The result is obtained by calling [executeShellCommand](js-apis-inner-applicatio ...@@ -20,12 +26,12 @@ The result is obtained by calling [executeShellCommand](js-apis-inner-applicatio
**Example** **Example**
```ts ```ts
import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
let abilityDelegator; let abilityDelegator: AbilityDelegatorRegistry.AbilityDelegator;
let cmd = 'cmd'; let cmd = 'cmd';
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (error: any, data: any) => { abilityDelegator.executeShellCommand(cmd, (error: any, data: any) => {
if (error && error.code !== 0) { if (error) {
console.error('executeShellCommand fail, error: ${JSON.stringify(error)}'); console.error('executeShellCommand fail, error: ${JSON.stringify(error)}');
} else { } else {
console.log('executeShellCommand success, data: ${JSON.stringify(data)}'); console.log('executeShellCommand success, data: ${JSON.stringify(data)}');
......
# console (Log) # console (Log Printing)
> **NOTE**<br> The **console** module provides basic log printing capabilities and supports log printing by log level.
> The APIs of this module are no longer maintained since API version 7. You are advised to use ['@ohos.hilog](js-apis-hilog.md)' instead.
If you want to use more advanced log printing services, for example, filtering logs by the specified ID, you are advised to use [`@ohos.hilog`](js-apis-hilog.md).
> **NOTE**
>
> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## console.debug ## console.debug
debug(message: string): void debug(message: string): void
Prints debug logs. Prints debug-level logs.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
- Parameters | Name | Type | Mandatory | Description |
| Name | Type | Mandatory | Description | | ------- | ------ | ---- | ----------- |
| ------- | ------ | ---- | ----------- | | message | string | Yes | Text to print.|
| message | string | Yes | Text to print.|
## console.log ## console.log
log(message: string): void log(message: string): void
Prints debug logs. Prints debug-level logs.
- Parameters **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- | **Parameters**
| message | string | Yes | Text to print.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## console.info ## console.info
...@@ -33,10 +44,13 @@ info(message: string): void ...@@ -33,10 +44,13 @@ info(message: string): void
Prints info-level logs. Prints info-level logs.
- Parameters **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- | **Parameters**
| message | string | Yes | Text to print.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## console.warn ## console.warn
...@@ -45,10 +59,13 @@ warn(message: string): void ...@@ -45,10 +59,13 @@ warn(message: string): void
Prints warn-level logs. Prints warn-level logs.
- Parameters **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- | **Parameters**
| message | string | Yes | Text to print.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## console.error ## console.error
...@@ -57,13 +74,16 @@ error(message: string): void ...@@ -57,13 +74,16 @@ error(message: string): void
Prints error-level logs. Prints error-level logs.
- Parameters **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- | **Parameters**
| message | string | Yes | Text to print.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## Example
**Example**
``` ```
export default { export default {
...@@ -78,4 +98,261 @@ export default { ...@@ -78,4 +98,261 @@ export default {
Switch to the HiLog window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to Info, and enter Hello World in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. Switch to the HiLog window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to Info, and enter Hello World in the search box. Logs that meet the search criteria are displayed, as shown in the following figure.
![en-us_image_0000001200913929](figures/en-us_image_0000001200913929.png) ![Printing logs](figures/printing-logs.png)
## console.assert<sup>10+</sup>
assert(value?: Object, ...arguments: Object[]): void
If **value** is false, the subsequent content will be printed.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| value | Object | No | Value|
| arguments | Object | No | Prints error messages.|
**Example**
```
console.assert(true, 'does nothing');
console.assert(false, 'console %s work', 'didn\'t');
// Assertion console:ohos didn't work
console.assert();
// Assertion failed
```
## console.count<sup>10+</sup>
count(label?: string): void
Adds a counter by the specified label name to count the number of times **console.count()** is called. The default value is **default**.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| label | string | No | Counter label name.|
**Example**
```
console.count()
// default: 1
console.count('default')
// default: 2
console.count('abc')
// abc: 1
console.count('xyz')
// xyz: 1
console.count('abc')
abc: 2
console.count()
// default: 3
```
## console.countReset<sup>10+</sup>
countReset(label?: string): void
Resets a counter by the specified label name. The default value is **default**.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| label | string | No | Counter label name.|
**Example**
```
console.count('abc');
// abc: 1
console.countReset('abc');
console.count('abc');
// abc: 1
```
## console.dir<sup>10+</sup>
dir(dir?: Object): void
Prints content of the specified object.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| dir | Object | No | Object whose content needs to be printed.|
## console.dirxml<sup>10+</sup>
dirxml(...arguments: Object[]): void
Calls **console.log()** and passes the received parameters to it. This API does not produce any content of the XML format.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| arguments | Object | No | Information to be printed.|
## console.group<sup>10+</sup>
group(...arguments: Object[]): void
Creates an inline group so that subsequent lines are indented by the value specified by **groupIndentation**.
If the information to be printed is provided, the information is printed without extra indentation.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| arguments | Object | No | Information to be printed.|
## console.groupCollapsed<sup>10+</sup>
groupCollapsed(...arguments: Object[]): void
Creates a collapsed inline group.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| arguments | Object | No | Information to be printed.|
## console.groupEnd<sup>10+</sup>
groupEnd(): void
Exits an inline group so that subsequent lines are not indented by the value specified by **groupIndentation** .
**System capability**: SystemCapability.Utils.Lang
## console.table<sup>10+</sup>
table(tableData?: Object): void
Prints data in a table.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| tableData | Object | No | Data to be printed in a table.|
**Example**
```
console.table([1, 2, 3]);
// ┌─────────┬────────┐
// │ (index) │ Values │
// ├─────────┼────────┤
// │ 0 │ 1 │
// │ 1 │ 2 │
// │ 2 │ 3 │
// └─────────┴────────┘
console.table({ a: [1, 2, 3, 4, 5], b: 5, c: { e: 5 } });
// ┌─────────┬───┬───┬───┬───┬───┬───┬────────┐
// │ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │ e │ Values │
// ├─────────┼───┼───┼───┼───┼───┼───┼────────┤
// │ a │ 1 │ 2 │ 3 │ 4 │ 5 │ │ │
// │ b │ │ │ │ │ │ │ 5 │
// │ c │ │ │ │ │ │ 5 │ │
// └─────────┴───┴───┴───┴───┴───┴───┴────────┘
```
## console.time<sup>10+</sup>
time(label?: string): void
Starts a timer to track the duration of an operation. The default value is **default**. You can use **console.timeEnd()** to disable the timer and print the result.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| label | string | No | Timer label.|
## console.timeEnd<sup>10+</sup>
timeEnd(label?: string): void
Stops the timer started by **console.time()** and prints the result. The default value is **default**.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| label | string | No | Timer label.|
**Example**
```
console.time('abc');
console.timeEnd('abc');
// abc: 225.438ms
```
## console.timeLog<sup>10+</sup>
timeLog(label?: string, ...arguments: Object[]): void
Prints the elapsed time and other logs for the timer started by **console.time()**.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| label | string | No | Timer label.|
| arguments | Object | No | Logs to be printed.|
**Example**
```
console.time('timer1');
const value = aaa (); // Return 17.
console.timeLog('timer1', value);
// timer1: 365.227ms 17
console.timeEnd('timer1');
// timer1: 513.22ms
```
## console.trace<sup>10+</sup>
trace(...arguments: Object[]): void
Creates a stack trace.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| arguments | Object | No | Logs to be printed.|
**Example**
```
console.trace();
console.trace("Show the trace");
```
# UI Appearance # @ohos.uiAppearance (UI Appearance)
The **uiAppearance** module provides basic capabilities for managing the system appearance. It allows for color mode configuration currently, and will introduce more features over time. The **uiAppearance** module provides basic capabilities for managing the system appearance. It allows for color mode configuration currently, and will introduce more features over time.
......
...@@ -47,7 +47,7 @@ struct Page45 { ...@@ -47,7 +47,7 @@ struct Page45 {
grad.addColorStop(0.5, '#ffffff') grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00') grad.addColorStop(1.0, '#00ff00')
this.context.fillStyle = grad this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500) this.context.fillRect(0, 0, 400, 400)
}) })
} }
.width('100%') .width('100%')
......
...@@ -24,12 +24,12 @@ An **ImageData** object stores pixel data rendered on a canvas. ...@@ -24,12 +24,12 @@ An **ImageData** object stores pixel data rendered on a canvas.
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Translate { struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") private img:ImageBitmap = new ImageBitmap("common/images/1234.png")
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -46,7 +46,7 @@ struct Translate { ...@@ -46,7 +46,7 @@ struct Translate {
.width('100%') .width('100%')
.height('100%') .height('100%')
} }
} }
``` ```
![en-us_image_000000127777780](figures/en-us_image_000000127777780.png) ![en-us_image_000000127777780](figures/en-us_image_000000127777780.png)
...@@ -39,7 +39,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -39,7 +39,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<Line>** component, which does not have corners. | | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<Line>** component, which does not have corners.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a shape with a sharp angle.| | strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a shape with a sharp angle.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.| | strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.|
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册