### Example: Starting a Child Process with Arguments Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-app-ability-childprocessargs Provides an example of how to create and pass ChildProcessArgs when starting a child process from the main process. ```APIDOC // Main process: import { common, ChildProcessArgs, childProcessManager } from '@kit.AbilityKit'; import { fileIo } from '@kit.CoreFileKit'; @Entry @Component struct Index { build() { Row() { Column() { Text('Click') .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(() => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; let path = context.filesDir + "/test.txt"; let file = fileIo.openSync(path, fileIo.OpenMode.READ_ONLY | fileIo.OpenMode.CREATE); let args: ChildProcessArgs = { entryParams: "testParam", fds: { "key1": file.fd } }; childProcessManager.startArkChildProcess("entry/./ets/process/DemoProcess.ets", args); }); } .width('100%') } .height('100%') } } ``` -------------------------------- ### Example Usage Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-app-ability-childprocessoptions This example demonstrates how to use ChildProcessOptions when starting a child process using `childProcessManager.startArkChildProcess` in the main process, and the structure of a child process class. ```APIDOC ## Example: **Child Process Part:** ```typescript // Create a DemoProcess.ets child process class in entry/src/main/ets/process: // entry/src/main/ets/process/DemoProcess.ets import { ChildProcess, ChildProcessArgs } from '@kit.AbilityKit'; export default class DemoProcess extends ChildProcess { onStart(args?: ChildProcessArgs) { let entryParams = args?.entryParams; let fd = args?.fds?.key1; // Child process logic } } ``` **Main Process Part:** ```typescript // Use the childProcessManager.startArkChildProcess method to start the child process: // entry/src/main/ets/pages/Index.ets import { ChildProcessArgs, ChildProcessOptions, childProcessManager } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import DemoProcess from '../process/DemoProcess'; @Entry @Component struct Index { build() { Row() { Column() { Text('Click') .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(() => { try { DemoProcess.toString(); // Call any method of DemoProcess class here to prevent it from being optimized out by the build tool if not referenced. let options: ChildProcessOptions = { isolationMode: false, isolationUid: false }; let args: ChildProcessArgs = { entryParams: "testParam", }; childProcessManager.startArkChildProcess("entry/ets/process/DemoProcess.ets", args, options) .then((pid) => { console.info(`startChildProcess success, pid: ${pid}`); }) .catch((err: BusinessError) => { console.error(`startChildProcess business error, errorCode: ${err.code}, errorMsg:${err.message}`); }); } catch (err) { console.error(`startChildProcess error, errorCode: ${err.code}, errorMsg:${err.message}`); } }); } .width('100%') } .height('100%') } } ``` ``` -------------------------------- ### Basic Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-inner-ability-want Demonstrates how to use the Want object to start an ability in a UIAbility context. ```APIDOC ## Basic Usage (Called in a UIAbility object, where context in the example is the context object of UIAbility) Expand Automatic line feed Dark code theme Copy ``` 1. import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 2. import UIAbility from '@ohos.app.ability.UIAbility'; 3. import Want from '@ohos.app.ability.Want'; 4. import { BusinessError } from '@ohos.base'; 5. 6. let want: Want = { 7. deviceId: '', // deviceId is empty, indicating the current device 8. bundleName: 'com.example.myapplication', 9. abilityName: 'EntryAbility', 10. moduleName: 'entry' // moduleName is optional 11. }; 12. class MyAbility extends UIAbility{ 13. onCreate(want: Want, launchParam: AbilityConstant.LaunchParam){ 14. this.context.startAbility(want, (error: BusinessError) => { 15. // Explicitly launch Ability, uniquely identify an Ability through bundleName, abilityName, and moduleName 16. console.error(`error.code = ${error.code}`); 17. }); 18. } 19. } ``` ``` -------------------------------- ### Start Ability with Parameters Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-inner-ability-startabilityparameter Initiates the launch of an Ability using the startAbility method. This example demonstrates how to construct and pass a StartAbilityParameter object, including Want information and specific ability start settings. ```javascript import ability from '@ohos.ability.ability'; import featureAbility from '@ohos.ability.featureAbility'; import Want from '@ohos.app.ability.Want'; let want: Want = { bundleName: 'com.example.abilityStartSettingApp2', abilityName: 'com.example.abilityStartSettingApp.EntryAbility', }; let startAbilityParameter: ability.StartAbilityParameter = { want : want, abilityStartSettings : { abilityBounds : [100,200,300,400], windowMode : featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED, displayId : 1, } }; try { featureAbility.startAbility(startAbilityParameter, (error, data) => { if (error && error.code !== 0) { console.error(`startAbility fail, error: ${JSON.stringify(error)}`); } else { console.info(`startAbility success, data: ${JSON.stringify(data)}`); } }); } catch(error) { console.error(`startAbility error: ${JSON.stringify(error)}`); } ``` -------------------------------- ### Full Example: Music Playback with Pause and Resume Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/using-avplayer-for-playback This example demonstrates a complete music playback scenario. It includes starting playback, pausing after 3 seconds, and resuming after another 3 seconds. Ensure you have the necessary audio resources and UI elements set up. ```ArkTS AVPlayerArkTSAudio entry/src/main/ets/ └── pages └── Index.ets (播放界面) entry/src/main/resources/ ├── base │ ├── element │ │ ├── color.json │ │ ├── float.json │ │ └── string.json │ └── media │ ├── ic_video_play.svg (播放键图片资源) │ └── ic_video_pause.svg (暂停键图片资源) └── rawfile └── test_01.mp3 (音频资源) ``` -------------------------------- ### CompletionHandler Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-app-ability-completionhandler This example demonstrates how to implement and use the CompletionHandler to manage the results of starting an ability. It includes both success and failure callback functions. ```javascript import { UIAbility, Want, StartOptions, CompletionHandler, bundleManager } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onForeground() { let want: Want = { deviceId: '', bundleName: 'com.example.myapplication', abilityName: 'EntryAbility' }; let completionHandler: CompletionHandler = { onRequestSuccess: (elementName: bundleManager.ElementName, message: string): void => { console.info(`${elementName.bundleName}-${elementName.moduleName}-${elementName.abilityName} start succeeded: ${message}`); }, onRequestFailure: (elementName: bundleManager.ElementName, message: string): void => { console.error(`${elementName.bundleName}-${elementName.moduleName}-${elementName.abilityName} start failed: ${message}`); } }; let options: StartOptions = { completionHandler: completionHandler }; try { this.context.startAbility(want, options, (err: BusinessError) => { if (err.code) { // 处理业务逻辑错误 console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); return; } // 执行正常业务 console.info('startAbility succeed'); }); } catch (err) { // 处理入参错误异常 let code = (err as BusinessError).code; let message = (err as BusinessError).message; console.error(`startAbility failed, code is ${code}, message is ${message}`); } } } ``` -------------------------------- ### StartupConfig Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-app-appstartup-startupconfig Provides an example of how to define a StartupConfigEntry and configure startup parameters, including timeout and a listener for completion events. ```APIDOC ```typescript import { StartupConfig, StartupConfigEntry, StartupListener } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; export default class MyStartupConfigEntry extends StartupConfigEntry { onConfig(): StartupConfig { hilog.info(0x0000, 'testTag', `onConfig`); let onCompletedCallback = (error: BusinessError) => { hilog.info(0x0000, 'testTag', `onCompletedCallback`); if (error) { hilog.error(0x0000, 'testTag', 'onCompletedCallback: %{public}d, message: %{public}s', error.code, error.message); } else { hilog.info(0x0000, 'testTag', `onCompletedCallback: success.`); } }; let startupListener: StartupListener = { 'onCompleted': onCompletedCallback }; let config: StartupConfig = { 'timeoutMs': 10000, 'startupListener': startupListener }; return config; } } ``` ``` -------------------------------- ### Configuration Example (ext.json) Source: https://developer.huawei.com/consumer/cn/doc/atomic-ascf/develop-data-preloading Example of configuring data preloading within the `ext` property of the ext.json file. ```APIDOC ## Configuration Example (ext.json) ### Description Example of configuring data preloading within the `ext` property of the `ext.json` file. ### Code ```json { "ext": { "preload": [ { "fetchType": "pre", "url": "https://www.example.com", "method": "POST", "data": { "x": "" }, "headers": { "content-type": "application/json" }, "dataType": "json" } ] } } ``` ``` -------------------------------- ### Get Rows from LiteResultSet Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-data-relationalstore-literesultset Demonstrates how to retrieve data from a LiteResultSet using getRows. It shows two examples: one fetching data with only maxCount specified, and another specifying both maxCount and a starting position. Ensure to handle potential errors and check for undefined result sets. ```typescript 1. async function getRowsExample(store : relationalStore.RdbStore) { 2. // 以查到100条数据为例 3. try { 4. let resultSet: relationalStore.LiteResultSet | undefined; 5. resultSet = await store.querySqlWithoutRowCount('select * from EMPLOYEE where name = ?', ["Rose"]); 6. // 示例1:仅指定maxCount 7. if (resultSet != undefined) { 8. let rows: Array; 9. let maxCount: number = 50; 10. // 从结果集的当前行(默认首次获取数据时为当前结果集的第一行,后续为上次获取数据结束位置的下一行)开始获取数据 11. // getRows会自动移动结果集当前行到上次getRows获取结束位置的下一行,goToNextRow等接口移动 12. while ((rows = await resultSet.getRows(maxCount)).length != 0) { 13. console.info(JSON.stringify(rows[0])); 14. } 15. } 16. 17. // 示例2:指定maxCount和起始的position 18. if (resultSet != undefined) { 19. let rows: Array; 20. let maxCount: number = 50; 21. let position: number = 50; 22. while ((rows = await resultSet.getRows(maxCount, position)).length != 0) { 23. console.info(JSON.stringify(rows[0])); 24. position += rows.length; 25. } 26. } 27. } catch (err) { 28. console.error(`failed, code is ${err.code}, message is ${err.message}`); 29. } 30. } ``` -------------------------------- ### ohpm-repo Install Command Format Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-ohpm-repo-install This is the basic command format for installing the ohpm-repo service. Ensure you use the correct options based on your setup. ```bash ohpm-repo install [options] ``` -------------------------------- ### Full Radar Chart Example Source: https://developer.huawei.com/consumer/cn/doc/architecture-guides/audio-v1_2-ts_61-0000002443435425 A complete example demonstrating the setup and rendering of a radar chart component, including canvas initialization and drawing logic. ```typescript 1. @Entry 2. @Component 3. struct RadarChartPage { 4. private settings: RenderingContextSettings = new RenderingContextSettings(true); 5. private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); 6. _ // 背景_ 7. private path2Db: Path2D = new Path2D(); 8. _// 能力值展示_ 9. private ratePath2Db: Path2D = new Path2D(); 10. _// 计算正六边形的顶点坐标_ 11. private baseRadius: number = 150; 12. _ // 画布半径_ 13. private canvasRadius: number = 200; 14. private angleOffset: number = (Math.PI * 2) / 6; 15. _ // 圈数_ 16. private count: number = 5; 17. _// 各能力值_ 18. private rateArray: number[] = [0.5, 1.0, 0.15, 0.7, 0.4, 0.65]; 19. _// 各能力名称_ 20. private nameList: string[] = ['推进', '战绩', '生存', '团战', '发育', '输出']; 21. _// 各能力对应的坐标点_ 22. private positionList: PositionModel[] = []; 23. 24. build() { 25. Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 26. Canvas(this.context) 27. .width('400') 28. .height('400') 29. .backgroundColor(Color.White) 30. .onReady(() => { 31. _ // 绘制背景_ 32. for (let index = 0; index < 6; index++) { 33. this.baseRadius = 150 - (index * 30); 34. const firstX = this.baseRadius * Math.sin(0) + this.canvasRadius; 35. const firstY = this.baseRadius * Math.cos(0) + this.canvasRadius; 36. if (index === 0) { 37. let firstModel = new PositionModel(firstX, firstY); 38. this.positionList.push(firstModel); 39. } 40. this.path2Db.moveTo(firstX, firstY); 41. for (let i = 1; i < 6; i++) { 42. const angle = i * this.angleOffset; ``` -------------------------------- ### Example Usage Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ohos-multimedia-avvolumepanel Example demonstrating how to use the AVVolumePanel component with custom positioning. ```APIDOC ```typescript import { AVVolumePanel } from '@kit.AudioKit'; @Entry @Component struct Index { @State volume: number = 0; build() { Row() { Column() { AVVolumePanel({ volumeLevel: this.volume, volumeParameter: { position: { x: 100, y: 200 } } }) } }.width('50%').height('50%') } } ``` ``` -------------------------------- ### Get User Risk Level Request Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/account-api-getuserrisklevel This example demonstrates how to make a POST request to the Get User Risk Level API. Ensure you replace placeholders like , , , and with your actual values. The 'scene' parameter should be either 'registration' or 'marketing'. ```http POST /user/getuserrisklevel?clientID=&transactionID= HTTP/1.1 Host: account.cloud.huawei.com Content-Type: application/json;charset=utf-8 {"accessToken":"", "scene":""} ``` -------------------------------- ### Example Usage Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-data-udmfcomponents Demonstrates how to initialize and display a ContentFormCard with sample data. ```APIDOC ## 示例 __ 收起 自动换行 深色代码主题 复制 ``` 1. import { uniformDataStruct } from '@kit.ArkData' 2. 3. @Entry 4. @Component 5. struct Index { 6. @State contentForm: uniformDataStruct.ContentForm = { 7. uniformDataType: 'general.content-form', 8. title: '' 9. }; 10. @State startToShow: boolean = false; 11. 12. aboutToAppear(): void { 13. this.initData(); 14. } 15. 16. async initData() { 17. let context = this.getUIContext().getHostContext(); 18. if (!context) { 19. return; 20. } 21. try { 22. let appIcon = await context.resourceManager.getMediaContent($r('app.media.startIcon').id); 23. let thumbImage = await context.resourceManager.getMediaContent($r('app.media.foreground').id); 24. this.contentForm = { 25. uniformDataType: 'general.content-form', 26. title: "Content form title", 27. thumbData: appIcon, 28. description: "Content form description", 29. appIcon: thumbImage, 30. appName: "com.test.demo" 31. }; 32. } catch (err) { 33. console.error("Init data error"); 34. } 35. } 36. 37. build() { 38. Column() { 39. Button('show card') 40. .onClick(() => { 41. this.startToShow = true; 42. }) 43. if (this.startToShow) { 44. ContentFormCard({ 45. contentFormData: this.contentForm, 46. formType: FormType.TYPE_SMALL, 47. formWidth: 110, 48. formHeight: 50, 49. handleOnClick: () => { 50. console.info("Clicked card"); 51. } 52. }) 53. } 54. } 55. } 56. } ``` ``` -------------------------------- ### Get History Item by Index Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-webview-backforwardlist Retrieve a specific history item from the BackForwardList using its index. This example demonstrates how to get the current history item and its icon. ```typescript // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { image } from '@kit.ImageKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State icon: image.PixelMap | undefined = undefined; build() { Column() { Button('getBackForwardEntries') .onClick(() => { try { let list = this.controller.getBackForwardEntries(); let historyItem = list.getItemAtIndex(list.currentIndex); console.info("HistoryItem: " + JSON.stringify(historyItem)); this.icon = historyItem.icon; } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` -------------------------------- ### HTML for resource:// Protocol Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/arkts-apis-webview-webviewcontroller An example HTML file demonstrating how to handle URL fragments ('#') when loaded via the 'resource://rawfile/' protocol. It dynamically loads content based on the hash in the URL. ```HTML
``` -------------------------------- ### API Call Authorization Header Example Source: https://developer.huawei.com/consumer/cn/doc/atomic-guides/instant-service-merchant-authentication This example shows how to construct the GET request to a service-direct API, including the Authorization header with the JWT token and the appId. ```http 1. GET https://connect-api.cloud.huawei.com/api/ability-platform-connect/hag-developer/v1/venues?venueId=1773242566167455872 2. Authorization: Bearer eyJr*****OiIx---****.eyJh*****iJodHR--***.QRod*****4Gp---**** 3. Content-Type: application/json;charset=UTF-8 4. appId: 5981*****5845 ``` -------------------------------- ### Start ASCF Debugger Source: https://developer.huawei.com/consumer/cn/doc/atomic-ascf/debug-ascf-code Use this command to start Webview and V8 engine debugging for your ASCF project. The output will guide you to open the debugging tools in Chrome. ```bash ascf debugger start ``` -------------------------------- ### Prepay Request Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/payment-agent-prepay This example demonstrates the structure of a POST request to the preorder create app API. Ensure all required headers and body parameters are correctly populated. ```HTTP POST /api/v2/partner/aggr/preorder/create/app HTTP/1.1 Content-Type: application/json;charset=UTF-8 PayMercAuth: {"callerId":"10132120***","traceId":"202305151026422776499","time":1684117602555,"authId":"120291744647139***","headerSign":"u+H1Oe3fXV9mGCES89XA7tSjp8+TELYgG4bKyECwrVGwwExH********************g/lOG7eAFfwjEWJu5JyvY5KunSeE6DiKs=","bodySign":"yWDtXOBqDoItPgHmF57L6U5G7F/Lh********************IFeaszpiRT2aQDaqLGaxvta6J5UxIUmAp+wGdV/juGEvQ="} Accept: application/json { "spAppId": "5765880207853***", "mercOrderNo": "czl00120240705***", "spMercNo": "10132120***", "subMercNo": "10193600***", "tradeSummary": "xx商城-手机", "totalAmount": 2, "currency": "CNY", "callbackUrl": "https://www.xxxxxx.com/hw/pay/callback", "payload": "example-payload", "expireTime": "2023-03-28T17:50:12.000+0800" } ``` -------------------------------- ### HTTP GET Request Example for JWT Public Keys Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/account-rest-jwt-public-key Alternatively, use this GET request to retrieve the JWT public key information. Network stability is required. ```http GET /oauth2/v3/certs HTTP/1.1 Host: oauth-login.cloud.huawei.com ``` -------------------------------- ### CompletionHandler Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-app-ability-completionhandler This example demonstrates how to instantiate and use the CompletionHandler with startAbility to handle the results of launching another application. ```APIDOC ### CompletionHandler Usage __ ```typescript import { UIAbility, Want, StartOptions, CompletionHandler, bundleManager } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onForeground() { let want: Want = { deviceId: '', bundleName: 'com.example.myapplication', abilityName: 'EntryAbility' }; let completionHandler: CompletionHandler = { onRequestSuccess: (elementName: bundleManager.ElementName, message: string): void => { console.info(`${elementName.bundleName}-${elementName.moduleName}-${elementName.abilityName} start succeeded: ${message}`); }, onRequestFailure: (elementName: bundleManager.ElementName, message: string): void => { console.error(`${elementName.bundleName}-${elementName.moduleName}-${elementName.abilityName} start failed: ${message}`); } }; let options: StartOptions = { completionHandler: completionHandler }; try { this.context.startAbility(want, options, (err: BusinessError) => { if (err.code) { // Handle business logic errors console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); return; } // Execute normal business console.info('startAbility succeed'); }); } catch (err) { // Handle parameter error exceptions let code = (err as BusinessError).code; let message = (err as BusinessError).message; console.error(`startAbility failed, code is ${code}, message is ${message}`); } } } ``` ``` -------------------------------- ### GetBool Usage Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-getbool Example demonstrating how to use the GetBool function to retrieve a boolean attribute value. It first gets the RuntimeAttrs object and then calls GetBool with an index. ```cpp const RuntimeAttrs * runtime_attrs = kernel_context->GetAttrs(); const bool *attr0 = runtime_attrs->GetBool(0); ``` -------------------------------- ### Configuration Example (preload.json) Source: https://developer.huawei.com/consumer/cn/doc/atomic-ascf/develop-data-preloading Example of configuring data preloading in the preload.json file at the root of the meta-service. ```APIDOC ## Configuration Example (preload.json) ### Description Example of configuring data preloading in the `preload.json` file at the root of the meta-service. ### Code ```json [ { "fetchType": "pre", "url": "https://www.example.com", "method": "POST", "data": { "x": "" }, "headers": { "content-type": "application/json" }, "dataType": "json" } ] ``` ``` -------------------------------- ### CalendarPicker with Start and End Dates Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-components-calendarpicker This example shows how to set the start and end dates for the CalendarPicker component using the 'start' and 'end' properties. It configures the hintRadius, selected date, start date, and end date, and sets the alignment to END. The onChange callback logs the selected date. ```typescript // xxx.ets @Entry @Component struct CalendarPickerExample { private selectedDate: Date = new Date('2025-01-15'); private startDate: Date = new Date('2025-01-05'); private endDate: Date = new Date('2025-01-25'); build() { Column() { Column() { CalendarPicker({ hintRadius: 10, selected: this.selectedDate, start: this.startDate, end: this.endDate }) .edgeAlign(CalendarAlign.END) .textStyle({ color: "#ff182431", font: { size: 20, weight: FontWeight.Normal } }) .margin(10) .onChange((value) => { console.info(`CalendarPicker onChange: ${value.toString()}`); }) }.alignItems(HorizontalAlign.End).width("100%") }.width('100%').margin({ top: 350 }) } } ``` -------------------------------- ### Example Batch Publish Execution Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-ohpm-repo-batch-publish This example shows the command execution and the expected output when publishing packages in batch, including success messages and warnings related to data storage. ```bash PS D:\> ohpm-repo batch_publish D:\batch_download_1754735610304.zip --force ... [2025-08-09T19:12:01.497] [INFO] default - all 6 package(s) are successfully published [2025-08-09T19:12:01.497] [WARN] default - You are using "filedb" to store data. If you have already started a repository service, please run `ohpm-repo restart` to restart the service. ``` -------------------------------- ### Line XML Specification and Example Source: https://developer.huawei.com/consumer/cn/doc/content/themes-engine-next-base-figure-0000002471395006 Defines the structure for a Line element and provides an example. Use for drawing straight lines with specified start and end points, stroke, and style. ```xml ``` -------------------------------- ### Start a new UIAbility instance using startAbility() Source: https://developer.huawei.com/consumer/cn/doc/architecture-guides/common-v1_26-ts_c49-0000002362362286 This code demonstrates how to use the startAbility() method to launch a new UIAbility instance. In 'multiton' mode, this new instance will not inherit the split-screen display mode of the original window. ```typescript import { UIAbility, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onForeground() { let want: Want = { bundleName: 'com.example.myapplication', abilityName: 'EntryAbility' }; try { this.context.startAbility(want, (err: BusinessError) => { if (err.code) { console.error(`startAbility failed, code is ${err.code}, message is ${err.message}`); return; } console.info('startAbility succeed'); }); } catch (err) { let code = (err as BusinessError).code; let message = (err as BusinessError).message; console.error(`startAbility failed, code is ${code}, message is ${message}`); } } } ``` -------------------------------- ### Get AbilityDelegator and Start Ability Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-app-ability-abilitydelegatorregistry Obtain the AbilityDelegator object to interact with the test framework and start a specified ability. Ensure the Want object contains the correct bundleName and abilityName. ```javascript import { abilityDelegatorRegistry } from '@kit.TestKit'; import { Want } from '@kit.AbilityKit'; let abilityDelegator = abilityDelegatorRegistry.getAbilityDelegator(); let want: Want = { bundleName: 'com.example.myapplication', abilityName: 'EntryAbility' }; abilityDelegator.startAbility(want, (err) => { if (err) { console.error(`Failed start ability, error: ${JSON.stringify(err)}`); } else { console.info('Success start ability.'); } }); ``` -------------------------------- ### Get All Installed App Bundle Names Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/obtaining-target-app-url-info Use the 'bm dump -a' command to list all installed applications and their bundle names. This is the first step to identify the target application. ```bash hdc shell bm dump -a ``` -------------------------------- ### Start Ability using SelectionExtensionContext Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-selectioninput-selectionextensioncontext Demonstrates how to use the startAbility method of SelectionExtensionContext to launch another Ability. This method is asynchronous and returns a Promise. Ensure the target Ability's bundleName and abilityName are correctly specified. ```typescript import { SelectionExtensionAbility, BusinessError } from '@kit.BasicServicesKit'; import { rpc } from '@kit.IPCKit'; import { Want } from '@kit.AbilityKit'; class SelectionAbilityStub extends rpc.RemoteObject { constructor(des: string) { super(des); } onRemoteMessageRequest( code: number, data: rpc.MessageSequence, reply: rpc.MessageSequence, options: rpc.MessageOption ): boolean | Promise { console.info(`onRemoteMessageRequest code: ${code}`); return true; } } class SelectionExtAbility extends SelectionExtensionAbility { onConnect(want: Want): rpc.RemoteObject { try { let wantAbility: Want = { bundleName: "com.selection.selectionapplication", abilityName: "EntryAbility", }; this.context.startAbility(wantAbility).then(() => { console.info(`startAbility success`); }).catch((err: BusinessError) => { console.error(`startAbility error: ${err.code}, error message: ${err.message}`); }) } catch (err) { console.error(`startAbility error: ${err.code}, error message: ${err.message}`); } return new SelectionAbilityStub('remote'); } } ``` -------------------------------- ### Service Account Key File Example Source: https://developer.huawei.com/consumer/cn/doc/atomic-guides/instant-service-merchant-authentication This is an example of a Service Account key file, which contains credentials like key_id, private_key, and URIs for authentication. ```json 1. { 2. "key_id": "*****", 3. "private_key": "-----BEGIN PRIVATE KEY-----\nMIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCKw6kJKtCh7qmMvp1u1dI27z2TKZrPOzHbQaXO/Eez0AWZ2EN+ouF496R3pfo7fQXC1XOT/YTbVC4DNZwWSMA54fu3/AOCY9Zzyi46OK*****==\n-----END PRIVATE KEY-----\n", 4. "sub_account": "*****", 5. "auth_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize", 6. "token_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/token", 7. "auth_provider_cert_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/certs", 8. "client_cert_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/x509?client_id=" 9. } ``` -------------------------------- ### Full Dynamic AIPP Configuration Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/cannkit-aipp-configuration-file An example of a complete AIPP configuration with dynamic settings for various operations including crop, resize, padding, swap, CSC, and DTC. ```protobuf aipp_op { input_para { shape { src_image_size_w: 480 src_image_size_h: 384 } } crop_func { switch: true dynamic: true load_start_pos_w: 50 load_start_pos_h: 50 crop_size_w: 150 crop_size_h: 150 } resize_func { switch: true dynamic: true resize_output_w: 250 resize_output_h: 200 } padding_func { switch: true dynamic: true left_padding_size: 0 right_padding_size: 0 top_padding_size: 0 bottom_padding_size: 0 } swap_func { dynamic: true ax_swap_switch: true } csc_func { switch: true dynamic: true output_format: RGB888_U8 color_space: JPEG } dtc_func { switch: true dynamic: true } } ``` -------------------------------- ### Example of Setting and Getting Custom Properties Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-universal-attributes-custom-property Demonstrates how to set custom properties on a Column component and retrieve them from its corresponding FrameNode. This example utilizes the customProperty API and FrameNode's getCustomProperty method. ```APIDOC ``` 1. // xxx.ets 2. import { FrameNode, UIContext } from '@kit.ArkUI'; 3. 4. @Entry 5. @Component 6. struct CustomPropertyExample { 7. build() { 8. Column() { 9. Text('text') 10. Button('print').onClick(() => { 11. // Get the frameNode corresponding to the Column and query the set custom properties 12. const uiContext: UIContext = this.getUIContext(); 13. if (uiContext) { 14. const node: FrameNode | null = uiContext.getFrameNodeById("Test_Column") || null; 15. if (node) { 16. for (let i = 1; i < 4; i++) { 17. const key = 'customProperty' + i; 18. const property = node.getCustomProperty(key); 19. console.info(key, JSON.stringify(property)); 20. } 21. } 22. } 23. }) 24. } 25. .id('Test_Column') 26. // Set custom properties for the Column component 27. .customProperty('customProperty1', { 28. 'number': 10, 29. 'string': 'this is a string', 30. 'bool': true, 31. 'object': { 32. 'name': 'name', 33. 'value': 100 34. } 35. }) 36. .customProperty('customProperty2', {}) 37. .customProperty('customProperty3', undefined) 38. .width('100%') 39. .height('100%') 40. } 41. } ``` ``` -------------------------------- ### Quick Game Directory Structure Example Source: https://developer.huawei.com/consumer/cn/doc/games-guides/games-quickgame-playable-subpackage-0000002351893469 This example shows a typical directory structure for a Quick Game project, including main package and subpackage folders. The 'subpackages' directory contains both regular and web version independent subpackages. ```plaintext 1. ├── assets 2. ├── image 3. └── icons.png 4. └── 1.png 5. ├── jsb-adapter 6. ├── src 7. ├── subpackages // 分包文件夹 8. └── moduleA // 普通分包 9. └── game.js // 普通分包入口文件,且分包入口文件只能命名为game.js 10. └── main.js 11. └── moduleB // Web版本独立分包 12. └── assets 13. └── src 14. └── index.html // Web版本独立分包入口文件 15. └── main.js 16. ├── game.js // 主包入口文件 17. ├── manifest.json // 配置文件 ``` -------------------------------- ### Failed Response Example Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/account-api-getuserrisklevel This example shows a failed response from the Get User Risk Level API, typically due to insufficient permissions. The 'errCode' will indicate the error, and 'errMsg' will provide a description. ```json HTTP/1.1 200 OK Content-Type: application/json;charset=utf-8 { "errCode": 403, "errMsg": "no permission" } ``` -------------------------------- ### Example Output of Importing User DB Data Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-ohpm-repo-import-userinfo This is an example output showing the process of importing user data, including verification, initialization, cleaning, and data import stages. ```bash PS D:\> ohpm-repo import_userinfo D:\export_userInfo_1754738056722.zip --clean-db [2025-08-09T19:19:31.623] [INFO] default - verifying the validity of the meta crypto component. [2025-08-09T19:19:31.633] [INFO] default - the meta crypto component is verified successfully. [2025-08-09T19:19:31.639] [INFO] default - initialize "file database" successfully. [2025-08-09T19:19:31.660] [INFO] default - all database data has been cleaned. [2025-08-09T19:19:31.660] [INFO] default - importing data in the 'user.json' file. ... [2025-08-09T19:19:31.673] [INFO] default - importing data in the 'system_security.json' file. [2025-08-09T19:19:31.674] [INFO] default - data import finished. ``` -------------------------------- ### Get Template List API Response Example Source: https://developer.huawei.com/consumer/cn/doc/FASP-by-Template-develop-References/get-template-list-0000001552137521 This example demonstrates the structure of a successful response when retrieving a list of templates. It includes details such as template ID, creation time, description, and type. ```json { "ret": { "code": 0, "msg": "success" }, "templateList": [ { "templateId": 1118****1040, "createTime": 1679571565000, "lastUpdateTime": 1679571565000, "userDesc": "描述信息", "templateType": 0, "userVersion": "1.0.0", "draftId": 1110****2352, "mode": 1, "packageType": "APP", "categoryId": 10000001 } ] } ``` -------------------------------- ### Prepare and Start Media Playback Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/distributed-playback-guide This snippet demonstrates how to prepare and start media playback using the AV cast controller. It includes setting up playback parameters like media URI, type, and DRM scheme. ```typescript playItem() { let playItem : avSession.AVQueueItem = { itemId: 0, description: { assetId: 'VIDEO-1', title: 'ExampleTitle', artist: 'ExampleArtist', mediaUri: 'https://xxx.xxx.com/example.mp4', mediaType: 'VIDEO', mediaSize: 1000, startPosition: 0, duration: 100000, albumCoverUri: 'https://www.example.jpeg', albumTitle: '《ExampleAlbum》', appName: 'ExampleApp', drmScheme: '3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c', } }; this.castController?.prepare(playItem, () => { console.info('Preparation done'); this.castController?.start(playItem, () => { console.info('Playback started'); }); }); } ```