### Environment Setup Example
Source: https://github.com/openharmony/docs/blob/master/en/contribute/template/tools-template.md
Example of environment setup instructions for a debugging tool, mentioning prerequisites like hdc.
```text
Before using this tool, you must obtain [hdc](../../application-dev/dfx/hdc.md) and run the **hdc shell** command.
```
--------------------------------
### Enable Cold Start and Start Application
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-boot-appspawn.md
This example demonstrates how to enable the cold start function for applications using the 'param' command and then start an application using the 'aa start' command with specific parameters.
```bash
param set startup.appspawn.cold.boot 1 // Enable the cold start function.
aa start -d 12345 -a $name -b $package -C
Reference command:
aa start -d 12345 -a ohos.acts.startup.sysparam.function.MainAbility -b ohos.acts.startup.sysparam.function -C
```
--------------------------------
### Example: Snapshot Mode Start
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/dfx/hitrace.md
This example shows the output upon successfully starting binary trace data capture in snapshot mode.
```shell
$ hitrace --start_bgsrv
2025/06/04 16:44:54 hitrace enter, running_state is SNAPSHOT_START
2025/06/04 16:44:54 OpenSnapshot done.
```
--------------------------------
### Install xDevice Basic Framework
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/device-test/xdevice.md
Install the core xDevice framework using the setup script. This command should be run from the root directory of xDevice.
```bash
python setup.py install
```
--------------------------------
### Start A/B Update Package Installation
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ota-guide.md
Starts the installation of an A/B update package from a specified file path. Ensure the path is correct and the package is valid.
```cpp
int StartUpdatePackageZip(string path)
```
--------------------------------
### Kernel Initialization Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/porting/porting-w800-combo-demo.md
Demonstrates the basic steps for kernel initialization, including creating and starting the init thread.
```c
osStatus_t ret = osKernelInitialize(); --- Kernel initialization.
if(ret == osOK)
{
threadId = osThreadNew((osThreadFunc_t)sys_init,NULL,&g_main_task); --- Create the init thread.
if(threadId!=NULL)
{
osKernelStart(); --- Thread scheduling.
}
}
```
--------------------------------
### Kernel Startup Sequence Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/porting/porting-cst85f01-combo-demo.md
Illustrates the kernel startup sequence, including initialization of LOS kernel, HDF, and system initialization before starting the scheduler.
```c
LOS_KernelInit();
DeviceManagerStart();
OHOS_SystemInit();
LOS_Start();
....
```
--------------------------------
### Installed Libraries Check
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/device-test/xdevice.md
Example output from 'python -m pip list' showing successful installation of 'xdevice' and 'xdevice-ohos'.
```text
xdevice 0.0.0
xdevice-ohos 0.0.0
```
--------------------------------
### Init Process Configuration Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-build-product.md
Defines the jobs and services for the init process, including commands for creating directories, changing permissions, and starting services.
```json
{
"jobs" : [{"name" : "pre-init",
"cmds" : [
"mkdir /storage/data",
"chmod 0755 /storage/data",
"mkdir /storage/data/log",
"chmod 0755 /storage/data/log",
"chown 4 4 /storage/data/log",
"mount vfat /dev/mmcblock0 /sdcard rw,umask=000"
]
}, {
"name" : "init",
"cmds" : [
"start shell",
"start service1"
]
}, {
"name" : "post-init",
"cmds" : []
}
],
"services" : [{
"name" : "shell",
"path" : ["/sbin/getty", "-n", "-l", "/bin/sh", "-L", "115200", "ttyS000", "vt100"],
"uid" : 0,
"gid" : 0
}]
}
```
--------------------------------
### Install Repo Tool
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-pkg-sourcecode.md
Installs the repo tool, a Python-based utility for managing multiple Git repositories. This example installs it in ~/bin and installs the 'requests' library.
```bash
mkdir ~/bin
curl https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 -o ~/bin/repo
chmod a+x ~/bin/repo
pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests
```
--------------------------------
### Example ohos_prebuilt_executable for Module Installation
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-build-reference.md
This code snippet demonstrates how to configure install_images and module_install_dir for a prebuilt executable module when generating a chip_prod.img for a specific product.
```shell
ohos_prebuilt_executable("moduleXXX"){
install_images = [ "chip_prod" ]
module_install_dir = "productA/etc/***" # The path must start with productA.
}
```
--------------------------------
### WebDownloadManager Example
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-arkweb/arkts-apis-webview-WebDownloadManager.md
This example demonstrates how to set up a download delegate to handle download events, start a download, and resume a failed download using WebDownloadManager and WebviewController.
```typescript
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate();
download: webview.WebDownloadItem = new webview.WebDownloadItem();
failedData: Uint8Array = new Uint8Array();
build() {
Column() {
Button('setDownloadDelegate')
.onClick(() => {
try {
this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => {
console.info("will start a download.");
// Pass in a download path and start the download.
webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName());
})
this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => {
console.info("download update percent complete: " + webDownloadItem.getPercentComplete());
this.download = webDownloadItem;
})
this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => {
console.error("download failed guid: " + webDownloadItem.getGuid());
// Serialize the failed download to a byte array.
this.failedData = webDownloadItem.serialize();
})
this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => {
console.info("download finish guid: " + webDownloadItem.getGuid());
})
this.controller.setDownloadDelegate(this.delegate);
webview.WebDownloadManager.setDownloadDelegate(this.delegate);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('startDownload')
.onClick(() => {
try {
this.controller.startDownload('https://www.example.com');
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('resumeDownload')
.onClick(() => {
try {
webview.WebDownloadManager.resumeDownload(webview.WebDownloadItem.deserialize(this.failedData));
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('cancel')
.onClick(() => {
try {
this.download.cancel();
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('pause')
.onClick(() => {
try {
this.download.pause();
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('resume')
.onClick(() => {
try {
this.download.resume();
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
--------------------------------
### Start Building Product from Scratch
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-appendix-hi3516-pkg.md
Use this command to build a product from scratch. Ensure all necessary files are prepared beforehand.
```bash
hb build -f
```
--------------------------------
### Image Animator Control Example
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/ui/ui-js-components-image-animator.md
This snippet provides a full example of controlling an image animator, including buttons for start, pause, stop, resume, getting the current state, and toggling reverse playback.
```html
```
--------------------------------
### Get OTA Update Status
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ota-guide.md
Retrieves the current status of the update package installation. Status codes indicate whether the update has started, is in progress, or has been completed.
```cpp
int GetUpdateStatus()
```
--------------------------------
### Detailed init.cfg Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-boot-init-cfg.md
A comprehensive example of an init configuration file demonstrating the use of import, jobs with commands, and services.
```json
{
"import" : [
"/etc/example1.cfg",
"/etc/example2.cfg"
],
"jobs" : [{
"name" : "jobName1",
"cmds" : [
"start serviceName",
"mkdir dir1"
]
}, {
"name" : "jobName2",
"cmds" : [
"chmod 0755 dir1",
"chown root root dir1"
]
}
],
"services" : [{
"name" : "serviceName",
"path" : ["/system/bin/serviceName"]
}
]
}
```
--------------------------------
### Get Photo Index Example
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-media-library-kit/js-apis-photoAccessHelper-sys.md
Demonstrates how to use the getPhotoIndex API to find the index of a specific photo within an album. Requires prior setup of PhotoAccessHelper and fetching album and photo assets.
```typescript
import { dataSharePredicates } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
async function example(phAccessHelper: photoAccessHelper.PhotoAccessHelper) {
try {
console.info('getPhotoIndexDemo');
let predicatesForGetAsset: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
let fetchOp: photoAccessHelper.FetchOptions = {
fetchColumns: [],
predicates: predicatesForGetAsset
};
// Obtain the uri of the album.
let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp);
let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
predicates.orderByAsc(photoAccessHelper.PhotoKeys.DATE_MODIFIED);
let fetchOptions: photoAccessHelper.FetchOptions = {
fetchColumns: [photoAccessHelper.PhotoKeys.DATE_MODIFIED],
predicates: predicates
};
let photoFetchResult: photoAccessHelper.FetchResult = await album.getAssets(fetchOptions);
let expectIndex = 1;
// Obtain the uri of the second file.
let photoAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getObjectByPosition(expectIndex);
phAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions).then((index) => {
console.info(`getPhotoIndex successfully and index is : ${index}`);
}).catch((err: BusinessError) => {
console.error(`getPhotoIndex failed; error: ${err.code}, ${err.message}`);
});
} catch (error) {
console.error(`getPhotoIndex failed; error: ${error.code}, ${error.message}`);
}
}
```
--------------------------------
### Uninstall Plugin Example
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-ability-kit/js-apis-installer-sys.md
Demonstrates how to uninstall a plugin for a given application using the uninstallPlugin API. It includes error handling for both getting the installer and the uninstallation process itself. Ensure you have the necessary permissions (ohos.permission.UNINSTALL_PLUGIN_BUNDLE) and that the application is a system API.
```typescript
import { installer } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let hostBundleName = 'com.example.application';
let pluginBundleName = 'com.ohos.pluginDemo';
let pluginParam : installer.PluginParam = {
userId : 100,
};
try {
installer.getBundleInstaller().then((data: installer.BundleInstaller) => {
data.uninstallPlugin(hostBundleName, pluginBundleName, pluginParam)
.then(() => {
console.info('uninstallPlugin successfully.');
}).catch((error: BusinessError) => {
console.error('uninstallPlugin failed:' + error.message);
});
}).catch((error: BusinessError) => {
console.error('uninstallPlugin failed. Cause: ' + error.message);
});
} catch (error) {
let message = (error as BusinessError).message;
console.error('getBundleInstaller failed. Cause: ' + message);
}
```
--------------------------------
### FAT File System Initialization and Mounting Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/kernel/kernel-mini-extend-file.md
This C code demonstrates the initialization, partitioning, formatting, and mounting of a FAT file system. It includes setting up partition information, calling the necessary LiteOS APIs, and handling potential errors. This example is suitable for QEMU with the LiteOS-M kernel and may require modification for specific hardware.
```c
#include "fatfs_conf.h"
#include "fs_config.h"
#include "los_config.h"
#include "ram_virt_flash.h"
#include "los_fs.h"
struct fs_cfg {
CHAR *mount_point;
struct PartitionCfg partCfg;
};
INT32 FatfsLowLevelInit()
{
INT32 ret;
INT32 i;
UINT32 addr;
int data = FMT_FAT32;
const char * const pathName[FF_VOLUMES] = {FF_VOLUME_STRS};
HalLogicPartition *halPartitionsInfo = getPartitionInfo(); /* Function for obtaining the partition lengths and start addresses. Modify it as required. */
INT32 lengthArray[FF_VOLUMES] = {25, 25, 25, 25};
INT32 addrArray[FF_VOLUMES];
/* Set the address and length for each partition. */
for (i = 0; i < FF_VOLUMES; i++) {
addr = halPartitionsInfo[FLASH_PARTITION_DATA1].partitionStartAddr + i * 0x10000;
addrArray[i] = addr;
FlashInfoInit(i, addr);
}
/* Set partition information. */
SetupDefaultVolToPartTable();
ret = LOS_DiskPartition("spinorblk0", "vfat", lengthArray, addrArray, FF_VOLUMES);
printf("%s: DiskPartition %s\n", __func__, (ret == 0) ? "succeed" : "failed");
if (ret != 0) {
return -1;
}
ret = LOS_PartitionFormat("spinorblk0p0", "vfat", &data);
printf("%s: PartitionFormat %s\n", __func__, (ret == 0) ? "succeed" : "failed");
if (ret != 0) {
return -1;
}
ret = mount("spinorblk0p0", "/system", "vfat", 0, &data);
printf("%s: mount fs on '%s' %s\n", __func__, pathName[0], (ret == 0) ? "succeed" : "failed");
if (ret != 0) {
return -1;
}
return 0;
}
```
--------------------------------
### start_window.json Configuration Example
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/quick-start/module-configuration-file.md
Example of a start_window.json file used to configure the UIAbility startup page. This file specifies various visual elements and their properties for the application's launch screen.
```json
{
"startWindowType": "REQUIRED_SHOW",
"startWindowAppIcon": "$media:start_window_app_icon",
"startWindowIllustration": "$media:start_window_illustration",
"startWindowBrandingImage": "$media:start_window_branding_image",
"startWindowBackgroundColor": "$color:start_window_back_ground_color",
"startWindowBackgroundImage": "$media:start_window_back_ground_image",
"startWindowBackgroundImageFit": "Cover"
}
```
--------------------------------
### Start Drag Operation with Deferred Data Loading
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-arkui/js-apis-arkui-dragController.md
Initiates a drag operation with deferred data loading configured via dataLoadParams. This example demonstrates dragging a video file, requiring setup for file access and resource management.
```TypeScript
import { unifiedDataChannel, uniformTypeDescriptor, uniformDataStruct } from '@kit.ArkData';
import { fileUri, fileIo as fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { dragController } from '@kit.ArkUI';
@Entry
@Component
struct ImageExample {
private dragAction: dragController.DragAction | null = null;
customBuilders: Array = new Array();
@State uri: string = "";
@State blockArr: string[] = [];
uiContext = this.getUIContext();
udKey: string = '';
@Builder
DraggingBuilder() {
Video({ src: $rawfile('test1.mp4'), controller: new VideoController() })
.width(100)
.height(100)
}
build() {
Column() {
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceAround }) {
Button('touch to execute drag')
.margin(10)
.onTouch((event?: TouchEvent) => {
if (event) {
if (event.type == TouchType.Down) {
this.customBuilders.splice(0, this.customBuilders.length);
this.customBuilders.push(() => {
this.DraggingBuilder()
});
const context: Context | undefined = this.uiContext.getHostContext();
if (context) {
let loadHandler: unifiedDataChannel.DataLoadHandler = () => {
let data =
context.resourceManager.getRawFdSync('test1.mp4');
let filePath = context.filesDir + '/test1.mp4';
let file = fileIo.openSync(filePath, fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE);
let bufferSize = data.length as number;
let buf = new ArrayBuffer(bufferSize);
fileIo.readSync(data.fd, buf, { offset: data.offset, length: bufferSize });
fileIo.writeSync(file.fd, buf, { offset: 0, length: bufferSize });
fileIo.closeSync(file.fd);
context.resourceManager.closeRawFdSync('test1.mp4')
```
--------------------------------
### HDI API Invocation Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/driver/driver-peripherals-external-des.md
This C code demonstrates how to use the HDI API to interact with the WLAN driver. It covers obtaining a WLAN service instance, starting and stopping the driver, getting supported features, and releasing the service instance.
```c
#include "v1_0/iwlan_interface.h"
#include "wlan_callback_impl.h"
#include "wlan_impl.h"
#define PROTOCOL_80211_IFTYPE_NUM 11
#define HDF_SUCCESS 0
#define HDF_FAILURE (-1)
static int32_t hdi_main()
{
int32_t rc;
const char *WLAN_SERVICE_NAME = "wlan_hal_c_service";
static struct IWlanInterface *g_wlanObj = NULL;
uint8_t supType[PROTOCOL_80211_IFTYPE_NUM + 1] = {0};
uint32_t supTypeLen = PROTOCOL_80211_IFTYPE_NUM + 1;
/* Obtain the WLAN service instance. */
g_wlanObj = WlanInterfaceGetInstance(WLAN_SERVICE_NAME);
if (g_wlanObj == NULL)
{
return HDF_FAILURE;
}
/* Create a channel between the HAL and the driver and obtain the driver NIC information. */
rc = g_wlanObj->Start(g_wlanObj);
if (rc != HDF_SUCCESS)
{
return HDF_FAILURE;
}
/* Obtain the WLAN features supported by the device irrespective of the device status (AP, STA, or P2P).
rc = g_wlanObj->GetSupportFeature(g_wlanObj, supType, &supTypeLen);
if (rc != HDF_SUCCESS)
{
return HDF_FAILURE;
}
/* Destroy the channel between the HAL and the driver. */
rc = g_wlanObj->Stop(g_wlanObj);
if (rc != HDF_SUCCESS)
{
return HDF_FAILURE;
}
/* Destroy the WLAN service instance. */
rc = WlanInterfaceRelease(g_wlanObj);
if (rc != HDF_SUCCESS)
{
return HDF_FAILURE;
}
return rc;
}
```
--------------------------------
### Example: Software with Dependencies
Source: https://github.com/openharmony/docs/blob/master/en/contribute/readme.opensource_design_specification_document_and_usage_guide.md
Demonstrates how to list direct dependencies for a piece of software in its `README.OpenSource` file.
```json
[
{
"Name": "bindgen",
"License": "BSD-3-Clause",
"License File": "LICENSE",
"Version Number": "0.59.1",
"Owner": "lihua@openharmony.io",
"Upstream URL": "https://github.com/rust-lang/rust-bindgen",
"Description": "A tool for generating Rust FFI bindings to C/C++ libraries.",
"Dependencies": ["shlex", "once_cell"]
}
]
```
--------------------------------
### Install an HSP using bm
Source: https://github.com/openharmony/docs/blob/master/en/contribute/template/tools-template.md
Example of installing an HSP file using the bm install command.
```bash
# Install an HSP.
bm install -s xxx.hsp
```
--------------------------------
### C Code for Setting and Getting System Parameters
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-boot-init-sysparam.md
Demonstrates how to set and get system parameters using SetParameter and GetParameter functions in C. Includes examples for retrieving various device and build information.
```c
// set && get
char key1[] = "rw.sys.version";
char value1[] = "10.1.0";
int ret = SetParameter(key1, value1);
char valueGet1[128] = {0};
ret = GetParameter(key1, "version=10.1.0", valueGet1, 128);
// get sysparm
char* value1 = GetDeviceType();
printf("Product type =%s\n", value1);
char* value2 = GetManufacture();
printf("Manufacture =%s\n", value2);
char* value3 = GetBrand();
printf("GetBrand =%s\n", value3);
char* value4 = GetMarketName();
printf("MarketName =%s\n", value4);
char* value5 = GetProductSeries();
printf("ProductSeries =%s\n", value5);
char* value6 = GetProductModel();
printf("ProductModel =%s\n", value6);
char* value7 = GetSoftwareModel();
printf("SoftwareModel =%s\n", value7);
char* value8 = GetHardwareModel();
printf("HardwareModel =%s\n", value8);
char* value9 = GetHardwareProfile();
printf("Software profile =%s\n", value9);
char* value10 = GetSerial();
printf("Serial =%s\n", value10);
char* value11 = GetOSFullName();
printf("OS name =%s\n", value11);
char* value12 = GetDisplayVersion();
printf("Display version =%s\n", value12);
char* value13 = GetBootloaderVersion();
printf("bootloader version =%s\n", value13);
char* value14 = GetSecurityPatchTag();
printf("secure patch level =%s\n", value14);
char* value15 = GetAbiList();
printf("abi list =%s\n", value15);
int value16 = GetFirstApiVersion();
printf("first api level =%d\n", value16);
char* value17 = GetIncrementalVersion();
printf("Incremental version = %s\n", value17);
char* value18 = GetVersionId();
printf("formal id =%s\n", value18);
char* value19 = GetBuildType();
printf("build type =%s\n", value19);
char* value20 = GetBuildUser();
printf("build user =%s\n", value20);
char* value21 = GetBuildHost();
printf("Build host = %s\n", value21);
char* value22 = GetBuildTime();
printf("build time =%s\n", value22);
char* value23 = GetBuildRootHash();
printf("build root later..., %s\n", value23);
char* value24 = GetOsReleaseType();
printf("OS release type =%s\n", value24);
char* value25 = GetOsReleaseType();
printf("OS release type =%s\n", value25);
char value26[65] = {0};
GetDevUdid(value26, 65);
printf("device udid =%s\n", value26);
char* value27 = GetChipType();
printf("device chiptype =%s\n", value27);
int value28 = GetBootCount();
printf("device boot count =%d\n", value28);
```
--------------------------------
### Install an HAP using bm
Source: https://github.com/openharmony/docs/blob/master/en/contribute/template/tools-template.md
Example of installing a HAP file using the bm install command.
```bash
# Install an HAP.
bm install -p /data/app/ohos.app.hap
```
--------------------------------
### Example: Record Mode Begin
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/dfx/hitrace.md
This example shows the output when record mode is successfully enabled with specified parameters.
```shell
$ hitrace --trace_begin --record -b 204800 --file_size 102400 app graphic
2025/06/04 17:03:37 hitrace enter, running_state is RECORDING_LONG_BEGIN_RECORD
2025/06/04 17:03:37 args: tags:app,graphic bufferSize:204800 overwrite:1 fileSize:102400
2025/06/04 17:03:37 trace capturing.
```
--------------------------------
### Example of Calling INIT_LOGI in SystemPrepare
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-boot-init-log.md
This snippet demonstrates calling INIT_LOGI within the SystemPrepare function to log the start of the init first stage. It's part of the system's startup sequence.
```c
void SystemPrepare(void)
{
MountBasicFs();
CreateDeviceNode();
LogInit();
// Make sure init log always output to /dev/kmsg.
EnableDevKmsg();
INIT_LOGI("Start init first stage.");
// Only ohos normal system support
// two stages of init.
// If we are in updater mode, only one stage of init.
if (InUpdaterMode() == 0) {
StartInitSecondStage();
}
}
```
--------------------------------
### Service Process Configuration Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-boot-init-service.md
Example configuration for enhanced init process startup and recycling, specifying parameters like name, path, priority, CPU binding, suppression, ability privilege level, distributed capabilities, and SELinux tag.
```json
"services" : [{
"name" : "serviceName",
"path" : ["/system/bin/serviceName"]
"importance" : 1, // Priority for service processes
"cpucore" : [0], // CPU binding for service processes
"critical" : [1, 5, 10], // Suppression for service processes
"apl" : "normal", // Ability privilege level for service processes
"d-caps" : ["OHOS_DMS"], // Distributed capabilities for service processes
"secon" : "u:r:distributedsche:s0" // SELinux tag for service processes. In this example, the SELinux tag is u:r:r:s0.
}
```
--------------------------------
### Boot Arguments and Command Configuration
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ota-guide.md
Example configuration for the `config` file, setting `bootargs` and `bootcmd` for the system.
```text
setenv bootargs 'mem=128M console=ttyAMA0,115200 root=/dev/mmcblk0p3 rw rootfstype=ext4 rootwait blkdevparts=mmcblk0:1M
(u-boot.bin),9M(kernel.bin),50M(rootfs_ext4.img),50M(userfs.img)' setenv bootcmd 'mmc read 0x0 0x82000000 0x800 0x4800;bootm 0x82000000'
```
--------------------------------
### Trustlist Configuration for Startup Files
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/arkts-utils/source-obfuscation.md
Example of configuring the trustlist to retain startup task and configuration file paths.
```text
-keep-file-name
# The startup task file paths are ./ets/startup/StartupTask_001.ets and ./ets/startup/StartupTask_002.ets.
startup
StartupTask_001
StartupTask_002
```
--------------------------------
### Install an HAP in overwrite mode using bm
Source: https://github.com/openharmony/docs/blob/master/en/contribute/template/tools-template.md
Example of installing a HAP file in overwrite mode using the bm install command.
```bash
# Install an HAP in overwrite mode.
bm install -p /data/app/ohos.app.hap -r
```
--------------------------------
### Install Docker on Ubuntu
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/get-code/gettools-acquire.md
Installs Docker using the apt package manager. For other operating systems, refer to the official Docker installation guide.
```bash
sudo apt install docker.io
```
--------------------------------
### Standard System: Prebuilt Configuration
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-boot-init-cfg.md
Example of how to define a prebuilt configuration file for the standard system using a build script.
```gn
ohos_prebuilt_etc("misc.cfg") {
source = "//base/startup/init/services/etc/misc.cfg"
relative_install_dir = "init"
part_name = "init"
}
```
--------------------------------
### Install HAP File
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-ability-kit/js-apis-installer-sys.md
Installs a HAP file using the BundleInstaller API. This example demonstrates how to obtain a BundleInstaller instance, specify installation parameters, and handle the installation result or errors.
```typescript
import { installer } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/'];
let installParam: installer.InstallParam = {
userId: 100,
isKeepData: false,
installFlag: 1,
};
try {
installer.getBundleInstaller().then((data: installer.BundleInstaller) => {
data.install(hapFilePaths, installParam, (err: BusinessError) => {
if (err) {
console.error('install failed:' + err.message);
} else {
console.info('install successfully.');
}
});
}).catch((error: BusinessError) => {
console.error('getBundleInstaller failed. Cause: ' + error.message);
});
} catch (error) {
let message = (error as BusinessError).message;
console.error('getBundleInstaller failed. Cause: ' + message);
}
```
--------------------------------
### CMSIS-RTOS v2 Kernel Initialization and Thread Creation
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/kernel/kernel-mini-appx-lib.md
Example demonstrating system initialization, CMSIS-RTOS kernel initialization, creating a new application thread, and starting the kernel. Ensure 'cmsis_os2.h' is included.
```c
#include ...
#include "cmsis_os2.h"
/*----------------------------------------------------------------------------
* Application main thread
*---------------------------------------------------------------------------*/
void app_main (void *argument) {
// ...
for (;;) {}
}
int main (void) {
// System initialization
MySystemInit();
// ...
osKernelInitialize(); // Initialize CMSIS-RTOS.
osThreadNew(app_main, NULL, NULL); // Create the main thread of the application.
osKernelStart(); // Start to execute the thread.
for (;;) {}
}
```
--------------------------------
### OpenHarmony Software Timer Development Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/kernel/kernel-small-basic-softtimer.md
Demonstrates the creation, starting, stopping, and deletion of both one-shot and periodic software timers. Includes callback functions and timer event handling.
```c
#include "los_swtmr.h"
void Timer1_Callback(uint32_t arg);
void Timer2_Callback(uint32_t arg);
UINT32 g_timercount1 = 0;
UINT32 g_timercount2 = 0;
void Timer1_Callback(uint32_t arg) // Callback function 1
{
unsigned long tick_last1;
g_timercount1++;
tick_last1=(UINT32)LOS_TickCountGet(); // Obtain the current number of ticks.
PRINTK("g_timercount1=%d\n",g_timercount1);
PRINTK("tick_last1=%d\n",tick_last1);
}
void Timer2_Callback(uint32_t arg) // Callback function 2
{
unsigned long tick_last2;
tick_last2=(UINT32)LOS_TickCountGet();
g_timercount2 ++;
PRINTK("g_timercount2=%d\n",g_timercount2);
PRINTK("tick_last2=%d\n",tick_last2);
}
void Timer_example(void)
{
UINT16 id1;
UINT16 id2; // timer id
UINT32 uwTick;
/* Create a one-shot software timer, with the number of ticks set to 1000. Callback 1 will be invoked when the number of ticks reaches 1000. */
LOS_SwtmrCreate (1000, LOS_SWTMR_MODE_ONCE, Timer1_Callback, &id1, 1);
/* Create a periodic software timer and invoke callback 2 every 100 ticks. */
LOS_SwtmrCreate(100, LOS_SWTMR_MODE_PERIOD, Timer2_Callback, &id2, 1);
PRINTK("create Timer1 success\n");
LOS_SwtmrStart(id1); // Start the one-shot software timer.
dprintf("start Timer1 success\n");
LOS_TaskDelay(200); // Delay 200 ticks.
LOS_SwtmrTimeGet(id1, &uwTick); // Obtain the number of remaining ticks of the one-short software timer.
PRINTK("uwTick =%d\n", uwTick);
LOS_SwtmrStop(id1); // Stop the software timer.
PRINTK("stop Timer1 success\n");
LOS_SwtmrStart(id1);
LOS_TaskDelay(1000);
LOS_SwtmrDelete(id1); // Delete the software timer.
PRINTK("delete Timer1 success\n");
LOS_SwtmrStart(id2); // Start the periodic software timer.
PRINTK("start Timer2\n");
LOS_TaskDelay(1000);
LOS_SwtmrStop(id2);
LOS_SwtmrDelete(id2);
}
```
--------------------------------
### Install a HAP and its dependent HSP using bm
Source: https://github.com/openharmony/docs/blob/master/en/contribute/template/tools-template.md
Example of installing a HAP file along with its dependent HSP files using the bm install command.
```bash
# Install a HAP and its dependent HSP.
bm install -p aaa.hap -s xxx.hsp yyy.hsp
```
--------------------------------
### Starting an Ability with Want
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-want.md
Example of how to create a Want object and use it to start another ability within a UIAbility.
```APIDOC
## Starting an Ability with Want
### Description
This example demonstrates how to create a Want object with essential parameters like `bundleName`, `abilityName`, and `moduleName`, and then use the `startAbility` method from the ability context to launch another ability.
### Method
`context.startAbility(want, callback)`
### Parameters
#### want (Want)
- **Type**: Want
- **Required**: Yes
- **Description**: The Want object defining the target ability to start.
- **deviceId** (string) - An empty deviceId indicates the local device.
- **bundleName** (string) - The bundle name of the target application.
- **abilityName** (string) - The name of the target ability.
- **moduleName** (string) - Optional. The module name of the target ability.
#### callback (function)
- **Type**: function
- **Required**: Yes
- **Description**: A callback function that handles the result of the `startAbility` operation. It receives an error object if the operation fails.
- **err** (BusinessError) - An object containing error code and message if the ability fails to start.
### Request Example
```typescript
import { UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage): void {
let want: Want = {
deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
moduleName: 'entry' // moduleName is optional.
};
this.context.startAbility(want, (err: BusinessError) => {
if (err.code) {
console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
}
});
}
}
```
```
--------------------------------
### Product ETC Configuration Example
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-power-mode-customization.md
An example of a product ETC configuration file that might include settings related to power modes.
```json
{
"product_etc_conf": [
"//vendor/hihope/rk3568/etc:product_etc_conf"
]
}
```
--------------------------------
### Get Ability State using AbilityDelegator
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-test-kit/js-apis-inner-application-abilityDelegator.md
Obtains the lifecycle state of a UIAbility. This example demonstrates how to get the delegator, retrieve the current top ability, and then get its state.
```javascript
import { abilityDelegatorRegistry } from '@kit.TestKit';
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let abilityDelegator: abilityDelegatorRegistry.AbilityDelegator;
let ability: UIAbility;
abilityDelegator = abilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.getCurrentTopAbility((err: BusinessError, data: UIAbility) => {
console.info('getCurrentTopAbility callback');
ability = data;
let state = abilityDelegator.getAbilityState(ability);
console.info(`getAbilityState ${state}`);
});
```
--------------------------------
### Start Test Framework
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/device-test/developer_test.md
Execute this script to start the test framework. Ensure you are in the correct directory.
```bash
./start.sh
```
--------------------------------
### HSP Startup Configuration Example
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/application-models/app-startup.md
Configuration file for an HSP module (hsp1) defining startup tasks and .so file preloading with dependencies and execution settings.
```json
{
"startupTasks": [
{
"name": "HSP1_Task_01",
"srcEntry": "./ets/startup/HSP1_Task_01.ets",
"dependencies": [
"HSP1_Task_02",
"HAR1_Task_01"
],
"runOnThread": "taskPool",
"waitOnMainThread": false,
"excludeFromAutoStart": true
}
],
"appPreloadHintStartupTasks": [
{
"name": "libhsp1_01",
"srcEntry": "libhsp1_01.so",
"dependencies": [
"libhsp1_02",
"libhar1_01"
],
"runOnThread": "taskPool",
"excludeFromAutoStart": true
}
]
}
```
--------------------------------
### Start System Timer
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-basic-services-kit/js-apis-system-timer-sys.md
Starts a timer with a specified ID, trigger time, and a callback function to handle the result. This example demonstrates creating a timer, then starting it after a delay. Ensure the timer is created before attempting to start it.
```typescript
import { BusinessError } from '@kit.BasicServicesKit';
let options: systemTimer.TimerOptions = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let triggerTime: number = new Date().getTime();
triggerTime += 3000;
try {
systemTimer.createTimer(options).then((timerId: number) => {
systemTimer.startTimer(timerId, triggerTime, (error: BusinessError) => {
if (error) {
console.error(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
return;
}
console.info(`Succeeded in starting the timer.`);
});
console.info(`Succeeded in creating a timer. timerId: ${timerId}`);
}).catch((error: BusinessError) => {
console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
});
} catch(e) {
let error = e as BusinessError;
console.error(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
}
```
--------------------------------
### Initialize System Installation Service
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-ota-guide.md
Initializes the system installation service and sets up an IPC connection. A callback function can be provided for event handling during installation.
```cpp
int SysInstallerInit(void* callback)
```
--------------------------------
### Example: Build a specified product
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-build-all.md
Builds a specified product directly, skipping the configuration step. Use this when the product and company are known.
```shell
hb build -p ipcamera@hisilicon
```
--------------------------------
### Retain Property Names Starting with 'a'
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/arkts-utils/bytecode-obfuscation.md
This example uses the '-keep-property-name' option with a wildcard to retain all property names that start with the letter 'a'.
```txt
-keep-property-name
a*
```
--------------------------------
### Initialize and Start Video Playback
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-multimedia-video-play-guide.md
Create a Player instance, set the playback source using a URI, register a callback, prepare for playback, set the video surface, and start playback.
```cpp
Player *player = new Player();
std::shared_ptr callback = std::make_shared();
player->SetPlayerCallback(callback);// Set a player callback.
std::string uri(filePath);// filePath is a local file path.
Source source(uri);// Create a Source instance and save the URI to the instance.
player->SetSource(source);// Set the Source instance to the player.
player->Prepare(); // Prepare for the playback.
player->SetVideoSurface(surface);// Set the playback surface.
player->Play(); // Start playback.
```
--------------------------------
### Get Allowed Install Bundles Synchronously
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bundleManager.md
Use this API to get a list of applications that can be installed by a specific user. Ensure the 'admin' parameter is correctly configured with the EnterpriseAdminExtensionAbility's details and the correct accountId is provided if targeting a specific user.
```typescript
import { bundleManager } from '@kit.MDMKit';
import { Want } from '@kit.AbilityKit';
let wantTemp: Want = {
// Replace with actual values.
bundleName: 'com.example.myapplication',
abilityName: 'EnterpriseAdminAbility'
};
try {
let result: Array = bundleManager.getAllowedInstallBundlesSync(wantTemp, 100);
console.info(`Succeeded in getting allowed install bundles, result : ${JSON.stringify(result)}`);
} catch (err) {
console.error(`Failed to get allowed install bundles. Code is ${err.code}, message is ${err.message}`);
}
```
--------------------------------
### Widget Configuration File Example
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/form/arkts-ui-widget-configuration.md
A complete example of a widget configuration file, demonstrating various properties like name, description, source path, UI syntax, window settings, rendering mode, update configurations, and dimensions.
```json5
{
"forms": [
{
"name": "widget",
"displayName": "$string:widget_display_name",
"description": "$string:widget_desc",
"src": "./ets/widget/pages/WidgetCard.ets",
"uiSyntax": "arkts",
"window": {
"designWidth": 720,
"autoDesignWidth": true
},
"renderingMode": "fullColor",
"isDefault": true,
"updateEnabled": true,
"scheduledUpdateTime": "10:30",
"updateDuration": 1,
"defaultDimension": "2*2",
"supportDimensions": [
"2*2"
],
"formConfigAbility": "ability://EntryAbility",
"isDynamic": true,
"metadata": []
}
]
}
```
--------------------------------
### Start TextTimer Immediately on Creation
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-texttimer.md
This example shows how to configure a TextTimer to start automatically as soon as it appears on the screen. It uses the `onAppear` event to trigger the `start()` method of the TextTimerController.
```typescript
// xxx.ets
@Entry
@Component
struct TextTimerStart {
textTimerController: TextTimerController = new TextTimerController();
@State format: string = 'mm:ss.SS';
build() {
Column() {
Scroll()
.height('20%')
TextTimer({ isCountDown: true, count: 30000, controller: this.textTimerController })
.format(this.format)
.fontColor(Color.Black)
.fontSize(50)
.onTimer((utc: number, elapsedTime: number) => {
console.info('textTimer notCountDown utc is: ' + utc + ', elapsedTime: ' + elapsedTime);
})
.onAppear(() => {
this.textTimerController.start();
})
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
}
}
```
--------------------------------
### Start Browser and Redirect
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/tools/aa-tool.md
Use the -A and -U flags with the 'aa start' command to launch the browser and navigate to a specific URL. Replace 'https://www.example.com' with your target URL.
```bash
aa start -A ohos.want.action.viewData -U https://www.example.com
```
--------------------------------
### Get Minimum Window Height from Ability Start Options
Source: https://github.com/openharmony/docs/blob/master/en/application-dev/reference/apis-ability-kit/capi-start-options-h.md
Retrieves the minimum window height in vp from the ability start options. Verifies the start options object is valid.
```cpp
#include
void demo()
{
AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions();
if (options == nullptr) {
// Record error logs and other service processing.
return;
}
int32_t minWindowHeight = 0;
AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsMinWindowHeight(options, minWindowHeight);
if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) {
// Record error logs and other service processing.
}
// Destroy options to prevent memory leakage.
OH_AbilityRuntime_DestroyStartOptions(&options);
}
```
--------------------------------
### Example Subsystem Startup Code
Source: https://github.com/openharmony/docs/blob/master/en/device-dev/porting/porting-minichip-subsys-startup.md
This snippet shows a basic structure for subsystem startup. Ensure all necessary headers are included and the function signature matches the system's requirements.
```c
}
```
```