提交 1e9d517b 编写于 作者: L liujuan 提交者: Gitee

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

Signed-off-by: Nliujuan <liujuan76@h-partners.com>
......@@ -13,3 +13,6 @@
*.so filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.dll filter=lfs diff=lfs merge=lfs -text
OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
......@@ -11,7 +11,7 @@ The basic dependency packages include:
- @ohos.data.dataAbility
- @ohos.data.rdb
- @ohos.data.relationalStore
The sample code for accessing a DataAbility is as follows:
......@@ -23,7 +23,7 @@ The sample code for accessing a DataAbility is as follows:
// Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), three slashes in total.
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb'
import relationalStore from '@ohos.data.relationalStore'
let urivar = "dataability:///com.ix.DataAbility"
let DAHelper = featureAbility.acquireDataAbilityHelper(urivar);
......
# AccessibilityExtensionAbility Development
# AccessibilityExtensionAbility
The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the **ExtensionAbility** framework. You can develop your accessibility applications by applying the **AccessibilityExtensionAbility** template to enhance usability.
......@@ -10,14 +10,6 @@ The **AccessibilityExtensionAbility** module provides accessibility extension ca
>
> Model: stage
This document is organized as follows:
- [AccessibilityExtensionAbility Overview](#accessibilityextensionability-overview)
- [Creating an Accessibility Extension Service](#creating-an-accessibility-extension-service)
- [Processing an Accessibility Event](#processing-an-accessibility-event)
- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services)
- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service)
## AccessibilityExtensionAbility Overview
Accessibility is about giving equal access to everyone so that they can access and use information equally and conveniently under any circumstances. It helps narrow the digital divide between people of different classes, regions, ages, and health status in terms of information understanding, information exchange, and information utilization, so that they can participate in social life more conveniently and enjoy the benefits of technological advances.
......
......@@ -48,13 +48,13 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-inner-
```ts
import featureAbility from '@ohos.ability.featureAbility'
import bundle from '@ohos.bundle';
import bundleManager from '@ohos.bundle.bundleManager';
export default {
onCreate() {
// Obtain the context and call related APIs.
let context = featureAbility.getContext();
context.setDisplayOrientation(bundle.DisplayOrientation.LANDSCAPE).then(() => {
context.setDisplayOrientation(bundleManager.DisplayOrientation.LANDSCAPE).then(() => {
console.info("Set display orientation.")
})
console.info('Application onCreate')
......
# Context (Stage Model)
## Overview
[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**.
[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application file path), and **area** (encryption level). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**.
- The figure below illustrates the inheritance relationship of contexts.
- The figure below illustrates the inheritance relationship of contexts.
![context-inheritance](figures/context-inheritance.png)
- The figure below illustrates the holding relationship of contexts.
![context-holding](figures/context-holding.png)
- The figure below illustrates the holding relationship of contexts.
The following describes the information provided by different contexts.
![context-holding](figures/context-holding.png)
- The following describes the information provided by different contexts.
- [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate an application component, obtain the application component configuration, and more.
```ts
......@@ -67,79 +70,81 @@ The following describes the information provided by different contexts.
This topic describes how to use the context in the following scenarios:
- [Obtaining the Application Development Path](#obtaining-the-application-development-path)
- [Obtaining Application File Paths](#obtaining-application-file-paths)
- [Obtaining and Modifying Encryption Levels](#obtaining-and-modifying-encryption-levels)
- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module)
- [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process)
### Obtaining the Application Development Path
### Obtaining Application File Paths
The following table describes the application development paths obtained from context.
The base class [Context](../reference/apis/js-apis-inner-application-context.md) provides the capability of obtaining application file paths. **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext** inherit this capability. The application file paths are a type of application sandbox paths. For details, see [Application Sandbox Directory](../file-management/app-sandbox-directory.md).
**Table 1** Application development paths
The application file paths obtained by the preceding contexts are different.
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| bundleCodeDir | string | Yes | No | Path for storing the application's installation package, that is, installation directory of the application on the internal storage. |
| cacheDir | string | Yes| No| Path for storing the cache files, that is, cache directory of the application on the internal storage.<br>It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.|
| filesDir | string | Yes | No | Path for storing the common files, that is, file directory of the application on the internal storage.<br>Files in this directory may be synchronized to other directories during application migration or backup.|
| preferencesDir | string | Yes | Yes | Path for storing the preference files, that is, preferences directory of the application. |
| tempDir | string | Yes | No | Path for storing the temporary files.<br>Files in this directory are deleted after the application is uninstalled.|
| databaseDir | string | Yes | No | Path for storing the application's database, that is, storage directory of the local database. |
| distributedFilesDir | string | Yes| No| Path for storing the distributed files.|
- The application file path obtained through **ApplicationContext** is at the application level. This path is recommended for storing global application information, and the files in the path will be deleted when the application is uninstalled.
The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below.
**Figure 1** Application development paths obtained from context
![context-dir](figures/context-dir.png)
- Obtain the application-level path through **ApplicationContext**. It is recommended that global application information be stored in this path. Files stored in this path will be deleted only when the application is uninstalled.
| Name| Path|
| -------- | -------- |
| bundleCodeDir | {Path prefix}/el1/bundle/|
| cacheDir | {Path prefix}/{Encryption level}/base/cache/|
| filesDir | {Path prefix}/{Encryption level}/base/files/|
| preferencesDir | {Path prefix}/{Encryption level}/base/preferences/|
| tempDir | {Path prefix}/{Encryption level}/base/temp/|
| databaseDir | {Path prefix}/{Encryption level}/database/|
| distributedFilesDir | {Path prefix}/el2/distributedFiles/|
- Obtain the HAP level path through **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. It is recommended that the HAP information be stored in this path. The file content stored in this path will be deleted when the HAP is uninstalled. The file content in the application-level path will be deleted only after all the HAPs of the application are uninstalled.
| Name| Path|
| Name| Path|
| -------- | -------- |
| bundleCodeDir | {Path prefix}/el1/bundle/|
| cacheDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/cache/|
| filesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/files/|
| preferencesDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/preferences/|
| tempDir | {Path prefix}/{Encryption level}/base/**haps/{moduleName}**/temp/|
| databaseDir | {Path prefix}/{Encryption level}/database/**{moduleName}**/|
| distributedFilesDir | {Path prefix}/el2/distributedFiles/**{moduleName}**/|
| bundleCodeDir | <Path prefix>/el1/bundle/|
| cacheDir | <Path prefix>/<Encryption level>/base/cache/|
| filesDir | <Path prefix>/<Encryption level>/base/files/|
| preferencesDir | <Path prefix>/<Encryption level>/base/preferences/|
| tempDir | <Path prefix>/<Encryption level>/base/temp/|
| databaseDir | <Path prefix>/<Encryption level>/database/|
| distributedFilesDir | <Path prefix>/el2/distributedFiles/|
The sample code is as follows:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
let applicationContext = this.context.getApplicationContext();
let cacheDir = applicationContext.cacheDir;
let tempDir = applicationContext.tempDir;
let filesDir = applicationContext.filesDir;
let databaseDir = applicationContext.databaseDir;
let bundleCodeDir = applicationContext.bundleCodeDir;
let distributedFilesDir = applicationContext.distributedFilesDir;
let preferencesDir = applicationContext.preferencesDir;
...
}
}
```
The sample code for obtaining the application development paths is as follows:
- The application file path obtained through **AbilityStageContext**, **UIAbilityContext**, or **ExtensionContext** is at the HAP level. This path is recommended for storing HAP-related information, and the files in this path are deleted when the HAP is uninstalled. However, the deletion does not affect the files in the application-level path unless all HAPs of the application are uninstalled.
| Name| Path|
| -------- | -------- |
| bundleCodeDir | <Path prefix>/el1/bundle/|
| cacheDir | <Path prefix>/<Encryption level>/base/**haps/\<module-name>**/cache/|
| filesDir | <Path prefix>/<Encryption level>/base/**haps/\<module-name>**/files/|
| preferencesDir | <Path prefix>/<Encryption level>/base/**haps/\<module-name>**/preferences/|
| tempDir | <Path prefix>/<Encryption level>/base/**haps/\<module-name>**/temp/|
| databaseDir | <Path prefix>/<Encryption level>/database/**\<module-name>**/|
| distributedFilesDir | <Path prefix>/el2/distributedFiles/**\<module-name>**/|
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
The sample code is as follows:
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
let cacheDir = this.context.cacheDir;
let tempDir = this.context.tempDir;
let filesDir = this.context.filesDir;
let databaseDir = this.context.databaseDir;
let bundleCodeDir = this.context.bundleCodeDir;
let distributedFilesDir = this.context.distributedFilesDir;
let preferencesDir = this.context.preferencesDir;
...
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
let cacheDir = this.context.cacheDir;
let tempDir = this.context.tempDir;
let filesDir = this.context.filesDir;
let databaseDir = this.context.databaseDir;
let bundleCodeDir = this.context.bundleCodeDir;
let distributedFilesDir = this.context.distributedFilesDir;
let preferencesDir = this.context.preferencesDir;
...
}
}
}
```
```
> **NOTE**
>
> The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name <fileName>** command in the hdc shell after file creation or modification.
### Obtaining and Modifying Encryption Levels
......@@ -153,22 +158,23 @@ In practice, you need to select a proper encryption level based on scenario-spec
>
> - AreaMode.EL2: user-level encryption. Directories with this encryption level are accessible only after the device is powered on and the password is entered (for the first time).
You can obtain and set the encryption level by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md).
You can obtain and set the encryption level by reading and writing the **area** attribute in [Context](../reference/apis/js-apis-inner-application-context.md).
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import contextConstant from '@ohos.app.ability.contextConstant';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
// Before storing common information, switch the encryption level to EL1.
if (this.context.area === 1) {// Obtain the area.
this.context.area = 0; // Modify the area.
if (this.context.area === contextConstant.AreaMode.EL2) { // Obtain the area.
this.context.area = contextConstant.AreaMode.EL1; // Modify the area.
}
// Store common information.
// Before storing sensitive information, switch the encryption level to EL2.
if (this.context.area === 0) { // Obtain the area.
this.context.area = 1; // Modify the area.
if (this.context.area === contextConstant.AreaMode.EL1) { // Obtain the area.
this.context.area = contextConstant.AreaMode.EL2; // Modify the area.
}
// Store sensitive information.
}
......@@ -178,7 +184,7 @@ export default class EntryAbility extends UIAbility {
### Creating Context of Another Application or Module
The base class **Context** provides [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) to create the context of other applications or modules, so as to obtain the resource information, for example, [obtaining the application development paths](#obtaining-the-application-development-path) of other modules.
The base class **Context** provides [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) to create the context of other applications or modules, so as to obtain the resource information, for example, [obtaining application file paths](#obtaining-application-development-paths) of other modules.
- Call **createBundleContext(bundleName:string)** to create the context of another application.
> **NOTE**
......@@ -188,9 +194,9 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications.
For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
......@@ -203,7 +209,7 @@ The base class **Context** provides [createBundleContext(bundleName:string)](../
}
}
```
- Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module.
> **NOTE**
>
......
......@@ -3,42 +3,45 @@
## Implementation Principles
**Figure 1** ArkTS widget implementation principles
**Figure 1** ArkTS widget implementation principles
![WidgetPrinciple](figures/WidgetPrinciple.png)
- Widget host: an application that displays the widget content and controls the widget location. Only the system application can function as a widget host.
- Widget provider: an application that provides the widget content to display and controls how widget components are laid out and how they interact with users.
- Widget Manager: a resident agent that manages widgets in the system. It provides the [formProvider](../reference/apis/js-apis-app-form-formProvider.md) and [formHost](../reference/apis/js-apis-app-form-formHost.md) APIs as well as widget management, usage, and periodic updates.
- Widget Manager: a resident agent that manages widgets in the system. It provides the [formProvider](../reference/apis/js-apis-app-form-formProvider.md) and [formHost](../reference/apis/js-apis-app-form-formHost.md) APIs as well as the APIs for widget management, usage, and periodic updates.
- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host.
**Figure 2** Working principles of the ArkTS widget rendering service
![WidgetRender](figures/WidgetRender.png)
Unlike JS widgets, ArkTS widgets support logic code running. To avoid potential ArkTS widget issues from affecting the use of applications, the widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of an application provider run in the same virtual machine operating environment, and rendering instances of different application providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different application providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets by the same application provider, and different **globalThis** objects for widgets by different application providers.
Unlike JS widgets, ArkTS widgets support logic code running. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers.
## Advantages of ArkTS Widgets
As a quick entry to applications, ArkTS widgets have the following advantages over JS widgets:
As a quick entry to applications, ArkTS widgets outperform JS widgets in the following aspects:
- Improved development experience and efficiency, thanks to the unified development paradigm
ArkTS widgets share the same declarative UI development framework as application pages. This means that the page layouts can be directly reused in widgets, improving development experience and efficiency.
**Figure 3** Comparison of widget project structures
**Figure 3** Comparison of widget project structures
![WidgetProject](figures/WidgetProject.png)
- More widget features
- Animation: The ArkTS widget supports the [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience.
- Custom drawing: The ArkTS widget allows you to draw graphics with the [Canvas](../reference/arkui-ts/ts-components-canvas-canvas.md) component to present information more vividly.
- Logic code execution: The capability to run logic code in widgets means that service logic can be self-closed in widgets, expanding the service application scenarios of widgets.
- Animation: ArkTS widgets support the [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) and [explicit animation](../reference/arkui-ts/ts-explicit-animation.md) capabilities, which can be leveraged to deliver a more engaging experience.
- Custom drawing: ArkTS widgets allow you to draw graphics with the [\<Canvas>](../reference/arkui-ts/ts-components-canvas-canvas.md) component to present information more vividly.
- Logic code execution: The capability to run logic code in widgets means that service logic can be self-closed in widgets, expanding the use cases of widgets.
## Constraints on ArkTS Widgets
Compared with JS widgets, ArkTS widgets provide more capabilities, but they are also more prone to malicious behavior. The ArkTS widget is displayed in the widget host, which is usually the home screen. To ensure user experience and power consumption, the ArkTS widget capability is restricted as follows:
Compared with JS widgets, ArkTS widgets provide more capabilities, but they are also more prone to malicious behavior. To account for the impact on the widget host – typically the home screen, ArkTS widgets are subject to the following restrictions:
- The .so file cannot be loaded.
......@@ -46,12 +49,14 @@ Compared with JS widgets, ArkTS widgets provide more capabilities, but they are
- Only [partial](arkts-ui-widget-page-overview.md) components, events, animations, data management, state management, and API capabilities of the declarative paradigm are supported.
- The event processing of the widget is independent of that of the widget host. It is recommended that you do not use the left and right sliding components when the widget host supports left and right swipes to prevent gesture conflicts.
- The event processing of the widget is independent of that of the widget host. To prevent gesture conflicts, avoid using swipers in the widget when the widget host supports left and right swipes.
The following features are coming to ArkTS widgets in later versions:
In addition, ArkTS widgets do not support the following features:
- Breakpoint debugging
- import statements
- Importing modules
- Instant preview
- Breakpoint debugging.
- Hot reload
......@@ -16,14 +16,14 @@ The following sample code enables the PageAbility to create connection callback
```ts
import rpc from "@ohos.rpc"
import prompt from '@system.prompt'
import promptAction from '@ohos.promptAction'
import featureAbility from '@ohos.ability.featureAbility'
let option = {
onConnect: function onConnectCallback(element, proxy) {
console.info(`onConnectLocalService onConnectDone`)
if (proxy === null) {
prompt.showToast({
promptAction.showToast({
message: "Connect service failed"
})
return
......@@ -33,19 +33,19 @@ let option = {
let option = new rpc.MessageOption()
data.writeInterfaceToken("connect.test.token")
proxy.sendRequest(0, data, reply, option)
prompt.showToast({
promptAction.showToast({
message: "Connect service success"
})
},
onDisconnect: function onDisconnectCallback(element) {
console.info(`onConnectLocalService onDisconnectDone element:${element}`)
prompt.showToast({
promptAction.showToast({
message: "Disconnect service success"
})
},
onFailed: function onFailedCallback(code) {
console.info(`onConnectLocalService onFailed errCode:${code}`)
prompt.showToast({
promptAction.showToast({
message: "Connect local service onFailed"
})
}
......
......@@ -9,18 +9,18 @@ The following sample code shows how to create a DataAbility:
```ts
import featureAbility from '@ohos.ability.featureAbility'
import dataAbility from '@ohos.data.dataAbility'
import dataRdb from '@ohos.data.rdb'
import relationalStore from '@ohos.data.relationalStore'
const TABLE_NAME = 'book'
const STORE_CONFIG = { name: 'book.db' }
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)'
let rdbStore: dataRdb.RdbStore = undefined
let rdbStore: relationalStore.RdbStore = undefined
export default {
onInitialized(abilityInfo) {
console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName)
let context = featureAbility.getContext()
dataRdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => {
relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
console.info('DataAbility getRdbStore callback')
store.executeSql(SQL_CREATE_TABLE, [])
rdbStore = store
......
......@@ -17,11 +17,13 @@ This document describes the following operations:
## Setting a Mission Snapshot Icon (for System Applications Only)
Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) to set the icon of a mission snapshot. The icon is an object of the [PixelMap](../reference/apis/js-apis-image.md#pixelmap7) type. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
Call [UIAbilityContext.setMissionIcon()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionicon) to set the icon of a mission snapshot. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). For details about how to obtain the PixelMap information in the example, see [Image Decoding](../media/image-decoding.md).
```ts
let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information.
let context = ...; // UIAbilityContext
let pixelMap: PixelMap =...; // PixelMap information of the image.
context.setMissionIcon(imagePixelMap, (err) => {
context.setMissionIcon(pixelMap, (err) => {
if (err.code) {
console.error(`Failed to set mission icon. Code is ${err.code}, message is ${err.message}`);
}
......@@ -31,7 +33,6 @@ context.setMissionIcon(imagePixelMap, (err) => {
The display effect is shown below.
Figure 2 Mission snapshot icon
![](figures/mission-set-task-snapshot-icon.png)
## Setting a Mission Snapshot Name
......@@ -39,7 +40,9 @@ Figure 2 Mission snapshot icon
Call [UIAbilityContext.setMissionLabel()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissionlabel) to set the name of a mission snapshot.
```ts
this.context.setMissionLabel('test').then(() => {
let context = ...; // UIAbilityContext
context.setMissionLabel('test').then(() => {
console.info('Succeeded in seting mission label.');
}).catch((err) => {
console.error(`Failed to set mission label. Code is ${err.code}, message is ${err.message}`);
......@@ -49,5 +52,4 @@ this.context.setMissionLabel('test').then(() => {
The display effect is shown below.
Figure 3 Mission snapshot name
![](figures/mission-set-task-snapshot-label.png)
......@@ -5,12 +5,11 @@ The OpenHarmony process model is shown below.
- All UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in an independent process, which is **Main process** in green in the figure.
- The ExtensionAbility components of the same type (except ServiceExtensionAbility and DataShareExtensionAbility) of an application (with the same bundle name) run in an independent process, which is **FormExtensionAbility process**, **InputMethodExtensionAbility process**, and other **ExtensionAbility process** in blue in the figure.
- All ExtensionAbility components of the same type (except ServiceExtensionAbility and DataShareExtensionAbility) of an application (with the same bundle name) run in an independent process, which is **FormExtensionAbility process**, **InputMethodExtensionAbility process**, and other **ExtensionAbility process** in blue in the figure.
- WebView has an independent rendering process, which is **Render process** in yellow in the figure.
**Figure 1** Process model
**Figure 1** Process model
![process-model](figures/process-model.png)
> NOTE
......@@ -20,7 +19,8 @@ The OpenHarmony process model is shown below.
A system application can apply for multi-process permissions (as shown in the following figure) and configure a custom process for an HAP. UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility in the HAP run in the custom process. Different HAPs run in different processes by configuring different process names.
**Figure 2** Multi-process
**Figure 2** Multi-process
![multi-process](figures/multi-process.png)
......
......@@ -4,19 +4,18 @@ For an OpenHarmony application, each process has a main thread to provide the fo
- Draw the UI.
- Manage the ArkTS engine instance of the main thread so that multiple UIAbility components can run on it.
- Manage ArkTS engine instances of other threads (such as the worker thread), for example, starting and terminating other threads.
- Manage ArkTS engine instances of other threads, for example, starting and terminating other threads.
- Distribute interaction events.
- Process application code callbacks (event processing and lifecycle management).
- Receive messages sent by the worker thread.
In addition to the main thread, there is an independent thread, named worker. The worker thread is mainly used to perform time-consuming operations. The worker thread is created in the main thread and is independent from the main thread. It cannot directly operate the UI. A maximum of seven worker threads can be created.
![thread-model-stage](figures/thread-model-stage.png)
Based on the OpenHarmony thread model, different services run on different threads. Service interaction requires inter-thread communication. In the same process, threads can communicate with each other in Emitter or Worker mode. Emitter is mainly used for event synchronization between threads, and Worker is mainly used to execute time-consuming tasks.
> **NOTE**
>
>
> - The stage model provides only the main thread and worker thread. Emitter is mainly used for event synchronization within the worker thread or between the main thread and worker thread.
> - The UIAbility and UI are in the main thread. For details about data synchronization between them, see [Data Synchronization Between UIAbility and UI](uiability-data-sync-with-ui.md).
> - To view thread information about an application process, run the **hdc shell** command to enter the shell CLI of the device, and then run the **ps -p *<pid>* -T command**, where *<pid>* indicates the [process ID](process-model-stage.md) of the application.
......@@ -115,7 +115,7 @@ To create a widget in the FA model, implement the widget lifecycle callbacks. Ge
import formBindingData from '@ohos.app.form.formBindingData';
import formInfo from '@ohos.app.form.formInfo';
import formProvider from '@ohos.app.form.formProvider';
import dataStorage from '@ohos.data.storage';
import dataPreferences from '@ohos.data.preferences';
```
2. Implement the widget lifecycle callbacks in **form.ts**.
......@@ -265,7 +265,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean
"updateCount": 0
};
try {
const storage = await dataStorage.getStorage(DATA_STORAGE_PATH);
const storage = await dataPreferences.getPreferences(this.context, DATA_STORAGE_PATH);
// Put the widget information.
await storage.put(formId, JSON.stringify(formInfo));
console.info(`storeFormInfo, put form info successfully, formId: ${formId}`);
......@@ -303,7 +303,7 @@ You should override **onDestroy** to implement widget data deletion.
const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store";
async function deleteFormInfo(formId: string) {
try {
const storage = await dataStorage.getStorage(DATA_STORAGE_PATH);
const storage = await dataPreferences.getPreferences(this.context, DATA_STORAGE_PATH);
// Delete the widget information.
await storage.delete(formId);
console.info(`deleteFormInfo, del form info successfully, formId: ${formId}`);
......
......@@ -27,4 +27,5 @@
- [Startup Development](faqs-startup.md)
- [Distributed Device Development](faqs-distributed-device-profile.md)
- [SDK Usage](faqs-sdk.md)
- [Compiler Runtime](faqs-compiler-runtime.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-fourth-party-library.md)
\ No newline at end of file
# Ability Access Control Development
# Application Access Control Development
## Can the app listen for the permission change after its permission is modified in Settings?
Applicable to: OpenHarmony 3.1 Beta 5 (API version 9)
Third-party apps cannot listen for the permission change.
## Why is there no pop-up window displayed when an app applies for the **ohos.permission.LOCATION** permission?
Applicable to: OpenHarmony 3.2 Release (API version 9)
Applications developed using SDKs earlier than API version 9 can directly apply for the **ohos.permission.LOCATION** permission.
For the applications developed using the SDK of API version 9 or later, you need to apply for **ohos.permission.APPROXIMATELY_LOCATION** and then **ohos.permission.LOCATION**.
**References**
[Application Permission List](../security/permission-list.md#ohospermissionlocation)
## What can I do to prevent the application from crashing when the application is started again after the user denies the permission requested?
Applicable to: OpenHarmony SDK 3.2 Beta5
**Possible Causes**
- If the permission required by a service is rejected by the user, the system directly returns the result and will no longer display a dialog box to request the permission.
- If related judgment is not performed after the permission is requested, the application will be rejected due to lack of the corresponding permission when accessing the target object under permission control, and terminated unexpectedly.
**Solution**
1. Before allowing an application to call an API protected by certain permission, verify whether the application has the permission. If the application has the permission, the application can call the API. Otherwise, a dialog box is dipslayed to ask user authorization.
2. If the user rejects to grant the permission, ensure that other functions irrelevant to this permission are not affected.
3. When this service is triggered again by the user or to implement a service function, on-screen message shall be provided to guide the user to grant the permission in **Settings**.
**References**
[Access Control (Permission) Overview](../security/accesstoken-overview.md)
## What are the differences between **extensionAbilities** and **requestPermissions** in the **module.json5** file?
Applicable to: OpenHarmony SDK 3.2 Beta5
- **requestPermissions**: specifies all the permissions required by an application for running. The permissions take effect only after being configured (declared) in the **module.json5** file.
- **extensionAbilitie.permissions**: specifies the permissions customized by the ExtensionAbility component. These permissions are required when an application needs to access the ExtensionAbility component. **extensionAbilitie.permissions** is used for permission verification only.
**References**
[module.json5 Configuration File](../quick-start/module-configuration-file.md)
# Compiler Runtime
## What if a crash occurs when I obtain a string in JSON format from rawfile, convert the string into an object, and call the instance method?
Applicable to: OpenHarmony 3.2 Beta (API version 9)
**Symptom**
"jscrash happened in xxxxxxxxx" is displayed, and the crash log contains "Error message: Unexpected Object in JSON".
**Solution**
The prototype of the object obtained by parsing the string in JSON format is object. The prototype chain does not contain the instance method. Therefore, the object cannot be called.
To solve this problem, use either of the following methods:
1. Add the prototype to the parsed object.
2. Change the instance method to a static method and call it through the class name.
......@@ -25,8 +25,6 @@ An error is reported when the **TRUNCATE TABLE** statement is used to clear tabl
The RDB store uses SQLite and does not support the **TRUNCATE TABLE** statement. To clear a table in an RDB store, use the **DELETE** statement, for example, **DELETE FROM sqlite\_sequence WHERE name = 'table\_name'**.
## What data types does an RDB store support?
Applicable to: OpenHarmony SDK 3.0 or later, API version 9 stage model
......@@ -35,13 +33,43 @@ Applicable to: OpenHarmony SDK 3.0 or later, API version 9 stage model
An RDB store supports data of the number, string, and Boolean types. The number type supports data of the Double, Long, Float, Int, or Int64 type, with a maximum precision of 17 decimal digits.
## How do I save pixel map data to a database?
## How do I persist application data?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
**Solution**
You can use the **PersistentStorage** class to implement application data persistence. You can link the persistent data with specific tags to **AppStorage**, and invoke **AppStorage** APIs to access the persistent data. Persistent data is stored in a local XML file in **/data/app/el2/100/base/<bundleName\>/haps/<hapName\>/files/persistent\_storage**.
Example:
```
AppStorage.Link('varA')
PersistentStorage.PersistProp("varA", "111");
@Entry
@Component
struct Index {
@StorageLink('varA') varA: string = ''
build() {
Column() {
Text('varA: ' + this.varA).fontSize(20)
Button('Set').width(100).height(100).onClick(() => {
this.varA += '333'
})
}
.width('100%')
.height('100%')
}
}
```
**Reference**
[Persistent Data Management\(OpenHarmony\)](../quick-start/arkts-persiststorage.md)
## How do I save pixel map data to a database?
Pixel map data fails to be stored.
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
......@@ -55,6 +83,10 @@ Convert the pixel map data into an **ArrayBuffer** and save the **ArrayBuffer**
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
Problem of obtaining RDB store files.
**Solution**
The RDB store files are stored in **/data/app/el2/100/database/*Bundle_name*/entry/rdb/**. You can use the hdc command to copy the file from the directory and use a SQLite tool to open the file.
......@@ -69,6 +101,10 @@ Example:
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
I do not know whether I need to design a lock mechanism for databases in development.
**Solution**
The distributed data service (DDS), RDB store, and preferences provided OpenHarmony have a lock mechanism. You do not need to bother with the lock mechanism during the development.
......@@ -97,5 +133,26 @@ In API version 8, large text files cannot be saved in RDB stores.
**Solution**
In versions earlier than API version 9, the maximum length of a text file is 1024 bytes. If the text file exceeds 1024 bytes, it cannot be saved.
The limit on the text file size has been removed since API9 version.
## What if **undefined** is returned by **Preferences.get** after **Preferences.put()** is successfully called?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Symptom**
Data is successfully saved using **preferences**, but fails to be obtained.
**Solution**
1. After **put()** is performed, use **flush()** to persist the data.
2. Wait until the **flush()** asynchronous operation is complete, and call **get()**.
## Can I specify the in-memory database mode when using an RDB store?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
**Solution**
RDB stores use SQLite. The default in-memory database mode is file, which cannot be modified.
......@@ -2,7 +2,7 @@
## How do I obtain the path of system screenshots?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
......@@ -10,7 +10,7 @@ The screenshots are stored in **/storage/media/100/local/files/Pictures/Screensh
## How do I change the permissions on a directory to read/write on a device?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Symptom**
......@@ -19,3 +19,94 @@ When the hdc command is used to send a file to a device, "permission denied" is
**Solution**
Run the **hdc shell mount -o remount,rw /** command to grant the read/write permissions.
## What is the best way to create a file if the file to open does not exist?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
Use **fs.open(path: string, mode?: number)** with **mode** set to **fs.OpenMode.CREATE**. **fs.OpenMode.CREATE** creates a file if it does not exist.
## How do I solve the problem of garbled Chinese characters in a file?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
After the buffer data of the file content is read, use **TextDecoder** of @ohos.util to decode the file content.
```
let filePath = getContext(this).filesDir + "/test0.txt";
let stream = fs.createStreamSync(filePath, "r+");
let buffer = new ArrayBuffer(4096)
let readOut = stream.readSync(buffer);
let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true })
let readString = textDecoder.decodeWithStream(new Uint8Array(buffer), { stream: false });
console.log ("File content read: "+ readString);
```
## Why is an error reported when **fs.copyFile** is used to copy a **datashare://** file opened by **fs.open()**?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
**fs.copyFile** does not support URIs. You can use **fs.open()** to obtain the URI, obtain the file descriptor (FD) based on the URI, and then use **fs.copyFile** to copy the file based on the FD.
```
let file = fs.openSync("datashare://...")
fs.copyFile(file.fd, 'dstPath', 0).then(() => {
console.info('copyFile success')
}).catch((err) => {
console.info("copy file failed with error message: " + err.message + ", error code: " + err.code);
})
```
## How do I modify the specified content of a JSON file in the sandbox?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
Perform the following steps:
1. Use **fs.openSyn** to obtain the FD of the JSON file.
```
import fs from '@ohos.file.fs';
let sanFile = fs.open(basePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let fd = sanFile.fd;
```
2. Use **fs.readSync** to read the file content.
```
let content = fs.readSync(basePath);
```
3. Modify the file content.
```
obj.name = 'new name';
```
4. Write the JSON file again.
```
fs.writeSync(file.fd, JSON.stringify(obj));
```
For more information, see [@ohos.file.fs](../reference/apis/js-apis-file-fs.md).
## What is the actual path corresponding to the file path obtained through the FileAccess module?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Solution**
The files are stored in the **/storage/media/100/local/files** directory. The specific file path varies with the file type and source. To obtain the actual file path, run the following command in the **/storage/media/100/local/files** directory:
**-name \[filename\]**
For more information, see [Uploading and Downloading an Application File](../file-management/app-file-upload-download.md).
......@@ -10,6 +10,10 @@
- [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md)
- [Sending Files to an Application Sandbox](send-file-to-app-sandbox.md)
- [Sharing an Application File](share-app-file.md)
- Application Data Backup and Restoration
- [Application Data Backup and Restoration Overview](app-file-backup-overview.md)
- [Backing Up and Restoring Application Access Data](app-file-backup-extension.md)
- [Backing Up and Restoring Application-triggered Data (for System Applications Only)](app-file-backup.md)
- User File
- [User File Overview](user-file-overview.md)
- Selecting and Saving User Files (FilePicker)
......
# Backing Up and Restoring Application Access Data
You can use BackupExtensionAbility to implement backup and restoration of application access data.
BackupExtensionAbility is a class derived from the [ExtensionAbility](../application-models/extensionability-overview.md) component in [Stage Model](../../application-dev/application-models/stage-model-development-overview.md). You can modify the configuration file to customize the behavior of the backup and restoration framework, including whether backup and restoration are allowed and which files are backed up.
## Constraints
- The paths of all files and directories to be backed up cannot exceed 4095 bytes. Otherwise, undefined behavior may occur.
- If a directory needs to be backed up, the application process must have the permission to read the directory and all its subdirectories (**r** in DAC). Otherwise, the backup fails.
- If a file needs to be backed up, the application process must have the permission to search for its grandparent directory of the file (**x** in DAC). Otherwise, the backup fails.
## How to Develop
1. Add the **extensionAbilities** configuration in the application's **module.json5** file.
Add **extensionAbilities**, set **type** to **backup**, and add **name: ohos.extension.backup** to **[metadata]**(../../application-dev/reference/apis/js-apis-bundleManager-metadata.md).
BackupExtensionAbility configuration example:
```json
{
"extensionAbilities": [
{
"description": "$string:ServiceExtAbility",
"icon": "$media:icon",
"name": "BackupExtensionAbility",
"type": "backup",
"visible": true,
"metadata": [
{
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
],
"srcEntrance": "",
}
]
}
```
2. Add a metadata resource configuration file.
The metadata resource configuration file defines the files to be transferred during backup and restoration. The file name must be the same as the value of **resource** under **metadata** in the **module.json5** file. This file is stored in the **Profile** folder.
Metadata resource configuration file example:
```json
{
"allowToBackupRestore": true,
"includes": [
"/data/storage/el2/base/files/users/*/*.json"
],
"excludes": [
"/data/storage/el2/base/files/users/*/hidden.json"
],
}
```
### Description of the Metadata Resource Configuration File
| Name | Type | Mandatory| Description |
| -------------------- | ---------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| allowToBackupRestore | Boolean | Yes | Whether to allow backup and restoration. The default value is **false**. |
| includes | String array| No | Files and directories to be backed up in the application sandbox.<br>Each item in the array is a pattern string, which can contain shell-style wildcards such as *****, **?**, and **[**.<br>The pattern string that does not start with a slash (/) indicates a relative path relative to the root path.<br>If **includes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses the **includes** default value (see the following code segment).|
| excludes | String array| No | Exception items in **includes** that do not need to be backed up. The value is in the same format as **includes**.<br>If **excludes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses an empty array as the default value. |
**includes** default value:
```json
{
"includes": [
"data/storage/el2/database/",
"data/storage/el2/base/files/",
"data/storage/el2/base/preferences/",
"data/storage/el2/base/haps/*/database/",
"data/storage/el2/base/haps/*/base/files/",
"data/storage/el2/base/haps/*/base/preferences/",
]
}
```
# Application Data Backup and Restoration Overview
Application data, such as the configuration and service data, is generated when an application is used. To ensure that user data will not be lost due to operations, such as application updates and hopping, applications need to access data backup and restoration.
Before development, you need to understand the ExtensionAbility component. For details, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md).
BackupExtensionAbility is a class derived from ExtensionAbility in the stage model. It provides the capabilities of backing up and restoring application data. It is an extended component without the UI. It runs when a backup or restoration task starts and exits when the task is complete.
The implementation includes the following:
- [Backup and restoration of application access data](app-file-backup-extension.md): All applications can access data backup and restoration. After accessed, the application can modify the configuration file to customize the behavior of the backup and restoration framework, including whether to allow backup and restoration and specifying the data to be backed up.
Applications can perform backup and restoration configurations, but not trigger data backup and restoration.
- [Backup and restoration of application-triggered data](app-file-backup.md): Only system applications can trigger data backup and restoration. After data backup or restoration is triggered, the backup and restoration framework checks whether each application has accessed data backup and restoration. If yes, the backup and restore framework backs up or restores data based on the application's configuration file.
# Backing Up and Restoring Application-triggered Data (for System Applications Only)
The backup and restoration module provides a complete data backup and restoration solution for application data, user data, and system services on devices. You can implement data backup or restoration for applications by performing the following operations:
- [Obtaining the capability file](#obtaining-the-capability-file): Obtain the capability file of all applications of the system user. The capability file is indispensable for data backup and restoration.
- [Backing up application data](#backing-up-application-data): Select the application data to be backed up based on the application information provided by the capability file, and back up the data.
- [Restoring application data](#restoring-application-data): Select the application data to be restored based on the application information provided in the capability file and restore the data.
- [Installing the application during data restoration](#installing-the-application-during-data-restoration): Install the application if the application has not been installed. As an extended function of application data restoration, this function allows the application to be installed on the device before data restoration.
## How to Develop
For details about the APIs to be used, see [Backup and Restoration](../reference/apis/js-apis-file-backup.md).
Before using the APIs, you need to:
1. Apply for the ohos.permission.BACKUP permission. For details, see [Apply for permissions](../security/accesstoken-guidelines.md).
2. Import **@ohos.file.backup**.
```js
import backup from '@ohos.file.backup';
```
## Obtaining the Capability File
Obtain the application capability file of the current system user. This file is indispensable for application data backup and restoration.
This file contains the device type and version and basic application information, such as the application name, application data size, application version, whether to allow backup and restoration, and whether to install the application during restoration.
Use **backup.getLocalCapabilities()** to obtain the capability file.
```js
import fs from '@ohos.file.fs';
async function getLocalCapabilities() {
try {
let fileData = await backup.getLocalCapabilities();
console.info('getLocalCapabilities success');
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
fs.copyFileSync(fileData.fd, fpath);
fs.closeSync(fileData.fd);
} catch (err) {
console.error('getLocalCapabilities failed with err: ' + err);
}
}
```
**Capability file example**
| Name | Type| Mandatory| Description |
| -------------- | -------- | ---- | ---------------------- |
| bundleInfos | Array | Yes | Application information. |
| allToBackup | Boolean | Yes | Whether to allow backup and restoration. |
| extensionName | String | Yes | Extension name of the application. |
| name | String | Yes | Bundle name of the application. |
| needToInstall | Boolean | Yes | Whether to install the application during data restoration.|
| spaceOccupied | Number | Yes | Space occupied by the application data.|
| versionCode | Number | Yes | Application version number. |
| versionName | String | Yes | Application version name. |
| deviceType | String | Yes | Type of the device. |
| systemFullName | String | Yes | Device version. |
```json
{
"bundleInfos" :[{
"allToBackup" : true,
"extensionName" : "BackupExtensionAbility",
"name" : "com.example.hiworld",
"needToInstall" : false,
"spaceOccupied" : 0,
"versionCode" : 1000000,
"versionName" : "1.0.0"
}],
"deviceType" : "default",
"systemFullName" : "OpenHarmony-4.0.0.0"
}
```
## Backing Up Application Data
You need to select the application data to be backed up based on the application information provided by the capability file.
The Backup & Restore service packages the application data into a file. The file handle is returned by the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the instance is created.
You can save the file to a local directory as required.
**Example**
```ts
import fs from '@ohos.file.fs';
// Create a SessionBackup instance for data backup.
let g_session;
function createSessionBackup() {
let sessionBackup = new backup.SessionBackup({
onFileReady: async (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
try {
let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName;
if (!fs.accessSync(bundlePath)) {
fs.mkdirSync(bundlePath);
}
fs.copyFileSync(file.fd, bundlePath + `/${file.uri}`);
fs.closeSync(file.fd);
console.info('onFileReady success');
} catch (e) {
console.error('onFileReady failed with err: ' + e);
}
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.info('onBundleBegin err: ' + err);
} else {
console.info('onBundleBegin bundleName: ' + bundleName);
}
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.info('onBundleEnd err: ' + err);
} else {
console.info('onBundleEnd bundleName: ' + bundleName);
}
},
onAllBundlesEnd: (err) => {
if (err) {
console.info('onAllBundlesEnd err: ' + err);
} else {
console.info('onAllBundlesEnd');
}
},
onBackupServiceDied: () => {
console.info('onBackupServiceDied');
},
});
return sessionBackup;
}
async function sessionBackup ()
{
g_session = createSessionBackup();
// Select the application to be backed up based on the capability file obtained by backup.getLocalCapabilities().
// You can also back up data based on the application bundle name.
const backupApps = [
"com.example.hiworld",
]
await g_session.appendBundles(backupApps);
console.info('appendBundles success');
}
```
## Restoring Application Data
You can select the application data to be restored based on the application information provided by the capability file.
During the restoration, the Backup and Restore service returns the file handle of the application data to be restored in the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the instance is created based on the [getFileHandle](../reference/apis/js-apis-file-backup.md#getfilehandle) called. Then, the data to be restored is written to the file handle based on the [uri](../reference/apis/js-apis-file-backup.md#filemeta) returned. After the data is written, use [publishFile()](../reference/apis/js-apis-file-backup.md#publishfile) to notify the service that the data write is complete.
When all the data of the application is ready, the service starts to restore the application data.
**Example**
```ts
import fs from '@ohos.file.fs';
// Create a SessionRestore instance for data restoration.
let g_session;
async function publishFile(file)
{
await g_session.publishFile({
bundleName: file.bundleName,
uri: file.uri
});
}
function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
// Set bundlePath based on the actual situation.
let bundlePath;
if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath);
}
fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd);
// After the data is transferred, notify the server that the file is ready.
publishFile(file);
console.info('onFileReady success');
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.error('onBundleBegin failed with err: ' + err);
}
console.info('onBundleBegin success');
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.error('onBundleEnd failed with err: ' + err);
}
console.info('onBundleEnd success');
},
onAllBundlesEnd: (err) => {
if (err) {
console.error('onAllBundlesEnd failed with err: ' + err);
}
console.info('onAllBundlesEnd success');
},
onBackupServiceDied: () => {
console.info('service died');
}
});
return sessionRestore;
}
async function restore ()
{
g_session = createSessionRestore();
const backupApps = [
"com.example.hiworld",
]
// You can obtain the capability file based on actual situation. The following is an example only.
// You can also construct a capability file as required.
let fileData = await backup.getLocalCapabilities();
await g_session.appendBundles(fileData.fd, backupApps);
console.info('appendBundles success');
// After the application to be restored is added, call getFileHandle() to obtain the handle of the application file to be restored based on the application name.
// The number of application data files to be restored varies depending on the number of backup files. The following is only an example.
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "manage.json"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
console.info('getFileHandle success');
}
```
## Installing the Application During Data Restoration
You can enable the application to be installed before application data restoration. To achieve this purpose, the value of **needToInstall** in **bundleInfos** in the [capability file](#obtaining-the-capability-file) must be **true**.
> **NOTE**
> - [Application data backup](#backing-up-application-data) does not support backup of the application installation package. Therefore, you need to obtain the application installation package.
> - To obtain the file handle of the application installation package, call [getFileHandle()](../reference/apis/js-apis-file-backup.md#getfilehandle) with **FileMeta.uri** set to **/data/storage/el2/restore/bundle.hap**. The file handle of the application installation package is returned through the **onFileReady()** callback registered when the instance is created. The returned **File.uri** is **data/storage/el2/restore/bundle.hap**.
**Example**
```ts
import fs from '@ohos.file.fs';
// Create a SessionRestore instance for data restoration.
let g_session;
async function publishFile(file)
{
await g_session.publishFile({
bundleName: file.bundleName,
uri: file.uri
});
}
function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
let bundlePath;
if( file.uri == "/data/storage/el2/restore/bundle.hap" )
{
// Set the path of the application installation package based on actual situation.
} else {
// Set bundlePath based on the actual situation.
}
if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath);
}
fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd);
// After the data is transferred, notify the server that the file is ready.
publishFile(file);
console.info('onFileReady success');
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.error('onBundleBegin failed with err: ' + err);
}
console.info('onBundleBegin success');
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.error('onBundleEnd failed with err: ' + err);
}
console.info('onBundleEnd success');
},
onAllBundlesEnd: (err) => {
if (err) {
console.error('onAllBundlesEnd failed with err: ' + err);
}
console.info('onAllBundlesEnd success');
},
onBackupServiceDied: () => {
console.info('service died');
}
});
return sessionRestore;
}
async function restore ()
{
g_session = createSessionRestore();
const backupApps = [
"com.example.hiworld",
]
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
let file = fs.openSync(fpath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE);
let content = "{\"bundleInfos\" :[{\"allToBackup\" : false,\"extensionName\" : \"\"," +
"\"name\" : \"cn.openharmony.inputmethodchoosedialog\",\"needToInstall\" : true,\"spaceOccupied\" : 0," +
"\"versionCode\" : 1000000,\"versionName\" : \"1.0.0\"}],\"deviceType\" : \"default\",\"systemFullName\" : \"OpenHarmony-4.0.6.2(Canary1)\"}";
fs.writeSync(file.fd, content);
fs.fsyncSync(file.fd);
await g_session.appendBundles(file.fd, backupApps);
console.info('appendBundles success');
// Obtain the file handle of the application to be installed.
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "/data/storage/el2/restore/bundle.hap"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "manage.json"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
console.info('getFileHandle success');
}
```
**Capability file example**
```json
{
"bundleInfos" :[{
"allToBackup" : true,
"extensionName" : "BackupExtensionAbility",
"name" : "com.example.hiworld",
"needToInstall" : true,
"spaceOccupied" : 0,
"versionCode" : 1000000,
"versionName" : "1.0.0"
}],
"deviceType" : "default",
"systemFullName" : "OpenHarmony-4.0.0.0"
}
```
......@@ -7,10 +7,11 @@ The operations for saving images, audio or video clips, and documents are simila
## Saving Images or Video Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **photoSaveOptions** instance.
......@@ -20,27 +21,43 @@ The operations for saving images, audio or video clips, and documents are simila
photoSaveOptions.newFileNames = ["PhotoViewPicker01.jpg"]; // (Optional) Set the names of the files to save.
```
3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the files.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the files. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
<br>The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let URI = null;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.save(photoSaveOptions)
.then(async (photoSaveResult) => {
let uri = photoSaveResult[0];
// Perform operations on the files based on the file URIs obtained.
})
.catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
photoViewPicker.save(photoSaveOptions).then((photoSaveResult) => {
URI = photoSaveResult[0];
console.info('photoViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
## Saving Documents
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **documentSaveOptions** instance.
......@@ -50,31 +67,43 @@ The operations for saving images, audio or video clips, and documents are simila
documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the names of the documents to save.
```
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the documents.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the documents. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let URI = null;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.save(documentSaveOptions)
.then(async (documentSaveResult) => {
let uri = documentSaveResult[0];
// For example, write data to the documents based on the obtained URIs.
})
.catch((err) => {
console.error(`Invoke documentPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => {
URI = documentSaveResult[0];
console.info('documentViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
## Saving Audio Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create an **audioSaveOptions** instance.
......@@ -84,20 +113,33 @@ The operations for saving images, audio or video clips, and documents are simila
audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the names of the files to save.
```
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the files.
After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
> **NOTE**
>
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the files. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned.
The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let URI = null;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.save(audioSaveOptions)
.then((audioSelectResult) => {
let uri = audioSelectResult[0];
// Perform operations on the audio files based on the file URIs.
})
.catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => {
URI = audioSelectResult[0];
console.info('audioViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
# Selecting User Files
If your application needs to support share and saving of user files (such as images and videos) by users, you can use the [FilePicker](../reference/apis/js-apis-file-picker.md) prebuilt in OpenHarmony to implement selecting and saving of user files.
If your application needs to support share and saving of user files (such as images and videos), you can use OpenHarmony [FilePicker](../reference/apis/js-apis-file-picker.md) to implement selection and saving of user files.
The **FilePicker** provides the following interfaces by file type:
......@@ -12,10 +12,11 @@ The **FilePicker** provides the following interfaces by file type:
## Selecting Images or Video Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **photoSelectOptions** instance.
......@@ -32,41 +33,44 @@ The **FilePicker** provides the following interfaces by file type:
photoSelectOptions.maxSelectNumber = 5; // Set the maximum number of images to select.
```
4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files.
Use [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) to return a result set. Further operations on the selected files can be performed based on the file URIs in the result set.
4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files. After the files are selected, [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) is returned.
<br>The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts
let uri = null;
const photoPicker = new picker.PhotoViewPicker();
photoPicker.select(photoSelectOptions).then((photoSelectResult) => {
uri = photoSelectResult.photoUris[0];
let URI = null;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
URI = photoSelectResult.photoUris[0];
console.info('photoViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke photoPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
5. After the GUI is returned from FilePicker, use [**fs.openSync**](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD.
5. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
6. Use [fs.writeSync](../reference/apis/js-apis-file-fs.md#writesync) to write data to the file based on the FD, and then close the FD.
6. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
## Selecting Documents
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **documentSelectOptions** instance.
......@@ -75,23 +79,24 @@ The **FilePicker** provides the following interfaces by file type:
const documentSelectOptions = new picker.DocumentSelectOptions();
```
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents.
After the documents are selected successfully, a result set containing the file URIs is returned. Further operations can be performed on the documents based on the file URIs.
For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned.
<br>The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
<br>For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let uri = null;
let URI = null;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => {
uri = documentSelectResult[0];
URI = documentSelectResult[0];
console.info('documentViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -109,7 +114,7 @@ The **FilePicker** provides the following interfaces by file type:
try {
let result = await context.startAbilityForResult(config, {windowMode: 1});
if (result.resultCode !== 0) {
console.error(`DocumentPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
return;
}
// Obtain the URI of the document.
......@@ -117,34 +122,34 @@ The **FilePicker** provides the following interfaces by file type:
// Obtain the name of the document.
let file_name_list = result.want.parameters.file_name_list;
} catch (err) {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
```
4. After the GUI is returned from FilePicker, use [**fs.openSync**](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD.
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
5. Use [fs.readSync](../reference/apis/js-apis-file-fs.md#readsync) to read data from the file based on the FD, and then close the FD.
5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(4096);
let num = fs.readSync(file.fd, buf);
console.info('read data to file succeed and size is:' + num);
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
## Selecting an Audio File
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create an **audioSelectOptions** instance.
......@@ -153,37 +158,39 @@ The **FilePicker** provides the following interfaces by file type:
const audioSelectOptions = new picker.AudioSelectOptions();
```
3. Create an **audioViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-6) to open the **FilePicker** page for the user to select audio files.
After the files are selected successfully, a result set containing the URIs of the audio files selected is returned. Further operations can be performed on the documents based on the file URIs.
For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md).
3. Create an **audioViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-6) to open the **FilePicker** page for the user to select audio files. After the files are selected, a result set containing the URIs of the audio files selected is returned.
<br>The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
<br>For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md).
> **NOTE**
>
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let uri = null;
let URI = null;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions).then(audioSelectResult => {
uri = audioSelectOptions[0];
URI = audioSelectOptions[0];
console.info('audioViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
4. After the GUI is returned from FilePicker, use [**fs.openSync**](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD.
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync](../reference/apis/js-apis-file-fs.md#writesync) to write data to the file based on the FD, and then close the FD.
5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
......@@ -37,14 +37,14 @@
- **AppScope** > **app.json5**: global configuration of your application.
- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
- **oh_modules**: third-party library dependency information. For details about how to adapt a historical npm project to ohpm, see [Manually Migrating Historical Projects](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212).
- **src > main > ets**: a collection of ArkTS source code.
- **src > main > ets > entryability**: entry to your application/service.
- **src > main > ets > pages**: pages included in your application/service.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Categories and Access](resource-categories-and-access.md#resource-categories).
- **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details, see [module.json5 Configuration File](module-configuration-file.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. Under **targets**, you can set **runtimeOS** to **HarmonyOS** (default) or **OpenHarmony**, depending on the OS of your application.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
- **hvigorfile.ts**: module-level build script. You can customize related tasks and code implementation.
- **oh_modules**: third-party library dependency information. For details about how to adapt a historical npm project to ohpm, see [Manually Migrating Historical Projects](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212).
- **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.ts**: application-level build script.
......
......@@ -2076,8 +2076,17 @@ store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err,
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
})
```
......@@ -2117,8 +2126,17 @@ let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
......@@ -2164,8 +2182,17 @@ store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], fu
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
})
```
......@@ -2211,8 +2238,17 @@ let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Rose");
let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
......@@ -2273,8 +2309,17 @@ store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALAR
console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}
)
```
......@@ -2335,8 +2380,17 @@ let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.greaterThan("id", 0);
let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Failed to remoteQuery, code is ${err.code},message is ${err.message}`);
})
......@@ -2374,8 +2428,17 @@ store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['s
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
})
```
......@@ -2413,8 +2476,17 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
```js
let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'");
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}`);
console.info(`ResultSet column count: ${resultSet.columnCount}`);
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
......
......@@ -368,8 +368,8 @@ Continues a mission on a remote device. This API uses an asynchronous callback t
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueDeviceInfo](#js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.|
| options | [ContinueCallback](#js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.|
| parameter | [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.|
| options | [ContinueCallback](js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
......@@ -426,8 +426,8 @@ Continues a mission on a remote device. This API uses a promise to return the re
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueDeviceInfo](#js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.|
| options | [ContinueCallback](#js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.|
| parameter | [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.|
| options | [ContinueCallback](js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.|
**Return value**
......@@ -475,6 +475,171 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
}
```
## distributedMissionManager.continueMission<sup>10+</sup>
continueMission(parameter: ContinueMissionInfo, callback: AsyncCallback&lt;void&gt;): void;
Continues a mission on a remote device, with the bundle name specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueMissionInfo](./js-apis-inner-application-continueMissionInfo.md) | Yes | Parameters required for mission continuation.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the mission continuation is complete.|
**Error codes**
For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errorcode-DistributedSchedule.md).
| ID| Error Message|
| ------- | -------------------------------------------- |
| 16300501 | The system ability work abnormally. |
| 16300503 | The application is not installed on the remote end and installation-free is not supported. |
| 16300504 | The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. |
| 16300505 | The operation device must be the device where the application to be continued is located or the target device to be continued. |
| 16300506 | The local continuation task is already in progress. |
| 16300507 | Failed to get the missionInfo of the specified bundle name. |
**Example**
```ts
var parameter = {
srcDeviceId: "",
dstDeviceId: "",
bundleName: "ohos.test.continueapp",
wantParam: {"key": "value"}
};
try {
distributedMissionManager.continueMission(parameter, (error) => {
if (error.code != 0) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
}
console.info('continueMission finished')
})
} catch (error) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.continueMission<sup>10+</sup>
continueMission(parameter: ContinueMissionInfo): Promise&lt;void&gt;
Continues a mission on a remote device, with the bundle name specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueMissionInfo](./js-apis-inner-application-continueMissionInfo.md) | Yes | Parameters required for mission continuation.|
**Return value**
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errorcode-DistributedSchedule.md).
| ID| Error Message|
| ------- | -------------------------------------------- |
| 16300501 | The system ability work abnormally. |
| 16300503 | The application is not installed on the remote end and installation-free is not supported. |
| 16300504 | The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. |
| 16300505 | The operation device must be the device where the application to be continued is located or the target device to be continued. |
| 16300506 | The local continuation task is already in progress. |
| 16300507 | Failed to get the missionInfo of the specified bundle name. |
**Example**
```ts
var parameter = {
srcDeviceId: "",
dstDeviceId: "",
bundleName: "ohos.test.continueapp",
wantParam: {"key": "value"}
};
try {
distributedMissionManager.continueMission(parameter)
.then(data => {
console.info('continueMission finished, ' + JSON.stringify(data));
}).catch(error => {
console.error('continueMission failed, cause: ' + JSON.stringify(error));
})
} catch (error) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
}
```
## distributedMissionManager.on('continueStateChange')<sup>10+</sup>
on(type: 'continueStateChange', callback: Callback&lt;{ state: ContinueState, info: ContinuableInfo }&gt;): void
Registers a listener for the mission continuation state of the current application.
**Required permissions**: ohos.permission.MANAGE_MISSIONS
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- |
| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. |
| callback | Callback&lt;{&nbsp;state:&nbsp;[ContinueState](#continuestate10),&nbsp;info:&nbsp;[ContinuableInfo](./js-apis-inner-application-continuableInfo.md)&nbsp;}&gt; | Yes | Callback used to return the mission continuation state and information. |
**Example**
```js
try {
distributedMissionManager.on('continueStateChange', (data) => {
console.info("continueStateChange on:" + JSON.stringify(data));
});
} catch (err) {
console.error("continueStateChange errCode:" + err.code + ",errMessage:" + err.message);
}
```
## distributedMissionManager.off('continueStateChange')<sup>10+</sup>
off(type: 'continueStateChange', callback?: Callback&lt;{ state: ContinueState, info: ContinuableInfo }&gt;): void
Deregisters a listener for the mission continuation state of the current application.
**Required permissions**: ohos.permission.MANAGE_MISSIONS
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- |
| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. |
| callback | Callback&lt;{&nbsp;state:&nbsp;[ContinueState](#continuestate10),&nbsp;info:&nbsp;[ContinuableInfo](./js-apis-inner-application-continuableInfo.md)&nbsp;}&gt; | No | Callback used for the listener to be deregistered. |
**Example**
```js
try {
distributedMissionManager.off('continueStateChange', (data) => {
console.info("continueStateChange on:" + JSON.stringify(data));
});
} catch (err) {
console.error("continueStateChange errCode:" + err.code + ",errMessage:" + err.message);
}
```
## MissionCallback
Defines the callbacks that can be registered as a mission status listener.
......@@ -514,3 +679,14 @@ Defines the parameters required for registering a listener.
| Name | Type | Readable | Writable | Description |
| -------- | ------ | ---- | ---- | ------- |
| deviceId | string | Yes | Yes | Device ID.|
## ContinueState<sup>10+</sup>
Enumerates the mission continuation states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Value | Description |
| ------------- | --------- | ------------------------------------------------------------ |
| ACTIVE | 0 | Mission continuation is activated for the current application. |
| INACTIVE | 1 | Mission continuation is not activated for the current application. |
......@@ -18,7 +18,7 @@ import ability from '@ohos.ability.ability';
Import the following modules based on the actual situation before using the current module:
```ts
import ohos_data_ability from '@ohos.data.dataAbility';
import ohos_data_rdb from '@ohos.data.rdb';
import relationalStore from '@ohos.data.relationalStore'
```
## DataAbilityHelper.openFile
......@@ -1007,4 +1007,4 @@ dataAbilityHelper.executeBatch('dataability:///com.example.jsapidemo.UserDataAbi
| Name| Type| Mandatory| Description|
| ------ | ------ | ------ | ------ |
| [key: string] | number \| string \| boolean \| Array\<string \| number \| boolean\> \| null | Yes| Data stored in key-value pairs.|
\ No newline at end of file
| [key: string] | number \| string \| boolean \| Array\<string \| number \| boolean\> \| null | Yes| Data stored in key-value pairs.|
# ContinuableInfo
The **ContinuableInfo** module provides the mission continuation information to be returned when the listener for listening for the mission continuation state is registered. For details about the registration, see [on('continueStateChange')](js-apis-distributedMissionManager.md#distributedmissionmanageroncontinuestatechange10).
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are system APIs.
## Modules to Import
```ts
import distributedMissionManager from '@ohos.distributedMissionManager';
```
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Type | Readable | Writable | Description |
| -------- | ------ | ---- | ---- | ------- |
| srcDeviceId | string | Yes | Yes | ID of the source device.|
| bundleName | string | Yes | Yes | Name of the bundle to which the mission belongs.|
**Example**
```js
import distributedMissionManager from '@ohos.distributedMissionManager';
try {
distributedMissionManager.on('continueStateChange', (data) => {
console.info("continueStateChange on:" + JSON.stringify(data));
});
} catch (err) {
console.error("continueStateChange errCode:" + err.code + ",errMessage:" + err.message);
}
```
# ContinueMissionInfo
The **ContinueMissionInfo** module defines the parameters required for initiating mission continuation with the bundle name specified. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission10).
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are system APIs.
## Modules to Import
```ts
import distributedMissionManager from '@ohos.distributedMissionManager';
```
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Type | Readable | Writable | Description |
| -------- | ------ | ---- | ---- | ------- |
| srcDeviceId | string | Yes | Yes | ID of the source device.|
| dstDeviceId | string | Yes | Yes | ID of the target device.|
| bundleName | string | Yes | Yes | Name of the bundle to which the mission belongs.|
| wantParam | {[key: string]: any} | Yes | Yes | Extended parameters.|
**Example**
```ts
import distributedMissionManager from '@ohos.distributedMissionManager';
var parameter = {
srcDeviceId: "",
dstDeviceId: "",
bundleName: "ohos.test.continueapp",
wantParam: {"key": "value"}
};
try {
distributedMissionManager.continueMission(parameter, (error) => {
if (error.code != 0) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
}
console.info('continueMission finished')
})
} catch (error) {
console.error('continueMission failed, cause: ' + JSON.stringify(error))
}
```
......@@ -93,7 +93,15 @@ Installs a bundle. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.INSTALL_ENTERPRISE_BUNDLE<sup>10+</sup>
> **NOTE**
>
> Since API version 10, this API can be called with the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
> To install an enterprise application, you must have the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
> To install a common application, you must have the **ohos.permission.INSTALL_BUNDLE** permission.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
......@@ -162,7 +170,15 @@ Installs a bundle. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.INSTALL_ENTERPRISE_BUNDLE<sup>10+</sup>
> **NOTE**
>
> Since API version 10, this API can be called with the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
> To install an enterprise application, you must have the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
> To install a common application, you must have the **ohos.permission.INSTALL_BUNDLE** permission.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
......@@ -226,7 +242,15 @@ Installs a bundle. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**Required permissions**: ohos.permission.INSTALL_BUNDLE or ohos.permission.INSTALL_ENTERPRISE_BUNDLE<sup>10+</sup>
> **NOTE**
>
> Since API version 10, this API can be called with the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
> To install an enterprise application, you must have the **ohos.permission.INSTALL_ENTERPRISE_BUNDLE** permission.
>
> To install a common application, you must have the **ohos.permission.INSTALL_BUNDLE** permission.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
......
......@@ -368,6 +368,7 @@ For details about the audio and video playback demo, see [Audio Playback](../../
| videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scaling type. The default value is **VIDEO_SCALE_TYPE_FIT_CROP**. It is a dynamic attribute<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.|
| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. The default value is **SHARE_MODE**. It is a dynamic attribute<br>and can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.|
| audioRendererInfo<sup>10+</sup> | [audio.AudioRendererInfo](js-apis-audio.md#audiorendererinfo8) | Yes | Yes | Audio renderer information. The default value of **contentType** is **CONTENT_TYPE_MUSIC**, and the default value of **streamUsage** is **STREAM_USAGE_MEDIA**.<br>It can be set only when the AVPlayer is in the initialized state.|
| audioEffectMode<sup>10+</sup> | [audio.AudioEffectMode](js-apis-audio.md#audioeffectmode10) | Yes | Yes | Audio effect mode. The audio effect mode is a dynamic attribute and is restored to the default value **EFFECT_DEFAULT** when **contentType** and **streamUsage** of **audioRendererInfo** are changed. It can be set only when the AVPlayer is in the prepared, playing, paused, or completed state.|
| state<sup>9+</sup> | [AVPlayerState](#avplayerstate9) | Yes | No | AVPlayer state. It can be used as a query parameter when the AVPlayer is in any state. |
| currentTime<sup>9+</sup> | number | Yes | No | Current video playback position, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.<br>The value **-1** indicates an invalid value.<br>In live mode, **-1** is returned by default.|
| duration<sup>9+</sup><a name=avplayer_duration></a> | number | Yes | No | Video duration, in ms. It can be used as a query parameter when the AVPlayer is in the prepared, playing, paused, or completed state.<br>The value **-1** indicates an invalid value.<br>In live mode, **-1** is returned by default.|
......@@ -1018,7 +1019,7 @@ Selects an audio track. This API can be called only when the AVPlayer is in the
```js
let index = 2
avPlayer.setBitrate(index)
avPlayer.selectTrack(index)
```
### deselectTrack<sup>10+</sup><a name=avplayer_deselecttrack></a>
......@@ -1071,7 +1072,7 @@ For details about the error codes, see [Media Error Codes](../errorcodes/errorco
let mediaType = media.MediaType.MEDIA_TYPE_AUD;
let trackIndex = null;
avPlayer.getCurrentTrack(mediaType (err, index) => {
avPlayer.getCurrentTrack(mediaType, (err, index) => {
if (err == null) {
console.info('getCurrentTrack success');
trackIndex = index;
......
......@@ -45,9 +45,9 @@ During RPC or IPC, the sender can use the **write()** method provided by **Messa
### create
static create(): MessageSequence
static create(): MessageSequence
Creates a **MessageSequence** object. This API is a static method.
Creates a **MessageSequence** object. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core
......@@ -2397,7 +2397,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -2415,10 +2415,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -4860,7 +4860,7 @@ Reads the exception information from this **MessageParcel** object.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -4878,10 +4878,10 @@ Reads the exception information from this **MessageParcel** object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -5452,6 +5452,7 @@ Marshals this **Parcelable** object into a **MessageSequence** object.
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
......@@ -5557,6 +5558,7 @@ Marshals the sequenceable object into a **MessageParcel** object.
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
......@@ -5673,7 +5675,7 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -5691,10 +5693,10 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6117,7 +6119,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6135,10 +6137,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6193,7 +6195,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6211,10 +6213,10 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6277,7 +6279,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6295,10 +6297,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6354,7 +6356,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6385,10 +6387,10 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
result.data.reclaim();
result.reply.reclaim();
}
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6435,7 +6437,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6466,10 +6468,10 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
result.data.reclaim();
result.reply.reclaim();
}
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6519,7 +6521,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6537,10 +6539,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6585,7 +6587,7 @@ Obtains the **LocalInterface** object of an interface token.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6603,10 +6605,10 @@ Obtains the **LocalInterface** object of an interface token.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6647,7 +6649,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6665,10 +6667,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6689,7 +6691,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
}
```
### addDeathRecippient<sup>(deprecated)</sup>
### addDeathRecipient<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9).
......@@ -6719,7 +6721,7 @@ Adds a callback for receiving the death notifications of the remote object, incl
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6737,14 +6739,14 @@ Adds a callback for receiving the death notifications of the remote object, incl
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **addDeathRecippient()** of the proxy object is called to add a callback for receiving the death notification of the remove object.
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **addDeathRecipient()** of the proxy object is called to add a callback for receiving the death notification of the remove object.
```ts
class MyDeathRecipient {
......@@ -6786,7 +6788,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6804,10 +6806,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6859,7 +6861,7 @@ Removes the callback used to receive death notifications of the remote object.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6877,10 +6879,10 @@ Removes the callback used to receive death notifications of the remote object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -6927,7 +6929,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -6945,10 +6947,10 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
The proxy object in the **onConnect** callback can be assigned a value only after the ability is connected asynchronously. Then, **getDescriptor()** of the proxy object is called to obtain the interface descriptor of the object.
......@@ -6986,7 +6988,7 @@ Obtains the interface descriptor of this proxy object.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -7004,10 +7006,10 @@ Obtains the interface descriptor of this proxy object.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -7039,7 +7041,7 @@ Checks whether the **RemoteObject** is dead.
```ts
// Import @ohos.ability.featureAbility only for the application developed based on the FA model.
// import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function(elementName, remoteProxy) {
......@@ -7057,10 +7059,10 @@ Checks whether the **RemoteObject** is dead.
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
// Use this method to connect to the ability for the FA model.
// FA.connectAbility(want,connect);
globalThis.context.connectServiceExtensionAbility(want, connect);
```
......@@ -7095,9 +7097,9 @@ A constructor used to create a **MessageOption** object.
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | -------------------------------------- |
| syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.|
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | -------------------------------------- |
| async | boolean | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.|
**Example**
......@@ -7146,7 +7148,7 @@ Checks whether **SendMessageRequest** is called synchronously or asynchronously.
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if **SendMessageRequest** is called synchronously; returns **false** if **SendMessageRequest** is called asynchronously.|
| boolean | Returns **true** if **SendMessageRequest** is called asynchronously; returns **false** if it is called synchronously.|
**Example**
......@@ -7825,7 +7827,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
| Type | Description |
| ---------------------------- | --------------------------------------------- |
| Promise&lt;RequestResult&gt; | Promise used to return the **sendRequestResult** object.|
| Promise&lt;RequestResult&gt; | Promise used to return the **RequestResult** instance. |
**Example**
......@@ -9101,29 +9103,30 @@ Reads data from the shared file associated with this **Ashmem** object.
```ts
import Ability from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate");
globalThis.context = this.context;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy");
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate");
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy");
}
onForeground() {
// Ability has brought to foreground
console.log("[Demo] MainAbility onForeground");
}
onBackground() {
// Ability has back to background
console.log("[Demo] MainAbility onBackground");
}
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate");
globalThis.context = this.context;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy");
}
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate");
}
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy");
}
onForeground() {
// Ability has brought to foreground
console.log("[Demo] MainAbility onForeground");
}
onBackground() {
// Ability has back to background
console.log("[Demo] MainAbility onBackground");
}
};
```
......@@ -236,7 +236,7 @@ Describes the window properties.
| dimBehindValue<sup>(deprecated)</sup> | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value **1** indicates the maximum dimness.<br>**NOTE**<br>This property is supported since API version 7 and deprecated since API version 9.<br> |
| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is **false**. The value **true** means that the screen is always on, and **false** means the opposite.|
| isPrivacyMode<sup>7+</sup> | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is **false**. The value **true** means that the window is in privacy mode, and **false** means the opposite.|
| isRoundCorner<sup>(deprecated)</sup> | boolean | Yes | Yes | Whether the window has rounded corners. The default value is **false**. The value **true** means that the window has rounded corners, and **false** means the opposite.<br>**NOTE**<br>This property is supported since API version 7 and deprecated since API version 9.<br> |
| isRoundCorner<sup>(deprecated)</sup> | boolean | Yes | Yes | Whether the window has rounded corners. The default value is **false**. The value **true** means that the window has rounded corners, and **false** means the opposite.<br>**NOTE**<br>This property is supported since API version 7 and deprecated since API version 9.<br> |
| isTransparent<sup>7+</sup> | boolean | Yes | Yes | Whether the window is transparent. The default value is **false**. The value **true** means that the window is transparent, and **false** means the opposite.|
| id<sup>9+</sup> | number | Yes | No | Window ID. The default value is **0.0**. |
......@@ -2418,6 +2418,53 @@ try {
}
```
### getUIContext<sup>10+</sup>
getUIContext(): UIContext
Obtain a **UIContext** instance.
**Model restriction**: This API can be used only in the stage model.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Return value**
| Type | Description |
| ---------- | ---------------------- |
| [UIContext](./js-apis-arkui-UIContext.md#uicontext) | **UIContext** instance obtained.|
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
// Load content for the main window.
windowStage.loadContent("pages/page2", (err) => {
if (err.code) {
console.error('Failed to load the content. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in loading the content.');
});
// Obtain the main window.
let windowClass = null;
windowStage.getMainWindow((err, data) => {
if (err.code) {
console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
return;
}
windowClass = data;
console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
// Obtain a UIContext instance.
globalThis.uiContext = windowClass.getUIContext();
})
}
};
```
### setUIContent<sup>9+</sup>
setUIContent(path: string, callback: AsyncCallback&lt;void&gt;): void
......@@ -7439,3 +7486,5 @@ controller.animationForHidden = (context : window.TransitionContext) => {
console.info('complete transition end');
};
```
<!--no_check-->
\ No newline at end of file
......@@ -235,7 +235,7 @@ Decompresses a file. This API uses an asynchronous callback to return the result
| Name | Type | Mandatory| Description |
| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| options | [Options](#options) | Yes | Decompression parameters. |
| AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. |
......@@ -287,7 +287,7 @@ Decompresses a file. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| inFile | string | Yes | Path of the file to decompress. The file name extension must be .zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| options | [Options](#options) | Yes | Decompression parameters. |
......
......@@ -33,19 +33,21 @@
- [Gradient Color](ts-universal-attributes-gradient-color.md)
- [Popup Control](ts-universal-attributes-popup.md)
- [Menu Control](ts-universal-attributes-menu.md)
- [Click Control](ts-universal-attributes-click.md)
- [Focus Control](ts-universal-attributes-focus.md)
- [Hover Effect](ts-universal-attributes-hover-effect.md)
- [Component ID](ts-universal-attributes-component-id.md)
- [Touch Target](ts-universal-attributes-touch-target.md)
- [Polymorphic Style](ts-universal-attributes-polymorphic-style.md)
- [Hit Test Control](ts-universal-attributes-hit-test-behavior.md)
- [Background Blur](ts-universal-attributes-backgroundBlurStyle.md)
- [restoreId](ts-universal-attributes-restoreId.md)
- [Foreground Color](ts-universal-attributes-foreground-color.md)
- [Spherical Effect](ts-universal-attributes-sphericalEffect.md)
- [Light Up Effect](ts-universal-attributes-lightUpEffect.md)
- [Pixel Stretch Effect](ts-universal-attributes-pixelStretchEffect.md)
- [Click Effect](ts-universal-attributes-click-effect.md)
- Touch Interactions
- [Click Control](ts-universal-attributes-click.md)
- [Touch Target](ts-universal-attributes-touch-target.md)
- [Hit Test Control](ts-universal-attributes-hit-test-behavior.md)
- Touch Interactions
- [Modal Transition](ts-universal-attributes-modal-transition.md)
- [Sheet Transition](ts-universal-attributes-sheet-transition.md)
- [Obscuring](ts-universal-attributes-obscured.md)
- [Universal Text Attributes](ts-universal-attributes-text-style.md)
- Gesture Handling
- [Gesture Binding Methods](ts-gesture-settings.md)
......@@ -146,12 +148,13 @@
- Canvas Components
- [Canvas](ts-components-canvas-canvas.md)
- [CanvasGradient](ts-components-canvas-canvasgradient.md)
- [CanvasPattern](ts-components-canvas-canvaspattern.md)
- [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md)
- [ImageBitmap](ts-components-canvas-imagebitmap.md)
- [ImageData](ts-components-canvas-imagedata.md)
- [Matrix2D](ts-components-canvas-matrix2d.md)
- [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md)
- [Path2D](ts-components-canvas-path2d.md)
- [Lottie](ts-components-canvas-lottie.md)
- Animation
- [AnimatorProperty](ts-animatorproperty.md)
- [Explicit Animatio](ts-explicit-animation.md)
......
......@@ -48,7 +48,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| ------------- | ------- | ---- | -------- |
| closeEffect | boolean | Yes| Whether to disable the rotation and shadow effects for the component.<br>Default value: **false**<br>**NOTE**<br> This attribute enables or disables the shadow effect only when **trackShadow** is not set.<br> The shadow effect enabled through this attribute is in the default style.|
| valueColors<sup>10+</sup> | Array<[ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient](#lineargradient10)> | Yes| Array of data segment colors. A value of the **ResourceColor** type indicates a solid color, and A value of the **LinearGradient** type indicates a color gradient.|
| trackBackgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Yes| Background color.<br>Default value: **'#081824'**|
| trackBackgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Yes| Background color.<br>The value is in hexadecimal ARGB notation. The first two digits indicate opacity.<br>Default value: **'#08182431'**|
| strokeWidth<sup>10+</sup> | [Length](ts-types.md#Length) | Yes| Stroke width of the border.<br>Default value: **24**<br>Unit: vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>This attribute does not take effect when the data panel type is **DataPanelType.Line**.|
| trackShadow<sup>10+</sup> | [DataPanelShadowOption](#datapanelshadowoption10) | Yes| Shadow style.<br>**NOTE**<br>If this attribute is set to **null**, the shadow effect is disabled.|
......
......@@ -23,9 +23,9 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | number | Yes| Current value of the chart, that is, the position to which the pointer points in the chart. It is used as the initial value of the chart when the component is created.|
| value | number | Yes| Current value of the chart, that is, the position to which the pointer points in the chart. It is used as the initial value of the chart when the component is created.<br>**NOTE**<br>If the value is not within the range defined by the **min** and **max** parameters, the value of **min** is used.|
| min | number | No| Minimum value of the current data segment.<br>Default value: **0**|
| max | number | No| Maximum value of the current data segment.<br>Default value: **100**|
| max | number | No| Maximum value of the current data segment.<br>Default value: **100**<br>**NOTE**<br>If the value of **max** is less than that of **min**, the default values **0** and **100** are used.<br>The values of **max** and **min** can be negative numbers.|
## Attributes
......@@ -36,8 +36,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| value | number | Value of the chart. It can be dynamically changed.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| startAngle | number | Start angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| endAngle | number | End angle of the chart. The value **0** indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **360**<br>Since API version 9, this API is supported in ArkTS widgets.|
| colors | Array&lt;[ColorStop](#colorstop)&gt; | Colors of the chart. Colors can be set for individual segments.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeWidth | Length | Stroke width of the chart.<br>Since API version 9, this API is supported in ArkTS widgets.|
| colors | Array&lt;[ColorStop](#colorstop)&gt; | Colors of the chart. Colors can be set for individual segments.<br>Default value: **Color.Black**<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeWidth | Length | Stroke width of the chart.<br>Default value: **4**<br>Unit: vp<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot be in percentage.|
## ColorStop
......@@ -47,7 +47,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Type | Description |
| --------- | -------------------- | ------------------------------------------------------------ |
| ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | Type of the gradient stop. The first parameter indicates the color value. If it is set to a non-color value, the black color is used. The second parameter indicates the color weight. If it is set to a negative number or a non-numeric value, the color weight is 0, which means that the color is not displayed.|
| ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | Type of the gradient stop. The first parameter indicates the color value. If it is set to a non-color value, the black color is used. The second parameter indicates the color weight. If it is set to a negative number or a non-numeric value, the color weight is 0.|
## Example
......
......@@ -17,31 +17,33 @@ Not supported
ImageAnimator()
Since API version 10, this API is supported in ArkTS widgets.
## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type |Description |
| ---------- | ----------------------- |-------- |
| images | Array&lt;[ImageFrameInfo](#imageframeinfo)&gt; | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. For details, see **ImageFrameInfo**.<br>Default value: **[]**<br>**NOTE**<br>Dynamic update is not supported.|
| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | Playback status of the animation. The default status is **Initial**.<br>Default value: **AnimationStatus.Initial**|
| duration | number | Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in **images**, the setting of this attribute is invalid.<br>Default value: **1000**|
| reverse | boolean | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.<br>Default value: **false**|
| fixedSize | boolean | Whether the image size is the same as the component size.<br> **true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.<br> **false**: The width, height, top, and left attributes of each image must be set separately.<br>Default value: **true**|
| preDecode<sup>(deprecated)</sup> | number | Number of pre-decoded images. The value **2** indicates that two images following the currently playing page will be pre-decoded to improve performance.<br>This API is deprecated since API version 9.<br>Default value: **0**|
| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Status before and after the animation starts. For details about the options, see **FillMode**.<br>Default value: **FillMode.Forwards**|
| iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**|
| images | Array&lt;[ImageFrameInfo](#imageframeinfo)&gt; | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. For details, see **ImageFrameInfo**.<br>Default value: **[]**<br>**NOTE**<br>Dynamic update is not supported.<br>Since API version 10, this API is supported in ArkTS widgets.|
| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | Playback status of the animation. The default status is **Initial**.<br>Default value: **AnimationStatus.Initial**<br>Since API version 10, this API is supported in ArkTS widgets.|
| duration | number | Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in **images**, the setting of this attribute is invalid.<br>Default value: **1000**<br>Since API version 10, this API is supported in ArkTS widgets.|
| reverse | boolean | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.<br>Default value: **false**<br>Since API version 10, this API is supported in ArkTS widgets.|
| fixedSize | boolean | Whether the image size is the same as the component size.<br> **true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.<br> **false**: The width, height, top, and left attributes of each image must be set separately.<br>Default value: **true**<br>Since API version 10, this API is supported in ArkTS widgets.|
| preDecode<sup>(deprecated)</sup> | number | Number of pre-decoded images. The value **2** indicates that two images following the currently playing page will be pre-decoded to improve performance.<br>This API is deprecated since API version 9.<br>Default value: **0** |
| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Status before and after the animation starts. For details about the options, see **FillMode**.<br>Default value: **FillMode.Forwards**<br>Since API version 10, this API is supported in ArkTS widgets.|
| iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1** |
## ImageFrameInfo
| Name | Type | Mandatory| Description|
| -------- | -------------- | -------- | -------- |
| src | string \| [Resource](ts-types.md#resource)<sup>9+</sup> | Yes | Image path. The image format can be .svg, .png, or .jpg. Since API version 9, this attribute accepts paths of the [Resource](ts-types.md#resource) type.|
| width | number \| string | No | Image width.<br>Default value: **0** |
| height | number \| string | No | Image height.<br>Default value: **0** |
| top | number \| string | No | Vertical coordinate of the image relative to the upper left corner of the widget<br>Default value: **0** |
| left | number \| string | No | Horizontal coordinate of the image relative to the upper left corner of the widget<br>Default value: **0** |
| duration | number | No | Playback duration of each image frame, in milliseconds.<br>Default value: **0** |
| src | string \| [Resource](ts-types.md#resource)<sup>9+</sup> | Yes | Image path. The image format can be .svg, .png, or .jpg. Since API version 9, this attribute accepts paths of the [Resource](ts-types.md#resource) type.<br>Since API version 10, this API is supported in ArkTS widgets.|
| width | number \| string | No | Image width.<br>Default value: **0**<br>Since API version 10, this API is supported in ArkTS widgets. |
| height | number \| string | No | Image height.<br>Default value: **0**<br>Since API version 10, this API is supported in ArkTS widgets. |
| top | number \| string | No | Vertical coordinate of the image relative to the upper left corner of the widget<br>Default value: **0**<br>Since API version 10, this API is supported in ArkTS widgets. |
| left | number \| string | No | Horizontal coordinate of the image relative to the upper left corner of the widget<br>Default value: **0**<br>Since API version 10, this API is supported in ArkTS widgets. |
| duration | number | No | Playback duration of each image frame, in milliseconds.<br>Default value: **0** |
## Events
......@@ -49,11 +51,11 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name| Description|
| -------- | -------- |
| onStart(event: () =&gt; void) | Triggered when the animation starts to play.|
| onPause(event: () =&gt; void) | Triggered when the animation playback is paused.|
| onRepeat(event: () =&gt; void) | Triggered when the animation playback is repeated.|
| onCancel(event: () =&gt; void) | Triggered when the animation playback is canceled.|
| onFinish(event: () =&gt; void) | Triggered when the animation playback is complete.|
| onStart(event: () =&gt; void) | Triggered when the animation starts to play.<br>Since API version 10, this API is supported in ArkTS widgets.|
| onPause(event: () =&gt; void) | Triggered when the animation playback is paused.<br>Since API version 10, this API is supported in ArkTS widgets.|
| onRepeat(event: () =&gt; void) | Triggered when the animation playback is repeated. |
| onCancel(event: () =&gt; void) | Triggered when the animation playback is canceled.<br>Since API version 10, this API is supported in ArkTS widgets.|
| onFinish(event: () =&gt; void) | Triggered when the animation playback is complete.<br>Since API version 10, this API is supported in ArkTS widgets.|
## Example
......
# CanvasPattern
**CanvasPattern** represents an object, created by the [createPattern](ts-canvasrenderingcontext2d.md#createpattern) API, describing an image filling pattern based on the image and repetition mode.
> **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Methods
### setTransform
setTransform(transform?: Matrix2D): void
Uses a **Matrix2D** object as a parameter to perform matrix transformation on the current **CanvasPattern** object.
Since API version 9, this API is supported in ArkTS widgets.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| --------- | ----------------------------------------------------- | ---- | ------ | ---------- |
| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No | null | Transformation matrix.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CanvasPatternPage {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private matrix: Matrix2D = new Matrix2D()
private img: ImageBitmap = new ImageBitmap("common/pattern.jpg")
private pattern : CanvasPattern
build() {
Column() {
Button("Click to set transform")
.onClick(() => {
this.matrix.scaleY = 1
this.matrix.scaleX = 1
this.matrix.translateX = 50
this.matrix.translateY = 200
this.pattern.setTransform(this.matrix)
this.context.fillRect(0, 0, 480, 720)
})
.width("45%")
.margin("5px")
Canvas(this.context)
.width('100%')
.height('80%')
.backgroundColor('#FFFFFF')
.onReady(() => {
this.pattern = this.context.createPattern(this.img, 'no-repeat')
this.context.fillStyle = this.pattern
this.matrix.scaleY = 0.5
this.matrix.scaleX = 0.5
this.matrix.translateX = 50
this.matrix.translateY = 50
this.pattern.setTransform(this.matrix)
this.context.fillRect(0, 0, 480, 720)
})
}
.width('100%')
.height('100%')
}
}
```
![CanvasPattern](./figures/canvas_pattern.gif)
......@@ -65,6 +65,6 @@ Since API version 9, this API is supported in ArkTS widgets.
close()
Releases all graphics resources associated with this **ImageBitmap** object. This API is a void API.
Releases all graphics resources associated with this **ImageBitmap** object and sets its width and height to **0**.
Since API version 9, this API is supported in ArkTS widgets.
......@@ -130,7 +130,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description |
| ----------------------- | ----------------------------------- | ------------------------------------------- |
| alignItems<sup>10+</sup> | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the **\<GridCol>** cross axis.<br>Default value: **ItemAlign.Start**<br>**NOTE**<br>In **ItemAlign**, only the enumerated values **Start**, **Center**, **End**, and **Stretch** are supported.<br>The alignment mode of the **\<GridCol>** component can also be set using **alignSelf([ItemAlign](ts-appendix-enums.md#itemalign))**. If both of the preceding methods are used, the setting of **alignSelf(ItemAlign)** prevails.<br>Since API version 10, this API is supported in ArkTS widgets.|
| alignItems<sup>10+</sup> | ItemAlign | Alignment mode of the **\<GridCol>** cross axis.<br>Default value: **ItemAlign.Start**<br>**NOTE**<br>**ItemAlign** supports the following enums: **ItemAlign.Start**, **ItemAlign.Center**, **ItemAlign.End**, and **ItemAlign.Stretch**.<br>The alignment mode of the **\<GridCol>** component can also be set using **alignSelf([ItemAlign](ts-appendix-enums.md#itemalign))**. If both of the preceding methods are used, the setting of **alignSelf(ItemAlign)** prevails.<br>Since API version 10, this API is supported in ArkTS widgets.|
## Events
......
......@@ -42,18 +42,18 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Horizontal | Only horizontal scrolling is supported. |
| Vertical | Only vertical scrolling is supported. |
| None | Scrolling is disabled. |
| Free<sup>(deprecated)</sup> | Vertical or horizontal scrolling is supported.<br>This API is deprecated since API version 9.|
| Free<sup>(deprecated)</sup> | Vertical or horizontal scrolling is supported.<br>This API is deprecated since API version 9. |
## Events
| Name | Description |
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onScrollFrameBegin<sup>9+</sup>(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\<Scroll>** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.<br>\- **offset**: amount to scroll by.<br>\- **state**: current scrolling status.<br>- **offsetRemain**: actual amount by which the component scrolls.<br>**NOTE**<br>1. This event is triggered when scrolling is started by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is not triggered when the controller API is called.<br>3. No out-of-bounds bounce effect is triggered.<br>**NOTE**<br>The value of **offsetRemain** can be a negative value.<br>If the **onScrollFrameBegine** event and **scrollBy** method are used to implement nested scrolling, set the **edgeEffect** attribute of the scrollable child component to **None**. For example, if a **\<List>** is nested in the **\<Scroll>** component, **edgeEffect** of the **\<List>** must be set to **EdgeEffect.None**.|
| onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.<br>**NOTE**<br>1. This event is triggered when scrolling is started by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called.<br>3. The out-of-bounds bounce effect is triggered.|
| onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge.<br>**NOTE**<br>1. This event is triggered when scrolling reaches the edge after being started by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called.<br>3. The out-of-bounds bounce effect is triggered.|
| onScrollEnd<sup>(deprecated) </sup>(event: () => void) | Triggered when scrolling stops.<br>This event is deprecated since API version 9. Use the **onScrollStop** event instead.<br>**NOTE**<br>1. This event is triggered when scrolling is stopped by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called, accompanied by a transition animation.|
| onScrollStart<sup>9+</sup>(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\<Scroll>** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) starts.<br>**NOTE**<br>1. This event is triggered when scrolling is started by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called, accompanied by a transition animation.|
| onScrollStop<sup>9+</sup>(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) stops.<br>**NOTE**<br>1. This event is triggered when scrolling is stopped by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called, accompanied by a transition animation.|
| onScrollFrameBegin<sup>9+</sup>(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when each frame scrolling starts. The input parameters indicate the amount by which the **\<Scroll>** component will scroll. The event handler then works out the amount by which the component needs to scroll based on the real-world situation and returns the result.<br>\- **offset**: amount to scroll by.<br>\- **state**: current scrolling status.<br>- **offsetRemain**: actual amount by which the component scrolls.<br>**NOTE**<br>1. This event is triggered when scrolling is started by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is not triggered when the controller API is called.<br>3. This event does not support the out-of-bounds bounce effect.<br>**NOTE**<br>The value of **offsetRemain** can be a negative value.<br>If the **onScrollFrameBegine** event and **scrollBy** method are used to implement nested scrolling, set the **edgeEffect** attribute of the scrollable child component to **None**. For example, if a **\<List>** is nested in the **\<Scroll>** component, **edgeEffect** of the **\<List>** must be set to **EdgeEffect.None**. |
| onScroll(event: (xOffset: number, yOffset: number) => void) | Triggered to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.<br>**NOTE**<br>1. This event is triggered when scrolling is started by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called.<br>3. This event supports the out-of-bounds bounce effect. |
| onScrollEdge(event: (side: Edge) => void) | Triggered when scrolling reaches the edge.<br>**NOTE**<br>1. This event is triggered when scrolling reaches the edge after being started by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called.<br>3. This event supports the out-of-bounds bounce effect. |
| onScrollEnd<sup>(deprecated) </sup>(event: () => void) | Triggered when scrolling stops.<br>This event is deprecated since API version 9. Use the **onScrollStop** event instead.<br>**NOTE**<br>1. This event is triggered when scrolling is stopped by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called, accompanied by a transition animation. |
| onScrollStart<sup>9+</sup>(event: () => void) | Triggered when scrolling starts and is initiated by the user's finger dragging the **\<Scroll>** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) starts.<br>**NOTE**<br>1. This event is triggered when scrolling is started by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called, accompanied by a transition animation. |
| onScrollStop<sup>9+</sup>(event: () => void) | Triggered when scrolling stops after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](#scroller) stops.<br>**NOTE**<br>1. This event is triggered when scrolling is stopped by the **\<Scroll>** component or other input settings, such as keyboard and mouse operations.<br>2. This event is triggered when the controller API is called, accompanied by a transition animation. |
> **NOTE**
>
......@@ -131,22 +131,24 @@ Obtains the scrolling offset.
### scrollToIndex
scrollToIndex(value: number): void
scrollToIndex(value: number, smooth?: boolean, align?: ScrollAlign): void
Scrolls to the item with the specified index.
When **smooth** is set to **true**, all passed items are loaded and counted in layout calculation. This may result in performance issues if a large number of items are involved.
> **NOTE**
>
> Only the **\<Grid>**, **\<List>**, and **\<WaterFlow>** components are supported.
> This API only works for the **\<Grid>**, **\<List>**, and **\<WaterFlow>** components.
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | ---------------------------------- |
| value | number | Yes | Index of the item to be scrolled to in the list.|
| Name | Type| Mandatory| Description |
| --------------------- | -------- | ---- | ------------------------------------------------------------ |
| value | number | Yes | Index of the item to be scrolled to in the list. |
| smooth<sup>10+ </sup> | boolean | No | Whether to enable the smooth animation for scrolling to the item with the specified index. The value **true** means to enable that the smooth animation, and **false** means the opposite.<br>Default value: **false**<br>**NOTE**<br>Currently, only the **\<List>** component supports this parameter.|
| align<sup>10+ </sup> | [ScrollAlign](#scrollalign10) | No | How the list item to scroll to is aligned with the list.<br>Default value: **ScrollAlign.START**<br>**NOTE**<br>Currently, only the **\<List>** component supports this parameter.|
### scrollBy<sup>9+</sup>
......@@ -158,7 +160,7 @@ Scrolls by the specified amount.
> **NOTE**
>
> Only the **\<Scroll>**, **\<ScrollBar>**, **\<Grid>**, and **\<List>** components are supported.
> This API only works for the **\<Scroll>**, **\<ScrollBar>**, **\<Grid>**, and **\<List>** components.
**Parameters**
......@@ -167,6 +169,14 @@ Scrolls by the specified amount.
| dx | Length | Yes | Amount to scroll by in the horizontal direction. The percentage format is not supported.|
| dy | Length | Yes | Amount to scroll by in the vertical direction. The percentage format is not supported.|
## ScrollAlign<sup>10+ </sup>
| Name | Description |
| ------ | ------------------------------ |
| START | The start edge of the list item is flush with the start edge of the list. |
| CENTER | The list item is centered along the main axis of the list. |
| END | The end edge of the list item is flush with the end edge of the list.|
| AUTO | The list item is automatically aligned.<br>If the list item is fully contained within the display area, no adjustment is performed. Otherwise, the list item is aligned so that its start or end edge is flush with the start or end edge of the list, whichever requires a shorter scrolling distance.|
## Example
### Example 1
......
......@@ -44,7 +44,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| showSideBar | boolean | Whether to display the sidebar.<br>Default value: **true**<br>Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.|
| controlButton | [ButtonStyle](#buttonstyle) | Attributes of the sidebar control button.|
| showControlButton | boolean | Whether to display the sidebar control button.<br>Default value: **true**|
| sideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Width of the sidebar.<br>Default value: **200**<br>Unit: vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value must comply with the width constraints. If it is not within the valid range, the value closest to the set one is used.<br>When set, the width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the width of the sidebar child component takes precedence.|
| sideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Width of the sidebar.<br>Default value: **200**<br>Unit: vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value must comply with the width constraints. If it is not within the valid range, the value closest to the set one is used.<br>The width of the sidebar, whether it is specified or kept at the default, takes precedence over that of the sidebar child components.|
| minSideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Minimum width of the sidebar.<br>Default value: **200**, in vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.<br>When set, the minimum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the minimum width of the sidebar child component takes precedence.|
| maxSideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Maximum width of the sidebar.<br>Default value: **280**, in vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.<br>When set, the maximum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the maximum width of the sidebar child component takes precedence.|
| autoHide<sup>9+</sup> | boolean | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.<br>Default value: **true**<br>**NOTE**<br>The value is subject to the **minSideBarWidth** attribute method. If it is not set in **minSideBarWidth**, the default value is used.<br>Whether the sidebar should be hidden is determined when it is being dragged. When its width is less than the minimum width, the damping effect is required to trigger hiding (a distance out of range).|
......
......@@ -29,8 +29,8 @@ You can bind a popup to a component, specifying its content, interaction logic,
| messageOptions<sup>10+</sup> | [PopupMessageOptions](#popupmessageoptions10) | No | Parameters of the popup message. |
| targetSpace<sup>10+</sup> | [Length](ts-types.md#length) | No | Space between the popup and the target. |
| placement<sup>10+</sup> | [Placement](ts-appendix-enums.md#placement8) | No | Position of the popup relative to the target. The default value is **Placement.Bottom**.<br>If both **placementOnTop** and **placement** are set, the latter prevails.|
| offset<sup>10+</sup> | [Position](ts-types.md#position8) | No | Offset of the popup relative to the display position specified by **placement**. |
| enableArrow<sup>10+</sup> | boolean | No | Whether to display the arrow.<br>Default value: **true**|
| offset<sup>10+</sup> | [Position](ts-types.md#position8) | No | Offset of the popup relative to the display position specified by **placement**.<br>**NOTE**<br>This parameter cannot be set in percentage.|
| enableArrow<sup>10+</sup> | boolean | No | Whether to display the arrow.<br>Default value: **true**|
## PopupMessageOptions<sup>10+</sup>
......@@ -53,7 +53,7 @@ You can bind a popup to a component, specifying its content, interaction logic,
| maskColor<sup>(deprecated)</sup> | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup mask.<br>**NOTE**<br>This parameter is deprecated since API version 10. You are advised to use **mask** instead.|
| mask<sup>10+</sup> | boolean \| [ResourceColor](ts-types.md#resourcecolor) | No | Whether to apply a mask to the popup. The value **true** means to apply a transparent mask to the popup, **false** means not to apply a mask to the popup, and a color value means to apply a mask in the corresponding color to the popup.|
| targetSpace<sup>10+</sup> | [Length](ts-types.md#length) | No | Space between the popup and the target. |
| offset<sup>10+</sup> | [Position](ts-types.md#position8) | No | Offset of the popup relative to the display position specified by placement.|
| offset<sup>10+</sup> | [Position](ts-types.md#position8) | No | Offset of the popup relative to the display position specified by **placement**.<br>**NOTE**<br>This parameter cannot be set in percentage.|
## Example
```ts
......
......@@ -21,7 +21,8 @@ When the **compressFile()** API is called, the file to compress does not exist.
**Solution**
1. Make sure the source file exists.
2. Make sure the path of the source file exists and the path is the correct sandbox path.
2. Ensure that the source file is in ZIP format.
3. Make sure the path of the source file exists and the path is the correct sandbox path.
## 900002 Invalid Destination File
......@@ -61,5 +62,5 @@ This error code is reported when the format of the source file is incorrect or t
**Solution**
1. Check whether the source file format is ZIP.
1. Check whether the source file is in ZIP format.
2. Check whether the source file is complete. If the file is downloaded from the network, ensure that the file download is complete before calling the **decompressFile** API.
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册