### Install Flask for Video Server Setup Source: https://github.com/linganmin/harmonyos_samples/blob/main/SmoothSwitchShortVideos/README.en.md This command installs the Flask framework, a Python micro web framework, which is required to run the provided Python script for setting up a local video server. Ensure you have pip installed. ```bash pip install flask ``` -------------------------------- ### Flutter Environment Setup Guide Source: https://github.com/linganmin/harmonyos_samples/blob/main/accountkit-samplecode-clientdemo-flutter/readme_cn.md Instructions for configuring the Flutter development environment for OpenHarmony. This includes cloning the Flutter repository, setting environment variables for Flutter, JDK, and Pub cache, and verifying the setup with `flutter doctor`. ```shell git clone https://gitee.com/openharmony-sig/flutter_flutter.git export FLUTTER_ROOT= ${clone下来的项目代码} export PATH=%FLUTTER_ROOT%\bin:$PATH export JAVA_HOME=${jdk的安装位置} export PATH=%JAVA_HOME%\bin:$PATH export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn export PUB_HOSTED_URL=https://pub.flutter-io.cn export PUB_CACHE=D:/PUB(自定义路径,新建一个空文件夹即可) flutter doctor -v ``` -------------------------------- ### Bash Script for Build Environment Preparation Source: https://github.com/linganmin/harmonyos_samples/blob/main/guide-snippets/ArkUIKit/LayoutSample/README_zh.md A bash script providing instructions for preparing the development environment. It outlines essential steps like ensuring DevEco Studio and HarmonyOS SDK are installed and configured, and that devices are connected. This is a setup instruction, not executable code within the project itself. ```bash # Ensure DevEco Studio and HarmonyOS development toolkit are installed. # Configure the development environment and connect your HarmonyOS device or simulator. # No direct commands are provided here, as it's a setup checklist. ``` -------------------------------- ### Install Resource Pre-fetching Source: https://github.com/linganmin/harmonyos_samples/blob/main/cloud-foundation-kit_-sample-code_-arkts/README.md This code demonstrates how to initiate resource pre-fetching upon application installation. It uses the `cloudResPrefetch.getPrefetchResult` method with `cloudResPrefetch.PrefetchMode.INSTALL_PREFETCH` to fetch resources that should be available immediately after installation. ```typescript cloudResPrefetch.getPrefetchResult(cloudResPrefetch.PrefetchMode.INSTALL_PREFETCH).then(result => { console.log('Install prefetch result:', result); }).catch(error => { console.error('Install prefetch failed:', error); }); ``` -------------------------------- ### Cloud Storage: Upload, Download, Delete, Get URL, List, Get/Set Metadata Source: https://github.com/linganmin/harmonyos_samples/blob/main/cloud-foundation-kit_-sample-code_-arkts/README.en.md Provides code examples for essential Cloud Storage operations. This includes uploading files using a picker, downloading files, deleting files, obtaining download URLs, listing files in a bucket, and managing file metadata. ```ets import cloudStorage from '@ohos.cloudstorage' import fs from '@ohos.fs' // Assuming 'context' is available and 'UI' is an object with 'uploadFileName' let context: Context; // Placeholder for actual context let UI = { uploadFileName: 'myFile.txt' }; // Placeholder // Upload File async function uploadFile() { const cacheDir = await fs.getCacheDir(context); const cacheFile = `${cacheDir}/${UI.uploadFileName}`; // Assume photoAccessHelper.PhotoViewPicker() is implemented elsewhere and returns a file path const selectedFilePath = await photoAccessHelper.PhotoViewPicker(); // Placeholder await fs.copyFile(selectedFilePath, cacheFile); cloudStorage.bucket().uploadFile(context, { localPath: cacheFile, cloudPath: UI.uploadFileName, mode: cloudStorage.UploadMode.BACKGROUND }).then(result => { console.log('File uploaded successfully:', result); }).catch(error => { console.error('File upload failed:', error); }); } // Download File function downloadFile() { cloudStorage.bucket().downloadFile(context, { localPath: `./${Date.now()}_${UI.uploadFileName}`, cloudPath: UI.uploadFileName }).then(result => { console.log('File downloaded successfully:', result); }).catch(error => { console.error('File download failed:', error); }); } // Delete File function deleteFile() { cloudStorage.bucket().deleteFile(UI.uploadFileName).then(result => { console.log('File deleted successfully:', result); }).catch(error => { console.error('File deletion failed:', error); }); } // Get Download URL function getDownloadURL() { cloudStorage.bucket().getDownloadURL(UI.uploadFileName).then(url => { console.log('Download URL:', url); }).catch(error => { console.error('Failed to get download URL:', error); }); } // List Files function listFiles() { cloudStorage.bucket().list('').then(fileList => { console.log('File list:', fileList); }).catch(error => { console.error('Failed to list files:', error); }); } // Get Metadata function getMetadata() { cloudStorage.bucket().getMetadata(UI.uploadFileName).then(metadata => { console.log('File metadata:', metadata); }).catch(error => { console.error('Failed to get metadata:', error); }); } // Set Metadata function setMetadata() { cloudStorage.bucket().setMetadata(UI.uploadFileName, { customMetadata: { key1: "value1", key2: "value2" } }).then(result => { console.log('Metadata set successfully:', result); }).catch(error => { console.error('Failed to set metadata:', error); }); } ``` -------------------------------- ### AR Engine Setup Source: https://github.com/linganmin/harmonyos_samples/blob/main/arengine_-sample-code_-clientdemo_cpp/README_EN.md Instructions for integrating AR Engine libraries and header files into your CMakeLists and C++ code. ```APIDOC ## AR Engine Setup ### Description Instructions for integrating AR Engine libraries and header files into your CMakeLists and C++ code. ### Integrating Libraries To use AR Engine APIs, you need to add the following dependencies to **CMakeLists**: ```cmake find_library( arengine-lib libarengine_ndk.z.so ) target_link_libraries(entry PUBLIC ${arengine-lib} ) ``` ### Importing Header File Import the header file: ```c #include "ar/ar_engine_core.h" ``` ``` -------------------------------- ### HarmonyOS Project Structure Example Source: https://github.com/linganmin/harmonyos_samples/blob/main/guide-snippets/BmsSample/AppConfigurationFile/README_zh.md Illustrates the typical directory structure for a HarmonyOS application project, highlighting key configuration and source files. ```tree AppScope/ | |---resources/ // 工程级的资源目录 | |--- app.json5 // 应用的全局配置信息 entry/src/ | |--- main/ | |--- module.json5 // entry模块配置hap类型:"type": "entry" | |---ets/ | |---entryability/EntryAbility.ets // 应用启动加载的入口ability | |---entrybackupability/EntryBackupAbility.ets // extensionAbility。 | |---pages/index.ets // entry主应用入口页面 ``` -------------------------------- ### Page Implementation Example (EntryPageOne) Source: https://github.com/linganmin/harmonyos_samples/blob/main/system-router-map/README.en.md An example page implementation within a HarmonyOS application, likely part of a navigation flow. It demonstrates basic UI structure and potential interaction points. ```ets import { Logger } from '../common/utils/Logger'; @Entry @Component struct EntryPageOne { @State message: string = 'Hello World!'; private TAG: string = 'EntryPageOne'; build() { Row { Column { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) Button('Jump to Page 2') .onClick(() => { Logger.info(this.TAG, 'Navigating to EntryPageTwo'); router.push({ name: 'entryPageTwo', params: { message: 'Navigated from EntryPageOne' } }); }) } .width('100%') } .height('100%') } aboutToAppear() { Logger.info(this.TAG, 'Page about to appear'); } onPageHide() { Logger.info(this.TAG, 'Page hidden'); } onPageShown() { Logger.info(this.TAG, 'Page shown'); } } ``` -------------------------------- ### CMake Project Setup and Library Configuration Source: https://github.com/linganmin/harmonyos_samples/blob/main/arengine_-sample-code_-clientdemo_cpp/entry/src/main/cpp/CMakeLists.txt This snippet shows the basic CMake setup for the ARSample project. It defines the minimum CMake version, sets the project name, specifies the C++ standard to C++17, and defines the native root path. It also demonstrates how to find and link the 'libarengine_ndk.z.so' library, which is crucial for AR functionalities. ```cmake cmake_minimum_required(VERSION 3.5.0) project(ARSample) set(CMAKE_CXX_STANDARD 17) set(NATIVE_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) find_library(arengine-lib libarengine_ndk.z.so) ``` -------------------------------- ### Install Git Keyword Expansion Filter (Windows CMD) Source: https://github.com/linganmin/harmonyos_samples/blob/main/xengine-samplecode-vulkan-demo-cpp/entry/src/main/cpp/3rdParty/ktx/README.md Installs the Git keyword expansion filter for $Date$ keywords on Windows using the Command Prompt. This involves running a batch script and then deleting and checking out specific files to apply the filter. ```cmd install-gitconfig.bat del TODO.md include/ktx.h tools/toktx/toktx.cpp git checkout TODO.md include/ktx.h tools/toktx/toktx.cpp ``` -------------------------------- ### Install Hamock using ohpm Source: https://github.com/linganmin/harmonyos_samples/blob/main/BestPracticeSnippets/MultipleImage/oh_modules/@ohos/hamock/README.md This command installs the Hamock framework on your OpenHarmony project using the ohpm package manager. Ensure you have the ohpm environment configured correctly. ```bash ohpm install @ohos/hamock ``` -------------------------------- ### Setup Wallet Environment Source: https://github.com/linganmin/harmonyos_samples/blob/main/wallet-kit-for-harmony-os_demo/readme_en.md Initializes the Wallet app's environment. This is necessary to be called when encountering specific Wallet app errors, guiding the user to install or set up the app. ```APIDOC ## POST /api/wallet/environment/setup ### Description Sets up the Wallet app's environment. This API should be called when encountering errors such as 'Wallet app not found' or 'Environment not ready'. It guides the user through the necessary steps to prepare the Wallet app for use. ### Method POST ### Endpoint /api/wallet/environment/setup ### Parameters None ### Request Example POST /api/wallet/environment/setup ### Response #### Success Response (200) - This endpoint returns a Promise, indicating success with no return value upon completion. #### Response Example (No response body on success) ``` -------------------------------- ### Log Action Start and End | JavaScript Source: https://github.com/linganmin/harmonyos_samples/blob/main/xengine-samplecode-subpass-shading-demo-cpp/oh_modules/@ohos/hypium/README.md This code example shows how to log the start and end of an action in the command-line interface using SysTestKit.actionStart and SysTestKit.actionEnd. These functions take a string tag to mark the beginning and end of a process, helping to delineate specific operations within test execution logs. They do not return any value. ```javascript import { describe, it, expect, SysTestKit} from '@ohos/hypium'; export default function actionTest() { describe('actionTest', function () { it('existKeyword',DEFAULT, async function () { let tag = '[MyTest]'; SysTestKit.actionStart(tag); //do something SysTestKit.actionEnd(tag); }) }) } ``` -------------------------------- ### Download HarmonyOS Project Sample Source: https://github.com/linganmin/harmonyos_samples/blob/main/guide-snippets/BmsSample/AppConfigurationFile/README_zh.md Provides the Git commands required to clone a specific sample project for HarmonyOS application configuration. ```bash git init git config core.sparsecheckout true echo code/DocsSample/bmsSample/AppConfigurationFile > .git/info/sparse-checkout git remote add origin https://gitcode.com/openharmony/applications_app_samples.git git pull origin master ``` -------------------------------- ### SpecifiedAbility Implementation in HarmonyOS Source: https://github.com/linganmin/harmonyos_samples/blob/main/ability-start-mode/README.en.md An example of a UIAbility configured for the specified launch mode. This mode allows starting a specific instance of an ability, potentially reusing an existing one. ```ets import UIAbility from '@ohos.app.ability.UIAbility' import Window from '@ohos.window' import Want from '@ohos.base.Want' export default class SpecifiedAbility extends UIAbility { onCreate(want: Want, launchParam: Record | undefined) { console.info('SpecifiedAbility onCreate. want: ' + JSON.stringify(want)); } onDestroy() { console.info('SpecifiedAbility onDestroy'); } onWindowCreate(window: Window.WindowType) { console.info('SpecifiedAbility onWindowCreate'); window.setUIContent({ appInfo: this.context.getApplicationInfo(), window: window }); } onForeground() { console.info('SpecifiedAbility onForeground'); } onBackground() { console.info('SpecifiedAbility onBackground'); } onAcceptWant(want: Want): Want | undefined { console.info('SpecifiedAbility onAcceptWant. want: ' + JSON.stringify(want)); return want; } } ``` -------------------------------- ### Producer-Consumer Pattern Example - ETS Source: https://github.com/linganmin/harmonyos_samples/blob/main/UseSendable/README.en.md Demonstrates the producer-consumer pattern for log generation and consumption using multiple threads. It showcases how to start and stop continuous log generation and manage consumer threads. ```ETS /* * Copyright (c) 2023 Huawei Device Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Component, State, Watch } from '@devextreme/runtime'; import hilog from '@ohos.hilog'; import { logger } from '../utils/Logger'; interface ProducerConsumerData { content: string; } @Component export struct ProducerConsumerPage { @State isProducerStart: boolean = false; @State isOneConsumerStart: boolean = false; @State isTwoConsumersStart: boolean = false; @State isTenThreadsStart: boolean = false; @State isContinuous: boolean = false; @State isStopConsumer: boolean = false; logText: string = ''; build() { Column({ space: 10 }) { Text('Producer-Consumer Pattern') .fontSize(20) .fontWeight(700) .margin({ bottom: 20 }) Row({ space: 10 }) { Button('One consumer thread consumes') .onClick(() => { this.isOneConsumerStart = !this.isOneConsumerStart; this.isProducerStart = true; this.isContinuous = false; this.isTwoConsumersStart = false; this.isTenThreadsStart = false; this.isStopConsumer = false; this.producerConsumerData.push({ content: 'one consumer thread consumes' }); }) Button('Two consumer threads consume') .onClick(() => { this.isTwoConsumersStart = !this.isTwoConsumersStart; this.isProducerStart = true; this.isContinuous = false; this.isOneConsumerStart = false; this.isTenThreadsStart = false; this.isStopConsumer = false; this.producerConsumerData.push({ content: 'two consumer threads consume' }); }) } Row({ space: 10 }) { Button('Ten child threads generate ten logs') .onClick(() => { this.isTenThreadsStart = !this.isTenThreadsStart; this.isProducerStart = true; this.isContinuous = false; this.isOneConsumerStart = false; this.isTwoConsumersStart = false; this.isStopConsumer = false; this.producerConsumerData.push({ content: 'ten child threads generate ten logs' }); }) Button('Continuously generate logs') .onClick(() => { this.isContinuous = !this.isContinuous; this.isProducerStart = true; this.isOneConsumerStart = false; this.isTwoConsumersStart = false; this.isTenThreadsStart = false; this.isStopConsumer = false; this.producerConsumerData.push({ content: 'continuously generate logs' }); }) } Row({ space: 10 }) { Button('Main thread generates one log') .onClick(() => { this.producerConsumerData.push({ content: 'main thread generates one log' }); }) Button('Stop continuous log generation') .onClick(() => { this.isContinuous = false; this.isProducerStart = false; this.isOneConsumerStart = false; this.isTwoConsumersStart = false; this.isTenThreadsStart = false; this.producerConsumerData.push({ content: 'stop continuous log generation' }); }) } Row({ space: 10 }) { Button('Stop consumer thread') .onClick(() => { this.isStopConsumer = !this.isStopConsumer; this.producerConsumerData.push({ content: 'stop consumer thread' }); }) } Scroll() .scrollable(true) .height(200) .width('100%') .children([ Text(this.logText) .fontSize(12) .lineHeight(20) .width('100%') ]) } .width('100%') .height('100%') .padding(20) } @State producerConsumerData: ProducerConsumerData[] = []; aboutToAppear() { this.updateStateLog(); } @Watch('producerConsumerData') updateStateLog() { this.logText = ''; this.producerConsumerData.forEach(data => { this.logText += data.content + '\n'; }); const logData: ProducerConsumerData = { content: this.logText }; this.consumerLog(logData); } consumerLog(data: ProducerConsumerData) { if (this.isOneConsumerStart) { logger.info(JSON.stringify(data)); } if (this.isTwoConsumersStart) { logger.info(JSON.stringify(data)); logger.info(JSON.stringify(data)); } if (this.isTenThreadsStart) { for (let i = 0; i < 10; i++) { logger.info(JSON.stringify(data)); } } if (this.isContinuous) { setTimeout(() => { this.producerConsumerData.push(data); }, 100); } if (this.isStopConsumer) { this.producerConsumerData = []; } } } ``` -------------------------------- ### Query Asset from Asset Store Kit (ArkTS) Source: https://github.com/linganmin/harmonyos_samples/blob/main/guide-snippets/Security/AssetStoreKit/AssetStoreArkTS/README.md Provides an example of how to query a critical asset from the Asset Store Kit using its key. This function retrieves the stored sensitive data. The implementation uses ArkTS. ```ArkTS import assetStore from '@ohos.data.assetstore'; async function queryAsset(key: string): Promise { try { const store = await assetStore.open('my_asset_store'); const value = await store.get(key); console.log('Asset queried successfully'); store.close(); return value; } catch (error) { console.error('Failed to query asset:', error); return undefined; } } ``` -------------------------------- ### HarmonyOS Native App Build Configuration (CMakeLists.txt) Source: https://github.com/linganmin/harmonyos_samples/blob/main/cannkit-samplecode-clientdemo-cpp/entry/src/main/cpp/CMakeLists.txt This snippet configures the build process for a HarmonyOS native application using CMake. It sets up the minimum required CMake version, project name, includes necessary directories for native rendering and system libraries, finds the 'cann-lib' library, and defines a shared library 'entry' linked with various HarmonyOS system libraries and the found 'cann-lib'. ```cmake cmake_minimum_required(VERSION 3.4.1) project(CANNDemo) set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${NATIVERENDER_ROOT_PATH} ${NATIVERENDER_ROOT_PATH}/include) include_directories(${HMOS_SDK_NATIVE}/sysroot/usr/lib) FIND_LIBRARY(cann-lib hiai_foundation) add_library(entry SHARED Classification.cpp HIAIModelManager.cpp) target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so ${cann-lib} libneural_network_core.so ) ``` -------------------------------- ### HarmonyOS Button with Navigation Source: https://github.com/linganmin/harmonyos_samples/blob/main/state-management/entry/src/main/resources/rawfile/AbilityGlobalDataSyncCode.ets.html Demonstrates creating a styled Button component in HarmonyOS. It includes text styling, size, alignment, and click handling for navigation to a new page or starting a specified ability. Relies on HarmonyOS UI framework and router module. ```ArkTS Button() { Text($r('app.string.enter\_pagetwo')) .fontColor(this.currentModelStatus ? $r('app.color.color\_white') : $r('app.color.button\_text\_color')) .fontSize(this.contentFontSize) .width('60%') .textAlign(TextAlign.Center) } .type(ButtonType.Capsule) .backgroundColor($r('app.color.button\_background\_color')) .padding($r('app.float.page\_padding')) .onClick(() \=> { router.pushUrl({ url: 'pages/applylevelstagemanagement/abilityglobaldatasync/LocalStorageLinkPage' }); }) Divider().width('100%').strokeWidth(1) Button() { Text($r('app.string.enter\_ability\_outofsync')) .fontColor(this.currentModelStatus ? $r('app.color.color\_white') : $r('app.color.button\_text\_color')) .fontSize(this.contentFontSize) .width('60%') .textAlign(TextAlign.Center) } .type(ButtonType.Capsule) .backgroundColor($r('app.color.button\_background\_color')) .padding($r('app.float.page\_padding')) .onClick(() \=> { startSpecifiedAbility('OutOfSyncAbility'); }) ``` -------------------------------- ### CMake Project Setup and Definitions Source: https://github.com/linganmin/harmonyos_samples/blob/main/xengine-samplecode-vulkan-demo-cpp/entry/src/main/cpp/CMakeLists.txt Initializes the CMake build system, sets the project name, and defines preprocessor macros for cross-platform compatibility and feature toggling. It specifies the minimum required CMake version and project name. ```cmake cmake_minimum_required(VERSION 3.4.1) project(XComponent) set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) ADD_DEFINITIONS(-DVK_USE_PLATFORM_OHOS=1) ADD_DEFINITIONS(-DVK_NO_PROTOTYPES=1) add_definitions(-DOHOS_PLATFORM) add_definitions(-DSTB_IMAGE_IMPLEMENTATION) ``` -------------------------------- ### Create GL Texture Object from KTX File Source: https://github.com/linganmin/harmonyos_samples/blob/main/xengine-samplecode-vulkan-temporal-upscale-demo-cpp/entry/src/main/cpp/3rdParty/ktx/lib/mainpage.md Shows how to create a ktxTexture object from a KTX file and upload it to create an OpenGL texture. It uses ktxtexture_GLUpload for the conversion and requires GL context setup. The ktxTexture object must be destroyed after the upload. ```c #include ktxTexture* kTexture; KTX_error_code result; ktx_size_t offset; ktx_uint8_t* image; ktx_uint32_t level, layer, faceSlice; GLuint texture = 0; GLenum target, glerror; result = ktxTexture_CreateFromNamedFile("mytex3d.ktx", KTX_TEXTURE_CREATE_NO_FLAGS, &kTexture); glGenTextures(1, &texture); // Optional. GLUpload can generate a texture. result = ktxtexture_GLUpload(kTexture, &texture, &target, &glerror); ktsTexture_Destroy(kTexture); // Corrected: should be ktxTexture_Destroy // ... // GL rendering using the texture // ... ``` -------------------------------- ### UI Components and Utilities Source: https://github.com/linganmin/harmonyos_samples/blob/main/accountkit-samplecode-clientdemo-arkts/readme_cn.md Documentation for reusable UI components and utility classes. ```APIDOC ## Avoid Repeat Click Utility ### Description A utility class designed to prevent users from repeatedly clicking buttons or triggering actions in quick succession. ### Method N/A (Utility Class) ### Endpoint N/A ### Usage Instantiate `AvoidRepeatClick` and use its methods to wrap click handlers. ## Agreement Dialog Component ### Description A customizable dialog component used to display user agreements and privacy policies. ### Method N/A (Component) ### Endpoint N/A ### Usage Can be controlled using `CustomDialogController` to manage its visibility. ## User Info Data Structure ### Description Defines the data structure for user information, including details like username, ID, etc. ### Method N/A (Data Structure) ### Endpoint N/A ### Fields - **userId** (string) - Unique identifier for the user. - **username** (string) - The user's display name. ## Error Code Entity ### Description Defines common entity data information for error codes and constants that may be encountered during various processes, such as login. ### Method N/A (Data Structure) ### Endpoint N/A ### Fields - **errorCode** (number) - The numeric error code. - **errorMessage** (string) - A descriptive message for the error. ## Protocol Web View Component ### Description A component that displays web content, specifically used for rendering the Huawei Account User Authentication Agreement. ### Method N/A (Component) ### Endpoint N/A ### Usage Fetches the URL from `data.json`. Currently supports English and Chinese. ``` -------------------------------- ### Initialize Startup Tasks with StartupConfigEntry (ArkTS) Source: https://github.com/linganmin/harmonyos_samples/blob/main/AppStartUp/README.en.md Configures the startup framework by defining tasks and their dependencies in a JSON file. This allows for organized and efficient app initialization. It requires referencing the startup_config.json in module.json5 and setting startup parameters in StartupConfig.ets. ```json { "startup": [ { "taskName": "KvManagerUtilTask", "dependencies": [], "async": false, "path": "entry/src/main/ets/startup/KvManagerUtilTask.ets" }, { "taskName": "KVStoreTask", "dependencies": ["KvManagerUtilTask"], "async": false, "path": "entry/src/main/ets/startup/KVStoreTask.ets" }, { "taskName": "RdbStoreTask", "dependencies": ["KvManagerUtilTask"], "async": false, "path": "entry/src/main/ets/startup/RdbStoreTask.ets" }, { "taskName": "ResourceManagerTask", "dependencies": [], "async": false, "path": "entry/src/main/ets/startup/ResourceManagerTask.ets" }, { "taskName": "FileTask", "dependencies": ["ResourceManagerTask"], "async": true, "path": "entry/src/main/ets/startup/FileTask.ets" }, { "taskName": "ImageKnifeTask", "dependencies": ["ResourceManagerTask"], "async": false, "path": "entry/src/main/ets/startup/ImageKnifeTask.ets" } ] } ``` ```ArkTS import AppStartup, { StartupConfig } from "@ohos.app.startup"; @Entry @Component struct Index { private router: Router; aboutToAppear() { this.router = Router; } build() { Row() { Column() { Text('Automatic Mode') .fontSize(20) .fontWeight(FontWeight.Bold) .onClick(() => { this.router.push({ url: 'pages/AutoModePage' }); }) .padding(10); Text('Manual Mode') .fontSize(20) .fontWeight(FontWeight.Bold) .onClick(() => { this.router.push({ url: 'pages/ManualModePage' }); }) .padding(10); } .width('100%') } .height('100%') } } // Initialize startup tasks AppStartup.init(); ``` -------------------------------- ### Handle App Installation and Updates (ArkTS) Source: https://github.com/linganmin/harmonyos_samples/blob/main/appgallerykit-samplecode-clientdemo-arkts/readme_en.md Enables users to download and install applications from AppGallery and check for app updates. It displays an app details page for installation and provides functionality for update detection. ```ArkTS import featureAbility from "@ohos.ability.featureability.featureAbility"; import hilog from "@ohos.hilog"; const TAG = "[AppInstallUpdate]" export class AppInstallUpdate { // Load product for app download and installation loadProduct(bundleName: string) { featureAbility.callAbilityManager("loadProduct", { "bundleName": bundleName }).then(data => { hilog.info(0x0001, TAG, 'loadProduct success: %{public}s', JSON.stringify(data)); }).catch(error => { hilog.error(0x0001, TAG, 'loadProduct failed: %{public}s', JSON.stringify(error)); }); } // Check for app updates checkUpdate(bundleName: string) { featureAbility.callAbilityManager("checkUpdate", { "bundleName": bundleName }).then(data => { hilog.info(0x0001, TAG, 'checkUpdate success: %{public}s', JSON.stringify(data)); }).catch(error => { hilog.error(0x0001, TAG, 'checkUpdate failed: %{public}s', JSON.stringify(error)); }); } } ``` -------------------------------- ### Project Directory Structure for ArkWeb Same-level Rendering Source: https://github.com/linganmin/harmonyos_samples/blob/main/arkweb-same-level-rendering/README_EN.md This snippet outlines the project directory structure for the ArkWeb same-level rendering sample. It highlights key files such as the EntryAbility configuration, GoodsModel type declaration, Index entry point, and GoodsViewModel simulated data class, along with the resource directory. ```plaintext ├──entry/src/main/ets/ │ ├──entryability │ │ └──EntryAbility.ets // Configuration class │ ├──model │ │ └──GoodsModel.ets // Type declaration │ ├──pages │ │ └──Index.ets // Entry point class │ └──viewmodel │ └──GoodsViewModel.ets // Simulated data class └──entry/src/main/resource // Static resources of the app ``` -------------------------------- ### Service Account Credential File Example (JSON) Source: https://github.com/linganmin/harmonyos_samples/blob/main/push-kit-service-sample-code-timeline-java/README.en.md An example structure of a service account credential file, which is required to authenticate and call Push Kit APIs. It contains sensitive information like project ID, key ID, and private key, which should be anonymized in the example. ```json { "project_id": "*****", "key_id": "*****", "private_key": "-----BEGIN PRIVATE KEY-----\n**********************************==\n-----END PRIVATE KEY-----", "sub_account": "*****", "auth_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize", "token_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/token", "auth_provider_cert_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/certs", "client_cert_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/x509?client_id=*****" } ``` -------------------------------- ### HarmonyOS RDB: Initialize, Create Table, Insert, Query, Update, Delete User Source: https://context7.com/linganmin/harmonyos_samples/llms.txt This TypeScript code demonstrates how to initialize an RDB store, create a user table, and perform insert, query, update, and delete operations on user data. It includes essential error handling and manages the database connection lifecycle. ```typescript import { relationalStore } from '@ohos.data.relationalStore'; import { BusinessError } from '@ohos.base'; import { common } from '@ohos.app.ability.common'; const DB_NAME = 'UserDatabase.db'; const TABLE_NAME = 'USER_TABLE'; interface UserData { id?: number; name: string; age: number; email: string; } class DatabaseManager { private store: relationalStore.RdbStore | null = null; private context: common.UIAbilityContext; constructor(context: common.UIAbilityContext) { this.context = context; } async initDatabase(): Promise { const config: relationalStore.StoreConfig = { name: DB_NAME, securityLevel: relationalStore.SecurityLevel.S1 }; try { this.store = await relationalStore.getRdbStore(this.context, config); await this.createTable(); console.info('Database initialized successfully'); } catch (error) { console.error(`Failed to initialize database: ${JSON.stringify(error)}`); throw error; } } private async createTable(): Promise { const createTableSql = ` CREATE TABLE IF NOT EXISTS ${TABLE_NAME} ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER NOT NULL, email TEXT UNIQUE NOT NULL ) `; try { await this.store!.executeSql(createTableSql); console.info('Table created successfully'); } catch (error) { console.error(`Failed to create table: ${JSON.stringify(error)}`); throw error; } } async insertUser(user: UserData): Promise { if (!this.store) { throw new Error('Database not initialized'); } const valueBucket: relationalStore.ValuesBucket = { name: user.name, age: user.age, email: user.email }; try { const rowId = await this.store.insert(TABLE_NAME, valueBucket); console.info(`User inserted with row ID: ${rowId}`); return rowId; } catch (error) { console.error(`Failed to insert user: ${JSON.stringify(error)}`); throw error; } } async queryAllUsers(): Promise { if (!this.store) { throw new Error('Database not initialized'); } const predicates = new relationalStore.RdbPredicates(TABLE_NAME); const users: UserData[] = []; try { const resultSet = await this.store.query(predicates); while (resultSet.goToNextRow()) { users.push({ id: resultSet.getLong(resultSet.getColumnIndex('id')), name: resultSet.getString(resultSet.getColumnIndex('name')), age: resultSet.getLong(resultSet.getColumnIndex('age')), email: resultSet.getString(resultSet.getColumnIndex('email')) }); } resultSet.close(); console.info(`Query returned ${users.length} users`); return users; } catch (error) { console.error(`Failed to query users: ${JSON.stringify(error)}`); throw error; } } async updateUser(id: number, user: Partial): Promise { if (!this.store) { throw new Error('Database not initialized'); } const valueBucket: relationalStore.ValuesBucket = {}; if (user.name) valueBucket.name = user.name; if (user.age) valueBucket.age = user.age; if (user.email) valueBucket.email = user.email; const predicates = new relationalStore.RdbPredicates(TABLE_NAME); predicates.equalTo('id', id); try { const rowsAffected = await this.store.update(valueBucket, predicates); console.info(`Updated ${rowsAffected} rows`); return rowsAffected; } catch (error) { console.error(`Failed to update user: ${JSON.stringify(error)}`); throw error; } } async deleteUser(id: number): Promise { if (!this.store) { throw new Error('Database not initialized'); } const predicates = new relationalStore.RdbPredicates(TABLE_NAME); predicates.equalTo('id', id); try { const rowsAffected = await this.store.delete(predicates); console.info(`Deleted ${rowsAffected} rows`); return rowsAffected; } catch (error) { console.error(`Failed to delete user: ${JSON.stringify(error)}`); throw error; } } async closeDatabase(): Promise { if (this.store) { this.store = null; console.info('Database closed'); } } } // Usage example @Entry @Component struct DatabaseDemo { private dbManager: DatabaseManager | null = null; @State users: UserData[] = []; async aboutToAppear() { const context = getContext(this) as common.UIAbilityContext; this.dbManager = new DatabaseManager(context); try { await this.dbManager.initDatabase(); ``` -------------------------------- ### Prefetch Data (Installation and Periodic) Source: https://github.com/linganmin/harmonyos_samples/blob/main/cloud-foundation-kit_-sample-code_-arkts/README.en.md Shows how to implement data prefetching in HarmonyOS applications. This includes obtaining data during app installation and registering/retrieving data for periodic prefetching tasks. ```ets import cloudResPrefetch from '@ohos.cloudresprefetch' // Prefetch During Installation function prefetchDuringInstallation() { cloudResPrefetch.getPrefetchResult(cloudResPrefetch.PrefetchMode.INSTALL_PREFETCH).then(result => { console.log('Installation prefetch result:', result); }).catch(error => { console.error('Installation prefetch failed:', error); }); } // Periodic Prefetch Task Registration and Retrieval function managePeriodicPrefetch() { // Register a periodic prefetch task (details of task configuration omitted for brevity) cloudResPrefetch.registerPrefetchTask({ /* task configuration */ }).then(() => { console.log('Periodic prefetch task registered.'); // Get prefetch results cloudResPrefetch.getPrefetchResult(cloudResPrefetch.PrefetchMode.PERIODIC_PREFETCH).then(result => { console.log('Periodic prefetch result:', result); }).catch(error => { console.error('Periodic prefetch failed:', error); }); }).catch(error => { console.error('Failed to register periodic prefetch task:', error); }); } ``` -------------------------------- ### Run Video Server Script Source: https://github.com/linganmin/harmonyos_samples/blob/main/SmoothSwitchShortVideos/README.en.md This command executes the Python script 'video_server.py' to start a Flask server. This server is used to simulate network video access for the HarmonyOS sample. Ensure the script is in the 'server' folder and the Python environment is set up. ```bash python video_server.py ``` -------------------------------- ### Guide to Turn On Minors Mode Source: https://github.com/linganmin/harmonyos_samples/blob/main/account-kit-samplecode-clientdemo-for-atomicservice-arkts/readme_en.md Illustrates the function to guide users to enable minors mode using the minorsProtection API. This is part of the youth protection features in the HarmonyOS application. ```ets // For details, please refer to MinorsProtection.ets // Use minorsProtection.leadToTurnOnMinorsMode to guide users to enable the youth mode. ``` -------------------------------- ### Download HarmonyOS Application Data Security Sample Project Source: https://github.com/linganmin/harmonyos_samples/blob/main/BestPracticeSnippets/AppDataSecurity/README_EN.md This code snippet shows how to download the HarmonyOS Application Data Security sample project using Git. It initializes a sparse checkout to download only the relevant directory. ```bash git init git config core.sparsecheckout true echo AppDataSecurity/ > .git/info/sparse-checkout git remote add origin https://gitee.com/harmonyos_samples/BestPracticeSnippets.git git pull origin master ``` -------------------------------- ### Download Project via Git Sparse Checkout Source: https://github.com/linganmin/harmonyos_samples/blob/main/BestPracticeSnippets/VideoPlayerSample/README_EN.md This snippet provides the Git commands required to download the Video Player sample project using sparse checkout. This method allows cloning only specific directories of a repository, which is useful for large projects. ```git git init git config core.sparsecheckout true echo VideoPlayerSample/ > .git/info/sparse-checkout git remote add origin https://gitee.com/harmonyos_samples/BestPracticeSnippets.git git pull origin master ``` -------------------------------- ### Util Class for Starting Abilities in HarmonyOS Source: https://github.com/linganmin/harmonyos_samples/blob/main/ability-start-mode/README.en.md Encapsulates methods for starting abilities in multiton, singleton, and specified launch modes. It takes the ability name and context to initiate the desired ability. ```ets import ability from '@ohos.app.ability.UIAbility' import Want from '@ohos.base.Want' let context: UIAbility['context']; function setContext(contextInstance: UIAbility['context']) { context = contextInstance; } function startAbility(abilityName: string, want?: Want) { if (!context) { console.error('Context is not set. Call setContext first.'); return; } const newWant: Want = { bundleName: context.bundleName, abilityName: abilityName, ...want }; context.startAbility(newWant) .then((data) => { console.info('Start ability succeeded. Data: ' + JSON.stringify(data)); }) .catch((error) => { console.error('Start ability failed. Reason: ' + JSON.stringify(error)); }); } ``` -------------------------------- ### Driver Server Initialization (JavaScript) Source: https://github.com/linganmin/harmonyos_samples/blob/main/guide-snippets/DriverDevelopmentKit/UsbDriverDemo/README_zh.md This code illustrates the server-side logic for a driver extension ability. It shows how to initialize the USB DDK and handle device connections within the `onInit` and `onConnect` methods of `DriverExtensionAbility`. ```javascript import hilog from '@ohos.hilog'; import DriverExtensionAbility from '@ohos.app.ability.DriverExtensionAbility'; // Assuming USB DDK C API is accessible via Napi export default class MyDriverExtensionAbility extends DriverExtensionAbility { onInit() { hilog.info(0x0001, 'MyDriver', 'DriverExtensionAbility onInit'); // Initialize USB DDK using Napi interface to C API // Example: usbDdkInit(); } onConnect(want) { hilog.info(0x0001, 'MyDriver', 'DriverExtensionAbility onConnect'); // Return the server instance return this.driverService; } // ... other methods for communication and device interaction } ``` -------------------------------- ### Install StateStore Dependency with ohpm Source: https://github.com/linganmin/harmonyos_samples/blob/main/StateStore/README.md This command installs the StateStore library using the ohpm package manager. It's a prerequisite for using StateStore in your HarmonyOS project. Ensure ohpm is configured correctly in your development environment. ```shell ohpm install @hadss/state_store ``` -------------------------------- ### Download HarmonyOS AppPrivacyProtection Sample Project Source: https://github.com/linganmin/harmonyos_samples/blob/main/BestPracticeSnippets/CustomDialogPractice/README_EN.md This command-line snippet initializes a Git repository, configures sparse checkout to isolate the AppPrivacyProtection directory, sets the remote origin, and pulls the master branch. It is used to download a specific project from a remote repository. ```bash git init git config core.sparsecheckout true echo AppPrivacyProtection/ > .git/info/sparse-checkout git remote add origin https://gitee.com/harmonyos_samples/BestPracticeSnippets.git git pull origin master ``` -------------------------------- ### Maven Dependencies for In-App Payment Server API Examples (Java) Source: https://github.com/linganmin/harmonyos_samples/blob/main/iapkit-sample-serverdemo/README_cn.md This snippet lists the Maven dependencies required for the In-App Payment Server API examples. It includes libraries for JWT generation (java-jwt), utility functions (commons-codec), and JSON data binding (jackson-databind). ```xml com.auth0 java-jwt 4.4.0 commons-codec commons-codec 1.9 com.fasterxml.jackson.core jackson-databind 2.13.4.2 compile ``` -------------------------------- ### Entry Point Ability - ETS Source: https://github.com/linganmin/harmonyos_samples/blob/main/audio-native/README.en.md This ETS file defines the entry ability for the HarmonyOS application. It manages the application's lifecycle and handles initial setup, including UI navigation. ```typescript /* * Copyright (c) 2023 Huawei Device Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIAbility from '@ohos.app.ability.UIAbility'; import Window from '@ohos.window'; import Logger from '../utils/Logger'; const TAG: string = 'EntryAbility'; export default class EntryAbility extends UIAbility { onCreate(want, launchReason) { Logger.info(TAG, `[EntryAbility] onCreate called. want: ${JSON.stringify(want)}, launchReason: ${launchReason}`); globalThis.abilityContext = this.context; let router = globalThis.router; if (router) { router.replace({ uri: 'pages/Index' }); } Logger.info(TAG, '[EntryAbility] onCreate finished.'); } onDestroy() { Logger.info(TAG, '[EntryAbility] onDestroy called.'); } onWindowStageCreate(windowStage: Window.WindowStage) { Logger.info(TAG, '[EntryAbility] onWindowStageCreate called.'); // Main window is created; this is where you initialize your UI. Attach an existing page or create a new one. windowStage.loadContent('pages/Index', (err, data) => { if (err) { Logger.error(TAG, `[EntryAbility] Failed to load the content. Code: ${err.code}, Message: ${err.message}`); return; } Logger.info(TAG, '[EntryAbility] Page loaded successfully. Data: ' + JSON.stringify(data)); }); Logger.info(TAG, '[EntryAbility] onWindowStageCreate finished.'); } onWindowStageDestroy() { Logger.info(TAG, '[EntryAbility] onWindowStageDestroy called.'); } onForeground() { // The scene has moved to the foreground. Respond to contextual changes. Logger.info(TAG, '[EntryAbility] onForeground called.'); } onBackground() { // The scene has moved to the background. Stop background activity, or save state before going to the background. Logger.info(TAG, '[EntryAbility] onBackground called.'); } } ``` -------------------------------- ### CMake Project Setup and Definitions Source: https://github.com/linganmin/harmonyos_samples/blob/main/xengine-samplecode-vulkan-temporal-upscale-demo-cpp/entry/src/main/cpp/CMakeLists.txt Initializes the CMake version, project name, and defines preprocessor macros required for the native build. These definitions often enable platform-specific features or disable certain functionalities. ```cmake cmake_minimum_required(VERSION 3.4.1) project(XComponent) set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) ADD_DEFINITIONS(-DVK_USE_PLATFORM_OHOS=1) ADD_DEFINITIONS(-DVK_NO_PROTOTYPES=1) add_definitions(-DOHOS_PLATFORM) add_definitions(-DSTB_IMAGE_IMPLEMENTATION) include_directories( ${NATIVERENDER_ROOT_PATH} ${NATIVERENDER_ROOT_PATH}/include ) ```