diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index 740e2bbdaf4a1aadc015c9e683da5f02940ab61a..c8989927e1f804c14effdfe071082ed15410ea80 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -1,21 +1,19 @@ # FAQs -- [Programming Languages](faqs-language.md) -- [Ability Framework Development](faqs-ability.md) +- [Ability Development](faqs-ability.md) +- [Bundle Management Development](faqs-bundle-management.md) - [Resource Manager Development](faqs-globalization.md) -- [ArkUI (ArkTS) Development](faqs-ui-ets.md) -- [ArkUI Web Component (ArkTS) Development](faqs-web-arkts.md) -- [ArkUI (JavaScript) Development](faqs-ui-js.md) - [Common Event and Notification Development](faqs-event-notification.md) -- [Graphics and Image Development](faqs-graphics.md) -- [Media Development](faqs-media.md) +- [Graphics Development](faqs-graphics.md) +- [Window Management Development](faqs-window-manager.md) +- [Multimedia Development](faqs-multimedia.md) - [Basic Security Capability Development](faqs-security.md) -- [Application Access Control Development](faqs-ability-access-control.md) +- [Ability Access Control Development](faqs-ability-access-control.md) - [Data Management Development](faqs-distributed-data-management.md) - [File Management Development](faqs-file-management.md) - [Network Management Development](faqs-network-management.md) - [DFX Development](faqs-dfx.md) -- [Native API Usage](faqs-native.md) +- [Pan-Sensor Development](faqs-sensor.md) - [Startup Development](faqs-startup.md) -- [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) -- [IDE Usage](faqs-ide.md) +- [Distributed Device Development](faqs-distributed-device-profile.md) +- [Usage of Third- and Fourth-Party Libraries](faqs-third-fourth-party-library.md) \ No newline at end of file diff --git a/en/application-dev/faqs/faqs-ability-access-control.md b/en/application-dev/faqs/faqs-ability-access-control.md index f336120a2b131eb75604fa3e51b1b8ff0130072e..51b3310de190a521b47471d607134c014a79be8c 100644 --- a/en/application-dev/faqs/faqs-ability-access-control.md +++ b/en/application-dev/faqs/faqs-ability-access-control.md @@ -1,4 +1,4 @@ -# Application Access Control Development +# Ability Access Control Development ## Can the app listen for the permission change after its permission is modified in Settings? diff --git a/en/application-dev/faqs/faqs-ability.md b/en/application-dev/faqs/faqs-ability.md index aab3ecc19aff704dbc34b9f7aa4d174344735453..b6901e40e6d84c622c41e487e30c62ba87a28ff4 100644 --- a/en/application-dev/faqs/faqs-ability.md +++ b/en/application-dev/faqs/faqs-ability.md @@ -1,68 +1,124 @@ -# Ability Framework Development +# Ability Development -## Is a guide similar to the Data ability development in the FA model available for the stage model? +## How do I obtain a notification when the device orientation changes? -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -A guide is available for the **DataShareExtensionAbility** class, which provides APIs for sharing data with other applications and managing the data, in the stage model. +**Solution** -Reference: [DataShare Development](../database/database-datashare-guidelines.md) +Use the **UIAbility.onConfigurationUpdate\(\)** callback to subscribe to system environment variable changes (including the language, color mode, and screen orientation). -## What should I do if the UI does not respond when an ability is started? +**Reference** -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +[Subscribing to System Environment Variable Changes](../application-models/subscribe-system-environment-variable-changes.md#using-uiability-for-subscription) -1. If the ability is started using **startAbility**, check whether the **abilityName** field in **want** uses the bundle name as the prefix. If yes, delete the bundle name. +## How do I redirect a user to a specified page after they touch a service widget? -2. Make sure the ability's home page file configured by **onWindowStageCreate** in the **MainAbility.ts** file is defined in the **main_pages.json** file. +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -3. You are advised to use the SDK and OpenHarmony SDK versions released on the same day. +**Solution** -Reference: [Release Testing Version](https://gitee.com/openharmony-sig/oh-inner-release-management/blob/master/Release-Testing-Version.md) +Configure a widget event with the redirected-to UIAbility specified, and call **loadContent** in the **onWindowStageCreate\(\)** callback of the target UIAbility to redirect to the specified page. -## How do I set the UI of an ability to transparent? +**Reference** -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 +[Developing Widget Events](../application-models/arkts-ui-widget-configuration.md) -Set the background color of the top container component to transparent, and then set the **opacity** attribute of the XComponent to **0.01**. +## How do I create a background service in the stage model? -Example: +Applicable to: OpenHarmony 3.2 Beta5 -``` -build() { - Stack() { - XComponent({ - id: 'componentId', - type: 'surface', - }) - .width('100%') - .height('100%') - .opacity(0.01) - // Page content - } - .width('100%') - .height('100%') - .backgroundColor('rgba(255,255,255, 0)') -} -``` +**Symptom** + +**ServiceExtensionAbility** in the stage model is a system API. Therefore, third-party applications cannot use it to create a background service. + +**Solution** + +Create a background task to provide the background service. + +**Reference** + +[Background Task](../task-management/background-task-overview.md) + +## Can I create a UIAbility and specify the process to run the UIAbility in the FA and Stage models? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +Yes. + +- FA model + + The FA model supports multiple processes. By default, all components of an application run in the same process. This default scenario is suitable for most applications. To run a specific component in an independent process, configure the **process** tag under **ability** in the configuration file. Note that this tag is available only for system applications. + +- Stage model + + The stage model supports multiple processes. The process model is defined by the system, and third-party applications cannot be configured with multiple processes. To customize an independent process, you must request special permissions, and then specify the **process** tag under **module** in the configuration file. This tag specifies the process in which all the abilities in an HAP run. If this tag is not set, the bundle name is used as the process name by default. + + +## What are the differences between the stage model and the FA model in intra-process object sharing? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +- In the stage model, multiple application components share the same ArkTS engine instance. Therefore, they can easily share objects and state with each other. This also reduces the memory usage of complex applications. +- In the FA model, each application component exclusively uses an ArkTS engine instance. Therefore, you are advised to use the stage model when developing complex applications in distributed scenarios. + +**Reference** + +[Data Synchronization Between UIAbility and UI](../application-models/uiability-data-sync-with-ui.md) + +## How do I use the lifecycle functions of AbilityStage? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +Add the field **"srcEntry": "./ets/myabilitystage/MyAbilityStage.ts"** under **module** in the **module.json5** file. + +**Reference** + +[AbilityStage Component Container](../application-models/abilitystage.md) + + +## How do I delete the mission snapshot in Recents after terminateself is called in the multiton scenario? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +You can set **removeMissionAfterTerminate** to **true** in the **module.json5** file. + +## Why can't I start a UIAbility instance by using startAbility\(\)? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +- If the UIAbility is started using **startAbility**, check whether the **abilityName** field in **want** uses the bundle name as the prefix. If yes, delete the bundle name. +- Make sure the UIAbility's home page file configured by **onWindowStageCreate** in the **MainAbility.ts** file is defined in the **main\_pages.json** file. You are advised to use the SDK and OpenHarmony SDK versions released on the same day. ## How do I prevent "this" in a method from changing to "undefined" when the method is called? -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** -Method 1: Add **.bind(this)** when calling the method. +Method 1: Add **.bind\(this\)** when calling the method. Method 2: Use the arrow function. -## What should I do when the message "must have required property 'startWindowIcon'" is displayed? +## What should I do when the error message "must have required property 'startWindowIcon'" is displayed during the UIAbility startup? -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -Configure the **startWindowIcon** attribute under **abilities** in the **module.json5** file. +**Solution** -Reference: [Application Package Structure (Stage Model)](../quick-start/module-configuration-file.md) +Configure the **startWindowIcon** attribute under **abilities** in the **module.json5** file. -Example: +**Example** ``` { @@ -77,138 +133,226 @@ Example: } ``` -## How do I obtain a notification when the device orientation changes? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 +**Reference** -Implement the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the orientation and density) change. +[module.json5 Configuration File](../quick-start/module-configuration-file.md) ## Can I obtain the context through globalThis in the stage model? -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +Do not use **globalThis** to obtain the context in the stage model. + +This is because all the processes of an application share a JS VM instance in the stage model. Multiple abilities can run on these processes and share the same global object. If **globalThis** is used, the context of different abilities of the same JS VM instance may be returned. + +**Reference** + +[Data Synchronization Between UIAbility and UI](../application-models/uiability-data-sync-with-ui.md) -Do not use **globalThis** to obtain the context in the stage model. This is because all the processes of an application share a JS VM instance in the stage model. Multiple abilities can run on these processes and share the same global object. If **globalThis** is used, the context of different abilities of the same JS VM instance may be returned. +## What should I do when an error indicating too large size is reported during HAP deployment? -Reference of the recommended operation: [Context (Stage Model)](../application-models/application-context-stage.md) +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -## How do I obtain the HAP installation path of application B from application A? +**Symptom** -Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9 +During HAP deployment, the following error message is displayed: -First, request the system permission. For details, see [Having Your App Automatically Signed](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465). Then, import the **bundle** module, and call **bundle.getApplicationInfo()** to obtain application information based on the bundle name. Finally, use **application.moduleSourceDirs** to obtain the application storage path. +Failure\[INSTALL\_FAILED\_SIZE\_TOO\_LARGE\] error while deploying hap? + +**Solution** + +You can split the HAP into multiple HAPs. ## How is data returned when startAbilityForResult is called? -Applicable to: OpenHarmony SDK3.0, stage model of API version 9 +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -The callee uses **AbilityContext.terminateSelfWithResult** to destroy its ability and pass parameters to **startAbilityForResult**. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextterminateselfwithresult). +**Solution** -## Can the lifecycle callback of a released FA widget be triggered when the widget is displayed in the service center so that the user login information can be obtained without opening the FA application? +The target UIAbilities uses **AbilityContext.terminateSelfWithResult** to terminate itselef and pass the result to **startAbilityForResult**. -Applicable to: OpenHarmony SDK 3.2.5.5, FA model of API version 8 +**Reference** -After a widget is added, the **oncreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed. +[Starting UIAbility in the Same Application and Obtaining the Return Result](../application-models/uiability-intra-device-interaction.md) -## How do I obtain the context? -Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9 +## How do I obtain the system timestamp? -You can use **this.context** to obtain the context in the **MainAbility.ts** file or call **getContext(this)** to obtain the context on the component page. +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -## What should I do when undefined is displayed for the calling of **abilityAccessCtrl.grantUserGrantedPermission** during API version 8 syntax verification? +**Solution** -Applicable to: OpenHarmony SDK 3.0, FA model of API version 8 +Use **getCurrentTime** of **@ohos.systemDateTime** to obtain the system time and time zone. -**abilityAccessCtrl.grantUserGrantedPermission** is a system API. It is not available in the public SDK, which is provided as default on DevEco Studio. To use system APIs, switch to the full SDK. For details, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md). +**Example** -## Which of the following Extension abilities are available in the public SDK: ServiceExtensionAbility, FormExtensionAbility, and DataShareExtensionAbility? +Use the **@ohos.systemDateTime** API as follows: -Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 + ``` + try { + systemDateTime.getCurrentTime(true, (error, time) => { + if (error) { + console.info(`Failed to get currentTime. message: ${error.message}, code: ${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); + } catch(e) { + console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`); + } + ``` -Among the aforementioned Extension abilities, only **FormExtensionAbility** is available in the public SDK. **ServiceExtensionAbility** and **DataShareExtensionAbility** are system APIs and available only in the full SDK. -Public SDK: intended for application developers and does not contain system APIs that require system permissions. +**Reference** -Full SDK: intended for original equipment manufacturers (OEMs) and contains system APIs that require system permissions. +[System time and time zone] (../reference/apis/js-apis-system-date-time.md#systemdatetimegetcurrenttime) -## Why can't I play GIF images cyclically on the widget? +## How do I obtain the cache directory of the current application? -Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -The system does not support the display of GIF images on the widget. +**Solution** -## How do I implement service login by touching a widget? +Use **Context.cacheDir** to obtain the cache directory of the application. -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 +**Reference** -You can start an ability upon the touch and implement service login in the ability. +[Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path) -## How do I redirect to the application details page in Settings? +## In which JS file is the service widget lifecycle callback invoked? -Applicable to: OpenHarmony SDK 3.2.6.5 +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -Refer to the following code: +**Solution** -``` -this.context.startAbility( -{ - action: "action.settings.app.info", - parameters: { "settingsParamBundleName": "your app bundlename" } -}) -``` +When a widget is created, a **FormAblity.ts** file is generated, which contains the widget lifecycle. -## How do I listen for screen rotation events? +**Reference** -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 +[FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md) -Refer to the following code: +## What should I do when the compilation on DevEco Studio fails while ServiceExtensionAbility and DataShareExtensionAbility APIs are used? -``` -let listener = mediaquery.matchMediaSync('(orientation: landscape)') -onPortrait(mediaQueryResult) { -if (mediaQueryResult.matches) { -// Do something here. - } else { -// Do something here. - } -} -listener.on('change', onPortrait) -``` +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Symptom** + +After the **ServiceExtensionAbility** and **DataShareExtensionAbility** APIs are used, DevEco Studio reports an error indicating that the compilation fails. + +**Cause** + +The following types of SDKs are provided: + +- Public SDK: intended for application developers and does not contain system APIs that require system permissions. +- Full SDK: intended for original equipment manufacturers (OEMs) and contains system APIs that require system permissions. + +The SDK downloaded using DevEco Studio is the public SDK. + +**Solution** + +Third-party application cannot use **ServiceExtensionAbility** and **DataShareExtensionAbility**. To develop a system application, first [download the full SDK](../quick-start/full-sdk-switch-guide.md). + +## How do I obtain the temp and files paths at the application level? + +Applicable to: OpenHarmony 3.2 Beta5 + +**Solution** + +Obtain them from the application context. Specifically, use **this.context.getApplicationContext.tempDir** i to obtain the **temp** path, and use **this.context.getApplicationContext.filesDir** to obtain the **files** path. + +**Reference** + +[Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path) + + +## Can the lifecycle callback of a released FA widget be triggered when the widget is displayed in the service center so that the user login information can be obtained without opening the FA application? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) -## How do I control the shadow background size during checkbox selection? +**Solution** -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 +After a widget is added, the **onCreate()** lifecycle is triggered so that related user information (silent login) can be displayed even when the application is not started. However, users must manually add the widget after the application is installed. -Set the **padding** attribute of the **\** component to control the shadow size. +## How do I implement service login by touching a widget? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +To create a service widget in the FA model, perform the following steps: + +1. Implement lifecycle callbacks for the widget. + +2. Configure the widget configuration file. + +3. Persistently store widget data. -## How do I set the widget background to transparent? +4. Update widget data. -Applicable to: OpenHarmony SDK 3.2.5.5 +5. Develop the widget UI page. -1. Create the **widget/resources/styles/default.json** file in the root directory of the widget. +6. Develop a widget event. You can start a UIAbility upon the touch and implement service login in the UIAbility. -2. Add the following code to the **default.json** file: +**Reference** + +[Widget Development in the FA Model](../application-models/widget-development-fa.md) + +## How do I redirect to the application details page in Settings? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +Refer to the following code: ``` -{ - "style": { - "app_background": "#00000000" - } -} +this.context.startAbility( +{ + action: "action.settings.app.info", + parameters: { "settingsParamBundleName": "your app bundlename" } +}) ``` -## How do I pass parameters for FA widgets? - -Applicable to: OpenHarmony SDK 3.2.5.5 +## How do I get UIAbilityContext within the @Component component in the stage model? -Use **featureAbility.getWant()** and **featureAbility.getContext()** to send data through **router** in the JSON file and use **featureAbility** to receive data in the JS file. +Applicable to: OpenHarmony 3.2 Beta5 (API version 9) -## How do I trigger router.disableAlertBeforeBackPage and router.enableAlertBeforeBackPage? +**Solution** -Applicable to: OpenHarmony SDK 3.2.5.5 +You can use **UIAbility.Context** to obtain the context. -The following conditions must be met: +**Example** -1. Before the redirection to the previous page, a confirm dialog box will be displayed. Note that **router.disableAlertBeforeBackPage** is used to disable the display of a confirm dialog box before returning to the previous page (default), and **router.enableAlertBeforeBackPage** is used to enable the display. +``` +import UIAbility from '@ohos.app.ability.UIAbility'; + +let UIAbilityContext = UIAbility.context; +let ApplicationContext = UIAbility.context.getApplicationContext(); +@Entry +@Component +struct AbilityContextTest { + // abilityContext + @State UIabilityInfo: string = 'Obtaining abilityInfo' + UIabilityContext: UIAbilityContext + + aboutToAppear() { + // Use getContext to obtain the context and convert it to abilityContext. + this.UIabilityContext = getContext(this) as UIAbilityContext + } -2. The system return key is used. + build() { + Row() { + Column({ space: 20 }) { + Text(this.abilityInfo) + .fontSize(20) + .onClick(()=>{ + this.UIabilityInfo = JSON.stringify(this.UIabilityContext.UIabilityInfo) + console.log(`ContextDemo abilityInfo= ${this.UIabilityInfo}`) + }) + } + .width('100%') + } + .height('100%') + } +} +``` diff --git a/en/application-dev/faqs/faqs-bundle-management.md b/en/application-dev/faqs/faqs-bundle-management.md new file mode 100644 index 0000000000000000000000000000000000000000..71b1e01ffcffea415266fb90213fc722e4f5b628 --- /dev/null +++ b/en/application-dev/faqs/faqs-bundle-management.md @@ -0,0 +1,126 @@ +# Bundle Management Development + +## How do I determine whether an application is a system application? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +Use **bundleManager.getApplicationInfo** (available only for system applications) to obtain application information, and check the value of **systemApp** in the information. The application is a system application if the value is **true**. + +**Reference** + +[bundleManager](../reference/apis/js-apis-bundleManager.md) + +## How do I obtain the version code and version name of an application? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +Use **bundleManager.getBundleInfoForSelf\(\)** to obtain the bundle information, which contains the version code (specified by **BundleInfo.versionCode**) and version name (specified by **BundleInfo.versionName**) . + +**Example** + +``` +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; +try { + bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { + const versionCode = data.versionCode; + const versionName = data.versionName; + hilog.info(0x0000, 'testTag', `successfully. versionCode: ${versionCode}, versionName: ${versionName}`); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'failed. Cause: %{public}s', err.message); + }); +} catch (err) { + hilog.error(0x0000, 'testTag', 'failed: %{public}s', err.message); +} +``` + +**Reference** + +[getBundleInfoForSelf](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundleinfoforself) + +## How do I obtain the bundle name of the current application? + +Applicable to: OpenHarmony 3.2 Beta5 (API version 9) + +**Solution** + +Obtain the bundle name from **UIAbilityContext.abilityInfo.bundleName**. + +**Example** + +``` +import common from '@ohos.app.ability.common'; +const context = getContext(this) as common.UIAbilityContext +console.log(`bundleName: ${context.abilityInfo.bundleName}`) +``` + +**Reference** + +[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontext) and [AbilityInfo](../reference/apis/js-apis-bundleManager-abilityInfo.md#abilityinfo) + +## How do I obtain the application version number, version name, and screen resolution? + +Applicable to: OpenHarmony 3.2 Beta5 + +**Solution** + +1. Obtain the bundle information from the **@ohos.bundle.bundleManager** module. + + The bundle information contains the application version number and version name. + + ``` + import bundleManager from '@ohos.bundle.bundleManager'; + ... + bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo)=>{ + let versionName = bundleInfo.versionName; // Application version name. + let versionNo = bundleInfo.versionCode; // Application version number. + }).catch((error)=>{ + console.error("get bundleInfo failed,error is "+error) + }) + ``` + +2. Obtain **screenDensity** from the **@ohos.app.ability.Configuration** module. **screenDensity** contains the screen resolution information. + + ``` + import common from '@ohos.app.ability.common'; + ... + let context = getContext(this) as common.UIAbilityContext; + let screenDensity = context.config.screenDensity; + ``` + + +## How do I obtain the source file path of the current application? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +- Method 1: Use the application context to obtain the source file path. + + ``` + this.uiAbilityContext.abilityInfo.applicationInfo.codePath + ``` + +- Method 2: Use **@ohos.bundle.bundleManager** to obtain the source file path. + + 1. Import the **@ohos.bundle.bundleManager** module and use **bundleManager.getBundleInfoForSelf\(\)** to obtain the bundle information. + 2. Obtain the source file path from **bundleInfo.appInfo.codePath**. + + ``` + import bundleManager from '@ohos.bundle.bundleManager'; + bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo)=>{ + this.sourcePath = bundleInfo.appInfo.codePath; + }) + ``` + + +## Can I obtain the HAP information of other applications from the current application? + +Applicable to: OpenHarmony 3.2 Beta (API version 9) + +According to the OpenHarmony security design specifications, the SDK does not provide APIs for third-party applications to obtain bundle information (including but not limited to the application name and version number) of other applications. diff --git a/en/application-dev/faqs/faqs-bundle.md b/en/application-dev/faqs/faqs-bundle.md deleted file mode 100644 index fda41c42bccc357d6b8800ce3f5401e1e2abbceb..0000000000000000000000000000000000000000 --- a/en/application-dev/faqs/faqs-bundle.md +++ /dev/null @@ -1,31 +0,0 @@ -# Bundle Management Development - -## How do I obtain the version code and version name of an application? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Use **bundle.getBundleInfo()** to obtain the bundle information, which contains the version code and version name. - -Reference: [Bundle](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo) - -## How do I obtain the bundle name of an application? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Obtain the bundle name through **context.abilityInfo.bundleName**. - -Reference: [AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md) - -## How do I obtain an application icon? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Use **bundle.getAbilityIcon** to obtain the application icon. To use this API, you must configure the permission **ohos.permission.GET_BUNDLE_INFO**. - -Reference: [Bundle](../reference/apis/js-apis-Bundle.md#bundlegetbundleinfo) - -## How do I determine whether an application is a system application? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -Use **bundle.getApplicationInfo** to obtain the application information, and then check the value of **systemApp** in the information. The application is a system application if the value is **true**. diff --git a/en/application-dev/faqs/faqs-distributed-device-profile.md b/en/application-dev/faqs/faqs-distributed-device-profile.md new file mode 100644 index 0000000000000000000000000000000000000000..8473e3d4bfcb36c02d3260312cf5379cb436d8a6 --- /dev/null +++ b/en/application-dev/faqs/faqs-distributed-device-profile.md @@ -0,0 +1,9 @@ +# Distributed Device Development + +## How do I view the IMEI of an OpenHarmony device? + +Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) + +**Solution** + +Obtain the device IMEI from the **HUKS\_TAG\_ATTESTATION\_ID\_IMEI** parameter of the **HuksTag** API. [Reference](../reference/apis/js-apis-huks.md) diff --git a/en/application-dev/faqs/faqs-graphics.md b/en/application-dev/faqs/faqs-graphics.md index 7eeba0644721dbf77174680f3c6c6d0ac0db05cf..9469a35736ef859342d2c24bdcb9780e94445bf8 100644 --- a/en/application-dev/faqs/faqs-graphics.md +++ b/en/application-dev/faqs/faqs-graphics.md @@ -1,90 +1,92 @@ -# Graphics and Image Development +# Graphics Development -## Why do the isStatusBarLightIcon and isNavigationBarLightIcon attributes not take effect when window.setSystemBarProperties() is called? +## How do I obtain the DPI of a device? -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model) -In effect, the **isStatusBarLightIcon** and **isNavigationBarLightIcon** attributes turn the font white when set to **true**. If **statusBarContentColor** is also set in **window.setSystemBarProperties()**, the **isStatusBarLightIcon** attribute does not take effect. Similarly, if **navigationBarContentColor** is set, the **isNavigationBarLightIcon** attribute does not take effect. +**Solution** -## How do I set the style of the system bar? +Import the **@ohos.display** module and call the **getDefaultDisplaySync\(\)** API. -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 +**Example** -Import the **\@ohos.window** module, and call **window.setSystemBarProperties()**. +``` +import display from '@ohos.display'; +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); + console.info('Test densityDPI:' + JSON.stringify(displayClass.densityDPI)); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +} +``` ## How do I hide the status bar to get the immersive effect? -Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 - -1. Use the **onWindowStageCreate** to obtain a **windowClass** object. - - ```ts - onWindowStageCreate(windowStage) { - // When the main window is created, set the main page for this ability. - console.log("[Demo] EntryAbility onWindowStageCreate") - windowStage.getMainWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the main window.') - return; - } - // Obtain a windowClass object. - globalThis.windowClass = data; - }) - } - ``` - -2. Enable the full-screen mode for the window and hide the status bar. - - ```ts - globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); - }); - ``` +Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model) + +**Solution** + +1. Use **onWindowStageCreate** to obtain a **windowClass** object. + + ``` + onWindowStageCreate(windowStage) { + // When the main window is created, set the main page for this ability. + console.log("[Demo] MainAbility onWindowStageCreate") + windowStage.getMainWindow((err, data) => { + if (err.code) { + console.error('Failed to obtain the main window.') + return; + } + // Obtain a windowClass object. + globalThis.windowClass = data; + }) + } + ``` + +2. Enable the full-screen mode for the window and hide the status bar. + + ``` + globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => { + if (err.code) { + console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); + }); + ``` + ## How do I obtain the window width and height? -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 +Applicable to: OpenHarmony SDK 3.2 Beta5 (API version 9, stage model) -Use **window.getProperties()** to obtain the window properties. The **windowRect** field in the properties specifies the window width and height. +**Solution** -Example: +Import the **@ohos.window** module, obtain a **Window** object, and use **getWindowProperties\(\)** of the object to obtain the window properties. The **windowRect** field in the properties specifies the window width and height. +**Example** -```ts -let promise = windowClass.getProperties(); -promise.then((data)=> { - console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data.windowRect)); -}).catch((err)=>{ - console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); -}); ``` - -## How do I set the color of the system bar? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -Refer to the following code: - - -```ts -window.getTopWindow(globalThis.mainContext).then(win => { - var systemBarProperties = { - statusBarColor: '#19B6FF', // Set the background color of the status bar. - navigationBarColor: '#19B6FF', // Set the background color of the navigation bar. - isStatusBarLightIcon: false, // Set the icon on the status bar not to be highlighted. - isNavigationBarLightIcon: true, // Set the icon on the navigation bar to be highlighted. - statusBarContentColor: '#0D0500', // Set the text color of the status bar. - navigationBarContentColor: '#FFA500' // Set the text color of the navigation bar. - }; - win.setSystemBarProperties(systemBarProperties).catch(err => { - INDEX_LOGGER.info(`set System Bar Properties failed:${err}`) - }) -}) -.catch(err => { - INDEX_LOGGER.info(`get top window failed:${err}`) -}) +import window from '@ohos.window'; +let windowClass = null; +try { + let promise = window.getLastWindow(this.context); + promise.then((data)=> { + // Obtain a Window object. + windowClass = data; + try { + // Obtain the window properties. + let properties = windowClass.getWindowProperties(); + let rect = properties.windowRect; + // rect.width: window width; rect.height: window height. + } catch (exception) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(exception)); + } + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + });} catch (exception) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); +} ``` diff --git a/en/application-dev/faqs/faqs-ide.md b/en/application-dev/faqs/faqs-ide.md deleted file mode 100644 index a9bbf987a8f098a5016278609cb7d9ebfdd632b8..0000000000000000000000000000000000000000 --- a/en/application-dev/faqs/faqs-ide.md +++ /dev/null @@ -1,79 +0,0 @@ -# IDE Usage - -## What should I do if the error message "npm ERR! code SELF_SIGNED_CERT_IN_CHAIN" is displayed? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -1. Run **npm config set strict-ssl=false** on the DevEco Studio terminal. - -2. Run **npm install** on the DevEco Studio terminal. - -## After manual updating of a DevEco Studio SDK, the error message "Cannot find module 'xxx\ets\x.x.x.x\build-tools\ArkTS-loader\node_modules\webpack\bin\webpack.js'" is displayed during HAP building. What should I do? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -1. Run **npm install** in the **ets\x.x.x.x\build-tools\ets-loader** directory of the SDK. - -2. Run **npm install** in the **js\x.x.x.x\build-tools\ace-loader** directory of the SDK. Perform HAP building again. - -## How do I pack a HAP file through the command line? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -Method 1: Run **hvigor assembleHap**. - -Method 2: In **scripts** of the project **package.json** file, define the build task script and run **npm buildOhosHaps**. The **buildOhosHaps** field can be customized. - - -``` -"scripts": { - "buildOhosHaps": "hvigor assembleHap" -}, -``` - -## How do I select API version 9 when creating a project in DevEco Studio? - -Applicable to: DevEco Studio 3.0 Beta4 3.0.0.993(B06) - -When creating a project in DevEco Studio, make sure you are on the **OpenHarmony** tab page. - -## What should I do if no callback is received and no error code is returned for downloads? - -Applicable to: all versions - -1. Re-install hdc_std and set up the device connection again. -2. Run **hdc_std shell hilog -Q pidoff** to disable log log flow control. - -## What should I do if the "error: unknow option. usage: aa start \" message is displayed after I click Run in DevEco Studio? - -Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 - -This issue occurs when the parameter in the **aa** command is invalid and therefore the target application fails to be opened. - -To fix this issue, use either of the following methods: - -1. Make sure the SDK version and the OS version are the same. - -2. Touch the application icon on the device to manually open the application. - -## What should I do if "The hdc_std version of the SDK does not match the hdcd version of the device." message is displayed when I run an application in DevEco Studio? - -Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 - -This issue occurs when the hdc and hdcd versions do not match. Update Dev Eco Studio to 3.0.1.993 or later. - -After the update, Dev Eco Studio will still indicate the version mismatch, but will not block the running. - -## How do I add a custom .d.ts file to the OpenHarmony SDK? - -Applicable to: OpenHarmony SDK 3.1.7.7, FA model of API version 8 - -Name the .d.ts file **@ohos.xxxx.d.ts**, save it to the SDK path, and restart Dev Eco Studio. - -A code notification is displayed when the file is imported. - -## How do I switch to the full SDK? - -Applicable to: OpenHarmony SDK 3.2.7.5 - -Follow the instructions in [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md). diff --git a/en/application-dev/faqs/faqs-language.md b/en/application-dev/faqs/faqs-language.md deleted file mode 100644 index 686283d7f8b41fa7abc4f4c78f74eed1240014d8..0000000000000000000000000000000000000000 --- a/en/application-dev/faqs/faqs-language.md +++ /dev/null @@ -1,288 +0,0 @@ -# Programming Languages - -## What are the restrictions on using generator functions in TypeScript? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -Below are the restrictions on using generator functions in TypeScript: - -- Expressions can be used only in character strings (in the ${expression} format), **if** conditions, **ForEach** parameters, and component parameters. - -- No expressions should cause any application state variables (including **@State**, **@Link**, and **@Prop**) to change. Otherwise, undefined and potentially unstable framework behavior may occur. - -- The generator function cannot contain local variables. - -None of the above restrictions apply to anonymous function implementations of event handlers (such as **onClick**). - -Negative example: - -``` -build() { - let a: number = 1 // invalid: variable declaration not allowed - Column() { - Text('Hello ${this.myName.toUpperCase()}') // ok. - ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array variable in place - } - buildSpecial() // invalid: no function calls - Text(this.calcTextValue()) // this function call is ok. -} -``` - -## How do I dynamically replace the %s placeholder in a resource file? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -In an application, you can replace the %s placeholder by using the second parameter in **$r('app.string.xx')**, which is used to reference application resources. - -Example: - -``` -build() { - //do something - // The second parameter indicates the referenced string resource, which can be used to replace the %s placeholder. - Text($r('app.string.entry_desc','aaa')) - .fontSize(100) - .fontColor(Color.Black) - //do something -} -``` - -## How do I read an XML file in Resource and convert data in it to the string type? - -Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 - -1. Obtain Uint8Array data by calling the **RawFile** API of **resourceManager**. - -2. Convert the Uint8Array data to strings by calling the **String.fromCharCode** API. - -Reference: [Resource Manager](../reference/apis/js-apis-resource-manager.md) - -Example: - - -``` -resourceManager.getRawFile(path, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let rawFile = value; - let xml = String.fromCharCode.apply(null, rawFile) - } -}); -``` - -## How do I convert a Resource object to the string type? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Use the **resourceManager.getString()** API of the **@ohos.resourceManager** module. - -Reference: [Resource Manager](../reference/apis/js-apis-resource-manager.md#getstring) - -## What should I do if the global static variables of a class do not work? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Objects imported to abilities and pages are packaged into two different closures, that is, two global objects. In this case, a static variable referenced by the abilities is not the same object as that referenced by the pages. Therefore, global variables cannot be defined by defining static variables in the class. You are advised to use AppStorage to manage global variables. - -## How do I obtain resources in the stage model? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -The stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This method, however, is not applicable to the FA model. - -Example: - - -``` -const context = getContext(this) as any -context - .resourceManager - .getString($r('app.string.entry_desc').id) - .then(value => { - this.message = value.toString() -}) -``` - -## How do I obtain data through an API before page loading? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -In the **aboutToAppear** function, use an asynchronous API to obtain page data and **@State** to decorate related variables. After the data is obtained, the page is automatically refreshed based on the variables. - - -``` -@Entry -@Component -struct Test6Page { - // After the data is obtained, the page is automatically refreshed. - @State message: string = 'loading.....' - aboutToAppear(){ - // Simulate an asynchronous API to obtain data. - setTimeout(()=>{ - this.message = 'new msg' - },3000) - } - build() { - Row() { - Column() { - Text(this.message) - .fontSize(50) - .fontWeight(FontWeight.Bold) - } - .width('100%') - } - .height('100%') - } -} -``` - -## Do the worker thread and the main thread run in the same global context? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -No. The worker thread and the main thread are not in the same global context. They interact with each other in data communication mode. - -## Which API is used for URL encoding in OpenHarmony? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -The global function **encodeURI** is used for URI encoding, and **decodeURI** is used for URI decoding. For example, a space character is encoded as %20. - -## Does OpenHarmony provide any API for parsing XML files? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -Yes. The **convert** API of the **convertxml** module can be used to convert XML text into JavaScript objects. - -Reference: [@ohos.convertxml](../reference/apis/js-apis-convertxml.md) - -## How do I configure application icons to be used across devices? - -Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 - -Use resource qualifiers to configure application icons to be used across devices. - -## Can placeholders be configured in the string.json file of the stage model? - -Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 - -The **string.json** file does not support placeholders. As an alternative, you can define variables on the target page and combine these variables and **Resource** objects. - -## Is there any difference between the OpenHarmony API systemTime.getCurrentTime() and the JS API new Date().getTime() API? - -Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 - -Similar to **new Date().getTime()**, **systemTime.getCurrentTime(false)** returns the number of milliseconds that have elapsed since the Unix epoch. **systemTime.getCurrentTime(true)** returns the number of nanoseconds that have elapsed since the Unix epoch. The system time is used in both APIs. - -## How do I define @BuilderParam decorated attributes based on the value assigned to them? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -If no parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, **content: this.specificParam**), define the type of the attribute as a function without a return value (for example, **@BuilderParam content: () => voi**). If any parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, **callContent: this.specificParam1("111")**), define the type of the attribute as **any** (for example, **@BuilderParam callContent: any**). - -## How does ArkTS convert a string into a byte array? - -Applicable to: all versions - -Refer to the following code: - - -``` -function stringToByte(str) { - var bytes = new Array(); - var len,c; - len = str.length; - for(var i = 0;i= 0x010000 && c<= 0x10FFFF) { - bytes.push(((c>>18) & 0x07) | 0xf0); - bytes.push(((c>>12) & 0x3F) | 0x80); - bytes.push(((c>>6) & 0x3f) | 0x80); - bytes.push((c & 0x3F) | 0x80); - } else if(c >= 0x000800 && c<= 0x00FFF){ - bytes.push(((c>>12) & 0x07) | 0xf0); - bytes.push(((c>>6) & 0x3F) | 0x80); - bytes.push((c & 0x3F) | 0x80); - } else if(c >= 0x000800 && c<= 0x0007FF) { - bytes.push(((c>>6) & 0x3F) | 0x80); - bytes.push((c & 0x3F) | 0x80); - } else { - bytes.push(c & 0xFF) - } - } - return bytes; -} -``` - -## What do I do if the "Too many wokers, the number of worker exceeds the maximum" message is displayed during worker creation? - -Applicable to: OpenHarmony SDK 3.2.6.5 - -An application allows for a maximum of seven workers. Therefore, use the **termiate** API to release workers when they are not needed. - -Reference: [@ohos.worker](../reference/apis/js-apis-worker.md#terminate) - -## What is the recommended multithreading solution on OpenHarmony? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -OpenHarmony recommends that worker threads be used for multithreading. - -Reference: [@ohos.worker](../reference/apis/js-apis-worker.md) - -## What is the difference between a @Builder decorated method and other methods? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -If the **@Builder** decorated method uses a custom component, this component is re-created each time the method is called. - -## Why is the callback registered through @Watch not triggered when the object attributes of an array change? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -As with **@State**, the callback registered through **@Watch** can be used to listen for only one layer of data changes. If the object attributes of the array changes at the inner layer, the callback will not be triggered. - -## How do I listen for in-depth changes of @State decorated variables? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -To listen for in-depth changes of **@State** decorated variables, you can use **@Observed** and **@ObjectLink** decorators. - -## How do I implement character string encoding and decoding? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -You can use **TextEncoder** and **TextDecoder** provided by the **util** module. - -Reference: [TextEncoder](../reference/apis/js-apis-util.md#textencoder) and [TextDecoder](../reference/apis/js-apis-util.md#textdecoder) - -## How do i import and export namespaces? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -- Exporting namespaces - - ``` - namespace Util{ - export function getTime(){ - return Date.now() - } - } - export default Util - ``` - -- Importing namespaces - - ``` - import Util from './util' - Util.getTime() - ``` - -## Can relational database operations be performed in the worker thread? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -No. Relational database operations cannot be performed in the worker thread. - - \ No newline at end of file diff --git a/en/application-dev/faqs/faqs-media.md b/en/application-dev/faqs/faqs-media.md deleted file mode 100644 index 0e88cf4e94aafa20e47a6ebd8fe3688d26a5e52a..0000000000000000000000000000000000000000 --- a/en/application-dev/faqs/faqs-media.md +++ /dev/null @@ -1,132 +0,0 @@ -# Media Development - -## How do I set a front camera? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -1. Set the camera position to **camera.CameraPosition.CAMERA_POSITION_FRONT**. - -2. Create a **CameraInput** instance based on the camera position and type. - -Reference: [Camera Management](../reference/apis/js-apis-camera.md) - -Example: - -``` -// The rear camera is set by default. You can use **isFrontCamera** to switch to the rear camera. -let cameraId -let cameraInput -for(let cameraIndex = 0; cameraIndex < this.cameraArray.length; cameraIndex++) { - let faceType = this.cameraArray[cameraIndex].cameraPosition - switch(faceType) { - case camera.CameraPosition.CAMERA_POSITION_FRONT: // Front camera - if(this.isFrontCamera){ - cameraId = this.cameraArray[cameraIndex].cameraId - } - break - case camera.CameraPosition.CAMERA_POSITION_BACK: // Rear camera - if(!this.isFrontCamera){ - cameraId = this.cameraArray[cameraIndex].cameraId - } - break - case camera.CameraPosition.CAMERA_POSITION_UNSPECIFIED: - default: - break - } -} -cameraInput = await this.cameraManager.createCameraInput(cameraId) -``` - -## How do I crop an image? - -Applicable to: OpenHarmony SDK 3.2.5.6, stage model of API version 9 - -1. Create an **ImageSource** instance based on the input URI. - - ``` - let path = this.context.getApplicationContext().fileDirs + "test.jpg"; - const imageSourceApi = image.createImageSource(path); - ``` - -2. Set decoding parameters and decode the image to obtain a **PixelMap** object. Image processing is supported during decoding. - - Set **desiredSize** to specify the target size after scaling. If the values are all set to **0**, scaling will not be performed. - - Set **desiredRegion** to specify the target rectangular area after cropping. If the values are all set to **0**, cropping will not be performed. - - Set **rotateDegrees** to specify the rotation angle. The image will be rotated clockwise at the center. - - ``` - const decodingOptions = { - desiredSize: { - height:0, - width:0 - }, - // Crop a rectangular area. - desiredRegion: { - size: { - height:100, - width:100 - }, - x:0, - y:0 - }, - // Rotate the image by 90 degrees. - rotate:90 - } - imageSourceApi.createPixelMap(decodingOptions).then(pixelMap => { - this.handlePixelMap(pixelMap) - }) - ``` - -3. Process the obtained **PixelMap** object. For example, render and display the image. - -## How do I apply for the media read/write permission on a device? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -1. Configure the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA** in the **module.json5** file. - Example: - - - ``` - { - "module" : { - "requestPermissions":[ - { - "name" : "ohos.permission.READ_MEDIA", - "reason": "$string:reason" - }, - { - "name" : "ohos.permission.WRITE_MEDIA", - "reason": "$string:reason" - } - ] - } - } - ``` - -2. Call **requestPermissionsFromUser** to request the permissions from end users in the form of a dialog box. This operation is required because the grant mode of both permissions is **user_grant**. - - ``` - import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts'; - - let permissions: Array = ['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] - let atManager = abilityAccessCtrl.createAtManager(); - // context is the ability-level context of the initiator UIAbility. - atManager.requestPermissionsFromUser(context, permissions).then((data) => { - console.log("Succeed to request permission from user with data: " + JSON.stringify(data)) - }).catch((error) => { - console.log("Failed to request permission from user with error: " + JSON.stringify(error)) - }) - ``` - -## Why can't I play MP4 videos? - -Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9 - -Currently, the system does not support the playback of MP4 videos in H.265 format. - - -## Why can't I play a new video or even encounters a crash after creating more than 10 videos? - -Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9 - -A maximum of 13 media player instances can be created. diff --git a/en/application-dev/faqs/faqs-multimedia.md b/en/application-dev/faqs/faqs-multimedia.md new file mode 100644 index 0000000000000000000000000000000000000000..080860a9a5ca913d1d40d9de049f9220a66118da --- /dev/null +++ b/en/application-dev/faqs/faqs-multimedia.md @@ -0,0 +1,135 @@ +# Multimedia Development + +## How do I obtain the frame data of a camera when using the XComponent to display the preview output stream of the camera? + +Applicable to: OpenHarmony 3.2 (API version 9, stage model) + +**Symptom** + +Currently, the API does not support real-time preview of the camera frame data. To obtain the frame data, you must bind an action, for example, photographing. + +**Solution** + +Create a dual-channel preview to obtain the frame data. + +1. Use the XComponent to create a preview stream. + + ``` + // Obtain a PreviewOutput instance. + const surfaceId = globalThis.mxXComponentController.getXComponentSurfaceld(); + this.mPreviewOutput = await Camera.createPreviewOutput(surfaceld) ; + ``` + +2. Use imageReceiver to listen for image information. + + ``` + // Add dual-channel preview. + const fullWidth = this.mFullScreenSize.width; + const fullHeight = this.mFullScreenSize.height; + const imageReceiver = await image.createImageReceiver(fullwidth, fullHeight, + formatImage, capacityImage) ; + const photoSurfaceId = await imageReceiver.getReceivingSurfaceld(); + this.mPreviewOutputDouble = await Camera.createPreviewOutput ( photoSurfaceld) + ``` + + +## How do I obtain the preview image of the front camera? + +Applicable to: OpenHarmony 3.2 (API version 9, stage model) + +**Solution** + +1. Use the **@ohos.multimedia.camera** module to obtain the physical camera information. + + ``` + let cameraManager = await camera.getCameraManager(context); + let camerasInfo = await cameraManager.getSupportedCameras(); + let cameraDevice = this.camerasInfo[0]; + ``` + +2. Create and start the input stream channel of the physical camera. + + ``` + let cameraInput = await cameraManager.createCameraInput(cameraDevice); + await this.cameraInput.open(); + ``` + +3. Obtain the output formats supported by the camera, and create a preview output channel based on the surface ID provided by the XComponent. + + ``` + let outputCapability = await this.cameraManager.getSupportedOutputCapability(cameraDevice); + let previewProfile = this.outputCapability.previewProfiles[0]; + let previewOutput = await cameraManager.createPreviewOutput(previewProfile, previewId); + ``` + +4. Create a camera session, add the camera input stream and preview output stream to the session, and start the session. The preview image is displayed on the XComponent. + + ``` + let captureSession = await cameraManager.createCaptureSession(); + await captureSession.beginConfig(); + await captureSession.addInput(cameraInput); + await captureSession.addOutput(previewOutput); + await this.captureSession.commitConfig() + await this.captureSession.start(); + ``` + + +## How do I set the camera focal length? + +Applicable to: OpenHarmony 3.2 (API version 9, stage model) + +**Solution** + +1. Check whether the camera is a front camera. A front camera does not support focal length setting. +2. Use **captureSession.getZoomRatioRange\(\)** to obtain the focal length range supported by the device. +3. Check whether the target focal length is within the range obtained. If yes, call **captureSession.setZoomRatio\(\)** to set the focal length. + +## How do I play music in the background? + +Applicable to: OpenHarmony 3.2 (API version 9, stage model) + +**Symptom** + +Music cannot be played in the background. + +**Solution** + +**AVSession** controls media playback. When a third-party application switches to the background or encounters a screen lock event, media playback is forcibly paused and the application is unaware of the pause. To enable the application to continue the playback in the background, request a continuous task and access the AVSession capability, which allows Control Panel to control the playback behavior of third-party applications. + +**Reference** + +[Continuous Task Development](../task-management/continuous-task-dev-guide.md) + +[AVSession Development](../media/using-avsession-developer.md) + + +## What should I do when multiple video components cannot be used for playback? + +Applicable to: OpenHarmony 3.2 (API version 9, stage model) + +**Symptom** + +A large number of video components are created. They cannot play media normally or even crash. + +**Solution** + +A maximum of 13 media player instances can be created. + + +## How do I invoke the image library directly? + +Applicable to: OpenHarmony 3.2 (API version 9, stage model) + +**Solution** + +``` +let want = { + bundleName: 'com.ohos.photos', + abilityName: 'com.ohos.photos.MainAbility', + parameters: { + uri: 'detail' + } +}; +let context = getContext(this) as common.UIAbilityContext; +context.startAbility(want); +``` diff --git a/en/application-dev/faqs/faqs-native.md b/en/application-dev/faqs/faqs-native.md deleted file mode 100644 index ef5700bb0ec1e3c903fd758d644779856f0ce681..0000000000000000000000000000000000000000 --- a/en/application-dev/faqs/faqs-native.md +++ /dev/null @@ -1,79 +0,0 @@ -# Native API Usage - -## Is there a native API that provides functions similar to Canvas? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -Yes. The native API **Drawing** provides similar functions. It can be used for 2D drawing. - -## When a native HAP is running, the error message "Obj is not a valid object" is displayed for the imported namespace. What should I do? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -Check the **abiFilters** parameter value in the **build-profile.json5** file in the root directory of the module (not the root directory of the project). If the device is 32-bit, the value must be **armeabi-v7a**. If the device is 64-bit, the value must be **arm64-v8a**. - -## What should I do when the error message "install parse profile prop check error" is displayed during the running of a native HAP? - -Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 - -Check the **abiFilters** parameter value in the **build-profile.json5** file in the root directory of the module (not the root directory of the project). If the device is 32-bit, the value must be **armeabi-v7a**. If the device is 64-bit, the value must be **arm64-v8a**. - -## What should I do when the error message "undefined symbol: OH_LOG_Print" is displayed during log printing by **OH_LOG_Print**? - -Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9 - -Modify the **CMakeLists.txt** file by adding **libhilog_ndk.z.so** to the end of **target_link_libraries**. - -## How do I obtain the value of version in the package.json file of a module? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -1. In the script file **hvigorfile.js** of Hvigor, use **subModule.getPackageJsonPath** to obtain the location of the **package.json** file in the module. - -2. Use Node.js to read the **version** field in the **package.json** file and write the value to the **buildOption.cppFlags** field in the **build-profile.json5** file. - -Example - - -``` -// Module-level hvigorfile.js -const subModule = require('@ohos/hvigor')(__filename) - -const fs = require("fs-extra") -const path = require("path") - -const packageJsonPath = subModule.getPackageJsonPath() -const buildProfilePath = path.resolve(packageJsonPath, '../build-profile.json5') -const packageJsonData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) -let buildProfileData = fs.readFileSync(buildProfilePath, 'utf8') -buildProfileData = buildProfileData.replace(/\"cppFlags\"\:(.*)\,/, `"cppFlags": "-D NWEBEX_VERSION=${packageJsonData.version}",`) -fs.writeFileSync(buildProfilePath, buildProfileData, 'utf8') - -const ohosPlugin = require('@ohos/hvigor-ohos-plugin').hapTasks(subModule) // The plug-in executes the C++ build task and reads the build-profile.json5 file. - -module.exports = { - ohos: ohosPlugin -} -``` - - -``` -// Read the hello.cpp file. -#define _NWEBEX_VERSION(v) #v -#define _NWEBEX_VER2STR(v) _NWEBEX_VERSION(v) - -static napi_value Add(napi_env env, napi_callback_info info) -{ - - napi_value fixed_version_value = nullptr; - napi_create_string_utf8(env, _NWEBEX_VER2STR(NWEBEX_VERSION), NAPI_AUTO_LENGTH, &fixed_version_value); - - return fixed_version_value; -} -``` - -## How do I traverse files in rawfile? - -Applicable to: OpenHarmony SDK 3.2 or later, stage model of API version 9 - -Use the native API **OH_ResourceManager_OpenRawDir()** to obtain the root directory of **rawfile** and traverse the root directory. diff --git a/en/application-dev/faqs/faqs-sensor.md b/en/application-dev/faqs/faqs-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..3932b223fb5c6af755c9eae019851e37edfa6ef4 --- /dev/null +++ b/en/application-dev/faqs/faqs-sensor.md @@ -0,0 +1,7 @@ +# Pan-Sensor Development + +## Are the APIs used for obtaining PPG and ECG sensor data open to individual developers? + +Applicable to: OpenHarmony 3.1 Beta 5 (API version 9) + +Data collected by the PPG and ECG sensors of wearable devices is personal privacy data. Therefore, relative APIs are not open to individual developers. diff --git a/en/application-dev/faqs/faqs-third-fourth-party-library.md b/en/application-dev/faqs/faqs-third-fourth-party-library.md new file mode 100644 index 0000000000000000000000000000000000000000..045a3f5efe77b0ad16b64960bbf015b62b07d46f --- /dev/null +++ b/en/application-dev/faqs/faqs-third-fourth-party-library.md @@ -0,0 +1,69 @@ +# Usage of Third- and Fourth-Party Libraries + +## How do I obtain available third-party libraries? + +Applicable to: OpenHarmony 3.1 Beta 5 (API version 9) + +The three-party and four-party libraries that can be obtained through ohpm are summarized in the [OpenHarmony-TPC/tpc_resource repository](https://gitee.com/openharmony-tpc/tpc_resource). You can access this repository, and find the desired component based on the directory index. + +## Which third-party libraries are related to network requests? + +Applicable to: OpenHarmony 3.1 Beta 5 (API version 9) + +The following third-party libraries are related to network requests: [Axios](https://gitee.com/openharmony-sig/axios), httpclient, and okdownload. For details, see the [OpenHarmony-TPC/tpc_resource repository](https://gitee.com/openharmony-tpc/tpc_resource). + +## How do I use ohpm to import third- and fourth-party libraries? + +Applicable to: OpenHarmony 3.1 Beta 5 (API version 9) + +**Solution** + +- Method 1: + 1. Open the **Terminal** window and run the following command to go to the **entry** directory: + + ``` + cd entry + ``` + + 2. Run the following command to install a third-party library, for example, **dayjs**: + + ``` + ohpm install dayjs + ``` + + 3. Add the following statement in the .js file to import the third-party library: + + ``` + import dayjs from 'dayjs'; + ``` + + +- Method 2: + 1. Enter the **entry** directory of the project and open the **oh-package.json5** file. + 2. Write the third-party library to be installed (for example, **dayjs**) in the **oh-package.json5** file. + + ``` + { + "dependencies": { + "dayjs": "^1.10.4", + } + } + ``` + + 3. Open the **Terminal** window and run the following command to go to the **entry** directory: + + ``` + cd entry + ``` + + 4. Run the following command to install the third-party library: + + ``` + ohpm install + ``` + + 5. Add the following statement in the .js file to import the third-party library: + + ``` + import dayjs from 'dayjs'; + ``` diff --git a/en/application-dev/faqs/faqs-third-party-library.md b/en/application-dev/faqs/faqs-third-party-library.md deleted file mode 100644 index 898055cd200805d8df549b33bb2c5f3b4b05bca6..0000000000000000000000000000000000000000 --- a/en/application-dev/faqs/faqs-third-party-library.md +++ /dev/null @@ -1,74 +0,0 @@ -# Usage of Third- and Fourth-Party Libraries - -## What does the following error message mean: "Stage model module... does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed." - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -The third- and fourth-party libraries are not yet compatible with the stage model of API version 9 and cannot be used. - -## Can I transfer project-level dependencies? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -For example, if project A depends on project B and project B depends on project C, can project A directly use the APIs provided by project C? - -No. Project A cannot directly use the APIs provided by project C. The project packing tool NPM does not support dependency transfer. To use the APIs provided by project C, you can add the dependency of project C to project A. - -## How do I obtain available third-party libraries? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -For details, see [Third-Party Components That Can Be Directly Used on OpenHarmony](https://gitee.com/openharmony-sig/third_party_app_libs). - -## Which third-party libraries are related to network requests? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -The [Axios](https://gitee.com/openharmony-sig/axios) library is related to network requests. - -## How do I use NPM to import third- and fourth-party libraries? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 -- Method 1: - 1. Open the **Terminal** window and run the following command to go to the **entry** directory: - - ``` - cd entry - ``` - 2. Run the following command to install a third-party package, for example, **dayjs**: - - ``` - npm install dayjs --save - ``` - 3. Add the following statement in the .js file to import the package: - - ``` - import dayjs from 'dayjs'; - ``` - -- Method 2: - 1. Enter the **entry** directory of the project and open the **package.json** file. - 2. Write the third-party NPM package to be installed (for example, **dayjs**) in the **package.json** file. - - ``` - { - "dependencies": { - "dayjs": "^1.10.4", - } - } - ``` - 3. Open the **Terminal** window and run the following command to go to the **entry** directory: - - ``` - cd entry - ``` - 4. Run the following command to install NPM: - - ``` - npm install - ``` - 5. Add the following statement in the .js file to import the package: - - ``` - import dayjs from 'dayjs'; - ``` diff --git a/en/application-dev/faqs/faqs-ui-ets.md b/en/application-dev/faqs/faqs-ui-ets.md deleted file mode 100644 index 8564d2f0969a2cf6eac9bb2d9ac521e62045d162..0000000000000000000000000000000000000000 --- a/en/application-dev/faqs/faqs-ui-ets.md +++ /dev/null @@ -1,656 +0,0 @@ -# ArkUI (ArkTS) Development - -## How do I use router to implement page redirection in the stage model? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -1. To implement page redirection through **router**, add all redirected-to pages to the pages list in the **main_pages.json** file. - -2. Page routing APIs in **router** can be invoked only after page rendering is complete. Do not call these APIs in **onInit** or **onReady** when the page is still in the rendering phase. - -Reference: [Page Routing](../reference/apis/js-apis-router.md) - -## Will a page pushed into the stack through router.push be reclaimed? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -After being pushed to the stack through **router.push**, a page can be reclaimed only when it is popped from the stack through **router.back**. - -## How do I position a container component to the bottom of the screen? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Create a **** component, and set the target container at the bottom of the **** component. - -Example: - -``` -build() { - Stack({alignContent : Alignment.Bottom}) { - // The container is at the bottom. - Stack() { - Column() - .width('100%') - .height('100%') - .backgroundColor(Color.Yellow) - } - .width('100%') - .height('10%') - } - .width('100%') - .height('100%') - .backgroundColor('rgba(255,255,255, 0)') -} -``` - -## Can CustomDialog be used in TypeScript files? - -Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 - -No. **CustomDialog** can be used only on ArkTS pages. - -Reference: [Custom Dialog Box](../reference/arkui-ts/ts-methods-custom-dialog-box.md) - -## How do I transfer variables in CustomDialog to variables on pages? - -Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 - -Use a custom callback so that when the confirm button in the custom dialog box is clicked, the value of **data** is transferred from the dialog box to the current page. - -Example: - - -``` -// Dialog box component -@CustomDialog -struct MyDialog { - controller: CustomDialogController - title: string - confirm: (data: string) => void - data: string = '' - - build() { - Row() { - Column({ space: 10 }) { - Text(this.title) - .fontSize(30) - .fontColor(Color.Blue) - TextInput({ placeholder: "Enter content", text: this.data }) - .onChange((data) => { - this.data = data // Obtain the data in the text box. - }) - Button('confirm') - .onClick(() => { - this.confirm(this.data) // Transfer the data in the text box to the main page through the callback. - this.controller.close() - }).backgroundColor(0xffffff).fontColor(Color.Red) - }.width("50%") - }.height("50%") - } -} - -// Main page -@Entry -@Component -struct DialogTest { - @State dialogTitle: string = '' - @State dialogData: string = '' - dialogController: CustomDialogController = new CustomDialogController({ - builder: MyDialog({ - title: this.dialogTitle, // Bind data. - data: this.dialogData, - confirm: this.confirm.bind(this) // Bind the custom callback. Change the direction of this here. - }) - }) - - confirm(data: string) { - this.dialogData = data - console.info(`recv dialog data: ${data}`) // Obtain the information entered in the dialog box. - } - - build() { - Row() { - Column({ space: 10 }) { - Button ('Open Dialog Box') - .onClick(() => { - this.dialogTitle ='Dialog Box' - this.dialogController.open() - }) - Text(`Accept pop-up window data:`) - .fontSize(20) - TextInput ({ placeholder: "Input", text: this.dialogData }) - .width("50%") - .onChange((data) => { - this.dialogData = data //Obtain the data in the text box. - }) - }.width("100%") - }.height("100%") - } -} -``` - -## What should I do if the \ component cannot be dragged to the bottom after it has a \ component added? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -The **\** component is a scrollable container. By default, it takes up the entire screen height. When any component with a fixed height takes up part of the screen height, you need to explicitly specify **layoutWeight(1)** for the parent container of the **\** component to take up the remaining height instead of the entire screen height. - -## How do I center child components in a grid container? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -By default, child components in a **\** are horizontally aligned to the left. To center them, perform the following steps: - -Nest a **\** component and set it to **justifyContent(FlexAlign.Center)**. For details, see [Grid Layout](../reference/arkui-ts/ts-container-gridcontainer.md). - -Example: - -``` -GridContainer({ sizeType: SizeType.SM, columns: 12 }) { - Row() { - Text('1') - .useSizeType({ - sm: { span: 4, offset: 0 }, - }) - .backgroundColor(0x46F2B4) - }.justifyContent(FlexAlign.Center) // Center child components. -} -``` - -## How do I obtain the height of the status bar and navigation bar? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -Before the window content is loaded, enable listening for the **systemAvoidAreaChange** event. - -Example: - -```ts -import Window from '@ohos.window'; -import UIAbility from '@ohos.app.ability.UIAbility'; - -/** - * Set the immersive window and obtain the height of the status bar and navigation bar. - * @param mainWindow Indicates the main window. - */ -async function enterImmersion(mainWindow: window.Window) { - mainWindow.on("systemAvoidAreaChange", (area: window.AvoidArea) => { - AppStorage.SetOrCreate("topHeight", area.topRect.height); - AppStorage.SetOrCreate("bottomHeight", area.bottomRect.height); - }) - await mainWindow.setFullScreen(true) - await mainWindow.setSystemBarEnable(["status", "navigation"]) - await mainWindow.sArkTSystemBarProperties({ - navigationBarColor: "#00000000", - statusBarColor: "#00000000", - navigationBarContentColor: "#FF0000", - statusBarContentColor: "#FF0000" - }) -} -export default class EntryAbility extends UIAbility { - // do something - async onWindowStageCreate(windowStage: window.WindowStage) { - let mainWindow = await windowStage.getMainWindow() - await enterImmersion(mainWindow) - windowStage.loadContent('pages/index') - } - // do something -} -``` - -## How do I fix misidentification of the pan gesture where container nesting is involved? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -Set the **distance** attribute to **1** for the gesture. By default, this attribute is set to **5**. - -## How do I obtain the height of a component? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -You can obtain the changes in the width and height of a component through **onAreaChange**. - -Example: - - -```ts -Column() { - Text(this.value) - .backgroundColor(Color.Green).margin(30).fontSize(20) - .onClick(() => { - this.value = this.value + 'Text' - }) - .onAreaChange((oldValue: Area, newValue: Area) => { - console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`) - this.size = JSON.stringify(newValue) - }) -``` - -## How do I obtain the offset of the \ component? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Bind the **\** component to a **Scoller** object and obtain the offset through **currentOffset**. - -Example: - - -```ts -Column() { - List({ space: 20, initialIndex: 0,scroller: this.scroller}) { - ForEach(this.arr, (item) => { - ListItem() { - Text('' + item) - .width('100%').height(100).fontSize(16) - .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) - }.editable(true) - }, item => item) - } - .listDirection(Axis.Vertical) // Arrangement direction - .editMode(this.editFlag) - .onScroll((xOffset: number, yOffset: number) => { - console.info("yOffset======="+this.scroller.currentOffset().yOffset) - }) -}.width('100%') -``` - -## How do I obtain the value of param for the target page of redirection implemented using router? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - - -```ts -// In versions earlier than 3.1.5.5, obtain the value through router.getParams().key. -private value: string = router.getParams().value; -// In 3.1.6.5 and later versions, obtain the value through router.getParams()['key']. -private value: string = router.getParams()['value']; -``` - -## Does the \ component support redirection to a local page? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -No. This feature is not supported. - -## How do I disable the transition effect for pages switched using router or navigator? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -1. Define the **pageTransition** method for the current and target pages, by following instructions in [Example](../reference/arkui-ts/ts-page-transition-animation.md#example). - -2. Set the **duration** parameter of both **PageTransitionEnter** and **PageTransitionExit** to **0**. - -## How do I select the pixel unit during UI development? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -It depends. - -The vp unit ensures consistency of visual effects across resolutions. For example, it ensures that an icon is displayed consistently under different resolutions. - -The lpx unit produces a visual effect where items are zoomed in or out proportionally. - -If you are concerned about visual effect consistency of items, for example, buttons, texts, and lists, use the vp unit. If your focus is on the layout, for example, 1/2 grid, the lpx is a better choice. - -## What color formats are used in ArkTS? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -The color can be represented in two formats, for example, 0x7F000000 or '\#7F000000'. The first two digits indicate opacity, and the last six digits indicate RGB. - - -```ts -fontColor(0x7F000000) -fontColor( '#7F000000' ) -``` - -## How do I listen for the return operation on a page? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -When a return operation is performed on a page, the system calls the **onBackPress()** callback of the **@Entry** decorated custom component. You can implement related service logic in the callback. - -Reference: [Custom Component Lifecycle Callbacks](../ui/ui-ts-custom-component-lifecycle-callbacks.md) - -## Can I customize the eye icon for the \ component in password mode? - -Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 - -No. The eye icon can be shown or hidden through **showPasswordIcon** when **type** of the **\** component is set to **InputType.Password**. It cannot be customized. - -Reference: [TextInput](../reference/arkui-ts/ts-basic-components-textinput.md) - -## Why can't images be loaded over HTTP? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -HTTP is insecure and HTTP sources will be filtered out by the trustlist. For security purposes, use HTTPS. - -## What should I do if the spacing set for the TextView layout does not fit the UI? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -By default, the **align** attribute of **TextView** is set to **Center**. To display the text from left to right, set the **align** attribute to **Start**. - -## Why do the constraintSize settings fail to take effect? - -Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 - -If **constraintSize** is set for a component and the width of its child component is set to a percentage, for example, **width('100%')**, **constraintSize** takes effect by multiplying the maximum width by the percentage. As a result, the child component may overflow, in which case it looks like the **constraintSize** settings fail to take effect. - -## How do I set the background color to transparent? - -Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 - -Set **backgroundColor** to **'\#00000000'**. - -## What should I do if the \ component cannot scroll to the bottom? - -Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 - -Unless otherwise specified, the height of the **\** component is equal to the window height. In this case, the component's bottom area will be blocked by components (if any) outside of it. To fix this issue, set the height of the **\** component or use the flex layout to limit this height. - -## How do I use the onSubmit event of the \ component? - -Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 - -The **onSubmit** event is triggered when the Enter key is pressed and accepts the current Enter key type as its input parameter. You can set the Enter key type for the **\** component through the **enterKeyType** attribute. The Enter key style of the soft keyboard requires the support of the input method. - -Reference: [TextInput](../reference/arkui-ts/ts-basic-components-textinput.md) - -## What is the maximum number of pages allowed during page routing? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -The maximum number of pages supported by the page stack is 32. When this limit is reached, the **router.push** API cannot be used for page redirection. - -## Does ArkUI allow components to be dynamically created in code? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -Yes. You can dynamically creaete components using [conditional rendering](../quick-start/arkts-rendering-control.md#conditional-rendering) and [loop rendering](../quick-start/arkts-rendering-control.md#loop-rendering). - -## What should I do if the PixelMap object carried in page routing cannot be obtained from the target page? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -Page routing supports only the common object type and common JSON data structure. To pass a **PixelMap** object to the target page, store it in the **localStorage**. - -## How do I use .caretPosition(0) to move the caret to the start of the text area when onEditChange is triggered for the \ component? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -The **onEditChange** event is triggered when the input box gains focus. Under this scenario, the caret position is related to the position where the gesture is when the event is triggered, and **caretPosition** cannot be used to change the caret position. Call **setTimeout** for asynchronous processing first. - -## Is there any method for selecting all items in the \ component? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -No. This feature is not supported yet. - -## Why can't I select a date when the type attribute of the input text box is set to date? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -Setting the **type** attribute of the input component to **date** means that the component accepts dates as input and the user will be notified of the valid input format. It does not display a date picker. To display a date picker, use the **\** component. - -## What should I do if the displayed input keyboard gets squeezed when using the **\** component? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -This issue may occur when the flex layout is used. To fix it, switch to the column layout. - -## How does the parent component pass values to a @Link decorated member variable in its child component? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -To pass a value from the parent component to the **@Link** decorated member variable in a child component, add **"$"** in front of the value. - -Example: - - -``` -@Component -struct FoodImageDisplay { - @Link imageSrc: Resource - - build() { - Stack({ alignContent: Alignment.BottomStart }) { - Image(this.imageSrc) - .objectFit(ImageFit.Contain) - Text('Tomato') - .fontSize(26) - .fontWeight(500) - .margin({ left: 26, bottom: 17.4 }) - } - .backgroundColor('#FFedf2f5') - .height(357) - } -} - -@Entry -@Component -struct FoodDetail { - - @State imageSrc: Resource = $r('app.media.Tomato') - - build() { - Column() { - FoodImageDisplay({imageSrc:$imageSrc}) - } - .alignItems(HorizontalAlign.Center) - } -} -``` - -## How do I share variables between Page abilities? - -Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 - -1. Use a lightweight database. - -2. Use persistent data management. - -3. Use the emitter event communication mechanism. - - -## How do I customize the control bar style of the \