### HarmonyOS App Development: Starting Ability to Open Files
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-ability-54
Calls the startAbility interface with the constructed Want object to initiate the process of opening a file using another installed application. Includes basic promise handling for success and errors.
```ets
// Call the startAbility interface to open files
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
context.startAbility(wantInfo).then(() => {
// ...
}).catch((err: BusinessError) => {
// ...
})
```
--------------------------------
### Get Component Render Time using ArkUI Inspector in HarmonyOS
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkui-302
This code snippet demonstrates how to get the component rendering completion time in HarmonyOS. It utilizes the @kit.ArkUI.inspector interface to create a ComponentObserver, registers a listener for the 'draw' event, and calculates the time difference between the start of rendering (in aboutToAppear) and the completion of drawing (in the listener callback).
```ets
import { inspector } from '@kit.ArkUI';
@Entry
@Component
struct GetComponentRenderTime {
@State startTime: number = 0;
private listener: inspector.ComponentObserver = this.getUIContext().getUIInspector().createComponentObserver('IMAGE_ID');
// Calculate rendering duration: currentTime - this.startTime
private onDrawCompleteCallback = () => {
// 2. Time when the image component finishes drawing
console.info('onDrawComplete', new Date().getTime());
};
aboutToAppear() {
// 1. Time when rendering starts
this.startTime = new Date().getTime();
console.info('aboutToAppear', this.startTime);
// layout: Component layout completed
// draw: Component drawing completed
this.listener.on('draw', this.onDrawCompleteCallback);
}
aboutToDisappear() {
// Unregister callback before destruction
this.listener.off('draw', this.onDrawCompleteCallback);
}
build() {
Column() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
Row({ space: 5 }) {
Image($r('app.media.app_icon'))
.width(110)
.height(110)
.id('IMAGE_ID')
}
}
}
.height(320)
.width(360)
.padding({
right: 10,
top: 10
})
}
}
```
--------------------------------
### Example: Managing Multiple Custom Keyboards for TextInputs (ArkUI)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkui-331
This comprehensive ArkUI example illustrates how to manage and bind different custom keyboards to multiple TextInput components within a single application. It defines separate controllers and builder methods for each keyboard, ensuring distinct input behaviors.
```typescript
@Entry
@Component
struct TextInputExample {
controller: TextInputController = new TextInputController();
@State inputValue: string = '';
controller1: TextInputController = new TextInputController();
@State inputValue1: string = '';
controller2: TextInputController = new TextInputController();
@State inputValue2: string = '';
build() {
Column() {
this.input({ inputValue: this.inputValue, controller: this.controller, index: 0 });
this.input({ inputValue: this.inputValue1, controller: this.controller1, index: 1 });
this.input({ inputValue: this.inputValue2, controller: this.controller2, index: 2 });
}
}
@Builder
input(tmp: Tmp) {
if (tmp.index === 0) {
TextInput({ controller: tmp.controller, text: tmp.inputValue })
.customKeyboard(this.keyboard())
.margin(10)
.border({ width: 1 })
.height('48vp')
} else if (tmp.index === 1) {
TextInput({ controller: tmp.controller, text: tmp.inputValue })
.customKeyboard(this.keyboard1())
.margin(10)
.border({ width: 1 })
.height('48vp')
} else {
TextInput({ controller: tmp.controller, text: tmp.inputValue })
.customKeyboard(this.keyboard2())
.margin(10)
.border({ width: 1 })
.height('48vp')
}
}
@Builder
keyboard() {
CustomKeyboardBuilder({ inputValue: this.inputValue, controller: this.controller, index: 0 });
}
@Builder
keyboard1() {
CustomKeyboardBuilder({ inputValue: this.inputValue1, controller: this.controller1, index: 1 });
}
@Builder
keyboard2() {
CustomKeyboardBuilder({ inputValue: this.inputValue2, controller: this.controller2, index: 2 });
}
}
class Tmp {
inputValue?: string;
controller?: TextInputController;
index?: number;
}
// Customize keyboard components
@Component
export struct CustomKeyboardBuilder {
controller?: TextInputController = new TextInputController();
index: number = 0;
@Link inputValue: string;
build() {
Column() {
Button('x').onClick(() => {
// Turn off custom keyboard
this.controller?.stopEditing();
})
Grid() {
ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
GridItem() {
Button(item + '')
.backgroundColor(this.index === 0 ? Color.Blue :
(this.index === 1 ? Color.Green : Color.Red))
.width(110)
.onClick(() => {
this.inputValue += item;
})
}
})
}
.maxCount(3)
.columnsGap(10)
.rowsGap(10)
.padding(5)
}
.backgroundColor(Color.Gray)
}
}
```
--------------------------------
### Correcting setup-regression.py Syntax for HarmonyOS Regression Packages
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-regression-test-3
This snippet demonstrates the correct way to write the 'setup-regression.py' file to avoid parsing errors. Ensure that comments are removed and parameters are set in the 'parameter_name=parameter_value' format. This file is crucial for packaging test cases for HarmonyOS applications.
```python
from setuptools import setup
setup(
name='hypiumTest',
version='1.0.0.0',
author='xxx',
py_modules=['testcases.Example'],
include_package_data=True
)
```
--------------------------------
### Open System Application Page from H5 using Anchor Tag and startAbility (ArkTS)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkweb-41
This ArkTS code snippet shows how to launch a system application (like Settings) from an H5 page embedded in a Web component. It defines a `startSettingsInfo` function that uses `startAbility` with a `Want` object containing the target application's bundle name, ability name, and URI. The `onLoadIntercept` method detects a specific URL scheme (e.g., `hmos://`) and calls this function to initiate the system app launch.
```ArkTS
import { webview } from '@kit.ArkWeb'
import { common } from '@kit.AbilityKit';
import { Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
function startSettingsInfo(context: common.UIAbilityContext,uri : string): void {
let want: Want = {
bundleName: 'com.huawei.hmos.settings',
abilityName: 'com.huawei.hmos.settings.MainAbility',
uri: uri
};
context.startAbility(want)
.then(() => {
// ...
})
.catch((err: BusinessError) => {
console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
});
}
@Entry
@Component
struct WebComponent {
context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext;
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Column() {
Web({ src: $rawfile('hello.html'), controller: this.controller })
.onLoadIntercept((event) => {
if(event){
let url = event.data.getRequestUrl();
console.log(url);
if(url.indexOf('hmos://') === 0){
startSettingsInfo(this.context,url.substring(7))
return true;
}
}
return false;
})
.width('100%')
.height('100%')
}
.layoutWeight(1)
}
}
}
```
--------------------------------
### Get Original Object Before Proxy in ArkTS
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkui-367
This ArkTS code snippet demonstrates how to use the `UIUtils.getTarget()` method to retrieve the original object before it's proxied by the state management framework. The example shows how changes to the original object might not update the UI, unlike changes to the proxied object.
```ArkTS
import { UIUtils } from '@kit.ArkUI';
@Observed
class UserInfo {
name: string = 'Tom';
}
@Entry
@Component
struct GetTargetDemo {
@State info: UserInfo = new UserInfo();
build() {
Column() {
Text(`info.name: ${this.info.name}`)
Button('Change the properties of the proxy object')
.onClick(() => {
this.info.name = 'Alice'; // The Text component can refresh
})
Button('更改原始对象的属性')
.onClick(() => {
let rawInfo: UserInfo = UIUtils.getTarget(this.info);
if (rawInfo) {
rawInfo.name = 'Bob'; // The Text component cannot be refreshed
}
})
}
}
}
```
--------------------------------
### 目标详情页 (HTML)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkweb-39
这是`index.html`跳转的目标页面。它展示了一个简单的HTML结构,并包含一些文本内容,模拟一个详情页面。
```html
详情页
欢迎来到详情页!
您已成功从首页跳转到此页,并在URL中添加了参数。
```
--------------------------------
### Get Application Cache Directory in HarmonyOS (ETS)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-ability-14
This snippet demonstrates how to retrieve the application's cache directory using the `Context.cacheDir` property in an ETS (ArkTS) component. It utilizes `common.UIAbilityContext` to access the application context and its cache directory. The example includes a button to trigger the retrieval and display the cache path.
```ets
import { common } from '@kit.AbilityKit';
@Entry
@Component
export struct GetCacheDirectoryView {
private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
@State cachePath: string = '';
build() {
Column() {
Text(this.cachePath)
.margin({ bottom: 24 })
Button() {
Text('Get the application cache directory address')
}
.onClick(() => {
const applicationContext = this.context.getApplicationContext();
// Get the application file path
const cacheDir = applicationContext.cacheDir;
this.cachePath = cacheDir + '/test.txt';
})
.width(300)
.height(50)
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
}
}
```
--------------------------------
### Get Parameters from router.back in HarmonyOS (TypeScript)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkui-164
This snippet demonstrates how to retrieve parameters passed to a page using router.back in HarmonyOS. It utilizes the Router module's getParams method within the onPageShow callback to access the parameter object. The example shows how to extract specific properties like 'id' and nested properties like 'age' from the received parameters.
```typescript
class InfoTmp {
age: number = 0
}
class RouTmp {
id: object = () => {
}
info: InfoTmp = new InfoTmp()
}
const context = AppStorage.get("context") as UIContext;
const params: RouTmp = context.getRouter().getParams() as RouTmp; // Get the parameter object passed
const id: object = params.id // Get the value of the id property
const age: number = params.info.age // Get the value of the age property
```
--------------------------------
### Basic C++ File Writing Example
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-ndk-11
A fundamental C++ function to write content to a specified file path. This example uses standard C file I/O (`fopen`, `fprintf`, `fclose`) and is provided as a basic illustration of file writing in a native context. It does not include HarmonyOS specific sandboxing.
```cpp
#include
void writeTempFile(const char* path, const char* content) {
FILE* file = fopen(path, "w");
if (file != NULL) {
fprintf(file, "%s", content);
fclose(file);
}
}
```
--------------------------------
### 本地HTML文件实现页面跳转 (HTML)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkweb-39
这是一个简单的HTML文件,用于演示如何使用`window.location.href`在Web组件内进行页面跳转,并模拟添加查询参数。当页面加载完成时,它会自动跳转到`details.html`。
```html
```
--------------------------------
### Define a Class with Methods in ArkTS
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkts-115
This snippet demonstrates how to define a class named `testClass` in ArkTS, including public methods like `test`, `toString`, and `FunToString`. This class serves as an example for retrieving its methods.
```typescript
export class testClass {
public test(): string {
return "ArkUI Web Component";
}
public toString(): void {
console.log('Web Component toString');
}
public FunToString(): void {
console.log('Web Component toString');
}
}
```
--------------------------------
### Install 'dayjs' via ohpm Command Line
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-command-line-tool-13
This method involves navigating to the 'entry' directory in the terminal and using the 'ohpm install dayjs' command to add the 'dayjs' library. The library can then be imported directly into JS files.
```bash
cd entry
ohpm install dayjs
import dayjs from 'dayjs';
```
--------------------------------
### Access BuildProfile Values in Index.ets - HarmonyOS
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-compiling-and-building-72
This code example shows how to access specific build-related properties like HAR_VERSION, BUILD_MODE_NAME, and DEBUG from the imported BuildProfile class in an Index.ets file. These values are typically defined in the module.json5 file.
```typescript
const HAR_VERSION: string = BuildProfile.HAR_VERSION;
const BUILD_MODE_NAME: string = BuildProfile.BUILD_MODE_NAME;
const DEBUG: boolean = BuildProfile.DEBUG;
```
--------------------------------
### Navigate to DevEco Studio Options Directory
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-app-test-11
This command navigates the terminal to the specific directory where DevEco Studio's configuration options are stored. This is a prerequisite for modifying the `other.xml` file.
```bash
cd ~/Library/Application\ Support/Huawei/DevEcoStudio6.0/options
```
--------------------------------
### Configure ohpm Environment Variables on Linux/macOS
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-development-environment-9
This section explains how to add the ohpm bin directory to the PATH environment variable in Linux and macOS systems, specifically using Zsh as an example. This allows the command line to execute ohpm commands. Ensure Node.js 18.x or later is installed and its environment variables are configured.
```shell
1. Open the terminal and edit the ~/.zshrc file: vi ~/.zshrc
2. Add the following line to the end of the file, replacing '/home/tctAdmin/ohpm/bin' with the actual path to your ohpm bin directory:
export PATH="/home/tctAdmin/ohpm/bin:$PATH"
3. Save and exit the editor.
4. Apply the changes by running: source ~/.zshrc
5. Verify the installation by running: ohpm -v
```
--------------------------------
### Example: Sending a Specific File with hdc
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-performance-analysis-kit-17
This example shows a practical application of the hdc file send command. It illustrates how to send a file named 'example.txt' from the local 'E:\' directory to the '/data/local/tmp/' directory on the remote device.
```bash
hdc file send E:\example.txt /data/local/tmp/example.txt
```
--------------------------------
### Count Method Execution Time with AOP in ArkTS
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkts-99
This ArkTS code snippet demonstrates how to use the `util.Aspect.addBefore` and `util.Aspect.addAfter` methods to record the start and end times of a method's execution. It utilizes `systemDateTime.getTime(true)` to get timestamps in nanoseconds. The recorded times are then logged to the console when a button is clicked.
```typescript
1. import { util } from '@kit.ArkTS';
2. import { systemDateTime } from '@kit.BasicServicesKit';
3.
4. class Utils {
5. Add(len: number): number {
6. let num = 0;
7. for (let index = 1; index <= len; index++) {
8. num += index;
9. }
10. return num;
11. }
12. }
13.
14. let startTime = 0; // Initialization start time
15. let endTime = 0; // Initialization end time
16.
17. util.Aspect.addBefore(Utils, 'Add', false, () => {
18. startTime = systemDateTime.getTime(true); // Return the start time in nanoseconds
19. })
20.
21. util.Aspect.addAfter(Utils, 'Add', false, () => {
22. endTime = systemDateTime.getTime(true); // Return the end time in nanoseconds
23. })
24.
25. let utilsObj = new Utils();
26. utilsObj.Add(1000);
27.
28. @Entry
29. @Component
30. struct Index {
31. build() {
32. Row() {
33. Column() {
34. Button('get execution time')
35. .onClick(() => {
36. console.log('startTime:', startTime);
37. console.log('endTime:', endTime);
38. console.log('endTime - startTime = ', endTime - startTime);
39. })
40. }
41. .width('100%')
42. }.height('100%')
43. }
44. }
```
--------------------------------
### HarmonyOS: Check Installed App Debug Info
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-compiling-and-building-103
This command is used to inspect the debug information of an installed HarmonyOS application. It helps in diagnosing issues related to debug flags that might cause installation conflicts.
```bash
bm dump -n 应用bundleName | grep debug
```
--------------------------------
### Create and Manage Temporary Files in HarmonyOS (ArkTS)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-local-file-manager-47
This ArkTS code snippet demonstrates how to create, write to, and read from temporary files using the `@kit.CoreFileKit` and `@kit.ArkTS` modules. It shows how to obtain the temporary directory, open files in read-write mode, write data, and read data back into an ArrayBuffer, converting it to a string. Error handling and file closing are implicitly managed within the provided functions.
```ArkTS
import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { buffer } from '@kit.ArkTS';
@Entry
@Component
struct CreateFileDemo {
@State message: string = 'Hello World';
@State writeStr: string = 'write content';
@State readStr: string = 'read content';
build() {
Column() {
Text(this.message)
Button(this.writeStr)
.margin({ top: 15, bottom: 15 })
.onClick(() => {
let context = this.getUIContext().getHostContext();
let filesDir = context!.tempDir;
let file = fs.openSync(filesDir + 'test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// Write a paragraph of content to a file
fs.writeSync(file.fd, 'Try to write str.');
console.info('str has been written');
// close file
fs.closeSync(file);
})
Button(this.readStr)
.onClick(() => {
let context = this.getUIContext().getHostContext();
let filesDir = context!.tempDir;
let file = fs.openSync(filesDir + 'test.txt', fs.OpenMode.READ_WRITE);
// Read a section of content from a file
let arrayBuffer = new ArrayBuffer(1024);
let readOptions: ReadOptions = {
offset: 0,
length: arrayBuffer.byteLength
};
let readLen = fs.readSync(file.fd, arrayBuffer, readOptions);
let buf = buffer.from(arrayBuffer, 0, readLen);
this.message = buf.toString();
// close file
fs.closeSync(file);
})
}
.height('100%')
.width('100%')
}
}
```
--------------------------------
### HarmonyOS: Error Log for Installation Failure
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-compiling-and-building-103
This log snippet details the error encountered during the installation of a HarmonyOS application. It indicates a failure to install the bundle with a specific error code and message related to version code mismatch.
```text
1. 04/10 14:01:54: Install Failed: error: failed to install bundle.
2. code:9568278
3. error: install version code not same.
4. $ hdc shell rm -rf data/local/tmp/f47e1222b8c64dbe92f86bc3b55cc3d2
5. Error while Deploy Hap
```
--------------------------------
### ArkTS: Instantiating a Class using `new` Keyword
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkts-148
This ArkTS code example demonstrates the recommended way to instantiate a class using the `new` keyword. This approach ensures that the created object is a proper instance of the class and avoids the compilation and runtime issues associated with object literal initialization, especially when dealing with SDK updates.
```typescript
1. // SDK
2. declare class Base2 {
3. // since 9
4. getPropA(): number;
5. // since 12 new method
6. getPropB(): number;
7. }
8.
9. // Initialize an instance of a class using the new method.
10. let b2: Base2 = new Base2();
11. // Upgrading to API 12 SDK will not result in errors.
```
--------------------------------
### Customize Video Component Control Bar Styles (ArkTS)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkui-97
This ArkTS code demonstrates how to customize the control bar of a Video component. It shows how to disable default controls, use a VideoController to manage playback (start, pause, stop, set time), and adjust playback speed. It also includes examples of switching video sources and preview URIs.
```arkts
1. @Entry
2. @Component
3. struct VideoCreateComponent {
4. @State videoSrc: Resource = $rawfile('xxx.mp4')
5. @State previewUri: Resource = $r('app.media.xxx')
6. @State curRate: PlaybackSpeed = PlaybackSpeed.Speed_Forward_1_00_X
7. @State isAutoPlay: boolean = false
8. @State showControls: boolean = true
9. controller: VideoController = new VideoController()
10.
11. build() {
12. Column() {
13. Video({
14. src: this.videoSrc,
15. previewUri: this.previewUri,
16. currentProgressRate: this.curRate,
17. controller: this.controller
18. })
19. .width('100%')
20. .height(600)
21. .autoPlay(this.isAutoPlay)
22. .controls(this.showControls)
23. .onStart(() => {
24. console.info('onStart')
25. })
26. .onPause(() => {
27. console.info('onPause')
28. })
29. .onFinish(() => {
30. console.info('onFinish')
31. })
32. .onError(() => {
33. console.info('onError')
34. })
35. .onPrepared((e) => {
36. console.info('onPrepared is ' + e.duration)
37. })
38. .onSeeking((e) => {
39. console.info('onSeeking is ' + e.time)
40. })
41. .onSeeked((e) => {
42. console.info('onSeeked is ' + e.time)
43. })
44. .onUpdate((e) => {
45. console.info('onUpdate is ' + e.time)
46. })
47. Row() {
48. Button('src').onClick(() => {
49. this.videoSrc = $rawfile('xxx.mp4') // Switch video source
50. }).margin(5)
51. Button('previewUri').onClick(() => {
52. this.previewUri = $r('app.media.xxx') // Switch video preview poster
53. }).margin(5)
54.
55. Button('controls').onClick(() => {
56. this.showControls = !this.showControls // Switch whether to display the video control bar
57. }).margin(5)
58. }
59.
60. Row() {
61. Button('start').onClick(() => {
62. this.controller.start() // 开始播放
63. }).margin(5)
64. Button('pause').onClick(() => {
65. this.controller.pause() // 暂停播放
66. }).margin(5)
67. Button('stop').onClick(() => {
68. this.controller.stop() // 结束播放
69. }).margin(5)
70. Button('setTime').onClick(() => {
71. this.controller.setCurrentTime(10, SeekMode.Accurate) // Accurately jump to the 10s position of the video
72. }).margin(5)
73. }
74.
75. Row() {
76. Button('rate 0.75').onClick(() => {
77. this.curRate = PlaybackSpeed.Speed_Forward_0_75_X // 0.75 times playback speed
78. }).margin(5)
79. Button('rate 1').onClick(() => {
80. this.curRate = PlaybackSpeed.Speed_Forward_1_00_X // Original speed playback
81. }).margin(5)
82. Button('rate 2').onClick(() => {
83. this.curRate = PlaybackSpeed.Speed_Forward_2_00_X // Play at 2x speed
84. }).margin(5)
85. }
86. }
87. }
88. }
```
--------------------------------
### Open System Application from HTML
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-arkweb-41
This HTML snippet demonstrates how to create a link that, when clicked, navigates the user to a specific system application setting, in this case, sound and vibration settings. It utilizes a custom URI scheme 'hmos://' to achieve this.
```html
Document
```
--------------------------------
### Add Log Dependency in CMakeLists.txt
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-ndk-10
This CMakeLists.txt file shows how to link the necessary NAPI and logging libraries for your native module. It includes `libace_napi.z.so` for NAPI functionalities and `libhilog_ndk.z.so` for logging purposes, ensuring your native code can interact with the system and log messages.
```cmake
1. # Screenbrightness/src/main/cpp/CMakeLists.txt
2. target_link_libraries(screenbrightness PUBLIC libace_napi.z.so libhilog_ndk.z.so)
```
--------------------------------
### Get Device UDID using hdc Command
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-performance-analysis-kit-59
This snippet demonstrates how to use the 'hdc shell bm get' command to retrieve the UDID of a connected device. This is a fundamental step for device identification in HarmonyOS development.
```bash
hdc shell bm get -u
hdc shell bm get --udid
```
--------------------------------
### Copy Local Database to Sandbox (TypeScript)
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-local-database-management-12
This snippet demonstrates how to copy a local database file (e.g., 'Objective.db') from the rawfile directory to the application's database sandbox path. It utilizes CoreFileKit for file operations and ArkData for database access. The code first creates necessary directories within the sandbox and then reads the raw file content to write it into the sandbox's db file.
```typescript
import { fileIo } from '@kit.CoreFileKit';
import { relationalStore } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
// Obtaining the Context in EntryAbility, save it to AppStorage, then use AppStorage to retrieve it in the utility class.
let context = AppStorage.get('context') as UIContext;
let UiAbilityContent = context.getHostContext() as common.UIAbilityContext;
let RDBDirectory = UiAbilityContent.databaseDir;
let resource = UiAbilityContent.resourceManager;
function initDatabase() {
// Create a database sandbox directory
try {
let dirPath = RDBDirectory + '/entry';
fileIo.mkdirSync(dirPath);
dirPath = dirPath + '/rdb';
fileIo.mkdirSync(dirPath);
} catch (error) {
console.error(`mkdir rdbPath failed, error code: ${error.code}, message: ${error.message}.`);
}
// Set db name
let dbName: string = 'Objective.db';
// Read the db file in the rawfile directory
try {
let content = resource.getRawFileContentSync(dbName);
let cFile = RDBDirectory + '/entry/rdb/' + dbName;
let cacheFile = fileIo.openSync(cFile, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
fileIo.write(cacheFile.fd, content.buffer);
fileIo.closeSync(cacheFile.fd);
} catch (error) {
console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}
}
```
--------------------------------
### Check App Installation Status in HarmonyOS using ETs
Source: https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs/faqs-package-structure-62
This ETs code snippet demonstrates how Application A checks if Application B is installed on the device. It utilizes the `bundleManager.canOpenLink` function to perform the check and logs the result. Error handling is included for robustness.
```ets
import { hilog } from '@kit.PerformanceAnalysisKit';
import { bundleManager } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
// Application A determines whether Application B is installed on the device
isAppBExist() {
let exist = false;
try {
let link = 'schB://com.example.test/open';
let data: boolean = bundleManager.canOpenLink(link);
hilog.info(0x0000, 'testTag', 'canOpenLink successfully: %{public}s', JSON.stringify(data));
exist = data;
} catch (err) {
let message = (err as BusinessError).message;
hilog.error(0x0000, 'testTag', 'canOpenLink failed: %{public}s', message);
exist = false;
}
console.info('Has application B been installed:' + exist);
}
@State text: string = 'isAppBExist'
build() {
Row() {
Column() {
Text(this.text)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.isAppBExist();
});
}
.width('100%')
}
.height('100%')
}
}
```