HDC常用功能

SDK 版本:HarmonyOS NEXT Developer Beta2 SDK (5.0.0.31)
DevEco-Studio 版本:DevEco Studio NEXT Developer Beta2 (5.0.3.502)
工程机版本:ALN-AL00 NEXT.0.0.31

0x01 鸿蒙样机升级,查询软件版本和序列号

1
2
3
4
5
6
## 获取 OTA 系统(鸿蒙)软件版本
$ hdc shell param get const.product.software.version

## 获取序列号(SN)
$ hdc list targets

麻烦升级 NEXT.0.0.68 版本
OTA 系统版本号
ALT-AL10 5.0.0.66(SP6C00E66R6P7log)
序列号
22M0224313000155

0x02 鸿蒙手机抓取全量日志保存到本地文件

1
2
3
4
hdc shell hilog -Q domainoff
hdc shell hilog -Q pidoff
hdc shell hilog -b D
hdc hilog >> d://txt.log

鸿蒙-使用系统文件预览不同类型的本地文件

SDK 版本:HarmonyOS NEXT Developer Beta2 SDK (5.0.0.31)
DevEco-Studio 版本:DevEco Studio NEXT Developer Beta2 (5.0.3.502)
工程机版本:ALN-AL00 NEXT.0.0.31

使用系统文件预览不同类型的本地文件

MediaUtils.ets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* Copyright (c) 2024. Dench.
* 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 { fileUri } from "@kit.CoreFileKit";
import { BusinessError } from "@kit.BasicServicesKit";
import { filePreview } from "@kit.PreviewKit";
import { uniformTypeDescriptor } from "@kit.ArkData";

/**
* filePreview(文件预览)
*/
export function openSystemPreview(context: Context, path: string) {
// let uiContext = getContext(this);
// let displayInfo: filePreview.DisplayInfo = {
// x: 100,
// y: 100,
// width: 800,
// height: 800
// };
const uri = fileUri.getUriFromPath(path);
const mimeType = getFileMimeType(path);
console.info("uri:" + uri);
console.info("mimeType:" + mimeType);
let fileInfo: filePreview.PreviewInfo = {
uri: uri,
mimeType: mimeType,
};
filePreview
.openPreview(context, fileInfo)
.then(() => {
console.info("Succeeded in opening preview");
})
.catch((err: BusinessError) => {
console.error(
`Failed to open preview, err.code = ${err.code}, err.message = ${err.message}`
);
});
}

/**
* 根据文件后缀查询对应文件的 mimeType
*/
export function getFileMimeType(path: string): string {
if (path.indexOf(".") != -1) {
try {
const ext = "." + path.split(".").pop();
console.info("ext:" + ext);
// 2.可根据 “.mp3” 文件后缀查询对应UTD数据类型,并查询对应UTD数据类型的具体属性
let typeId1 =
uniformTypeDescriptor.getUniformDataTypeByFilenameExtension(ext);
console.info("typeId1:" + typeId1);
let typeObj1 = uniformTypeDescriptor.getTypeDescriptor(typeId1);
// console.info('typeId:' + typeObj1.typeId);
console.info("belongingToTypes:" + typeObj1.belongingToTypes);
// console.info('description:' + typeObj1.description);
// console.info('referenceURL:' + typeObj1.referenceURL);
// console.info('filenameExtensions:' + typeObj1.filenameExtensions);
console.info("mimeTypes:" + typeObj1.mimeTypes);
return typeObj1.mimeTypes[0];
} catch (e) {}
}
return "text/plain";
}

Reference

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/preview-arkts-V5#section1081123302517

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/uniform-data-type-descriptors-V5

文件大小最大两位小数显示

SDK 版本:HarmonyOS NEXT Developer Beta2 SDK (5.0.0.31)
DevEco-Studio 版本:DevEco Studio NEXT Developer Beta2 (5.0.3.502)
工程机版本:ALN-AL00 NEXT.0.0.31

文件大小最大两位小数显示

FileUtil.ets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
* Copyright (c) 2024. Dench.
* 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 { intl } from "@kit.LocalizationKit";

export class FileUtil {
/**
* 文件大小最大两位小数显示
*/
getFileSizeStr(size?: number): string {
const numberFormat = new intl.NumberFormat("zh-CN", {
maximumFractionDigits: 2,
});
if (size === undefined) {
return "";
}
if (size >= this.GB) {
return numberFormat.format(size / this.GB) + "G";
}
if (size >= this.MB) {
return numberFormat.format(size / this.MB) + "M";
}

if (size >= this.KB) {
return numberFormat.format(size / this.KB) + "k";
}
return size + "b";
}

private readonly KB = 1000;
private readonly MB = 1000000;
private readonly GB = 1000000000;
}

Reference

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/i18n-numbers-weights-measures-V5#%E6%95%B0%E5%AD%97%E6%A0%BC%E5%BC%8F%E5%8C%96

鸿蒙-日期格式化输出(ArkTS)

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2(4.1.3.700)
HarmonyOS API 版本:4.1.0(11)

日期格式化输出(ArkTS)

1
2
3
4
5
6
7
8
9
10
11
// 时间戳转换为显示时间输出
function timestampToDate(t: number): string {
let date = new Date(t);
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const day = ("0" + date.getDate()).slice(-2);
const hours = ("0" + date.getHours()).slice(-2);
const minutes = ("0" + date.getMinutes()).slice(-2);
const seconds = ("0" + date.getSeconds()).slice(-2);
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

鸿蒙-HDC 常用命令

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2(4.1.3.700)
HarmonyOS API 版本:4.1.0(11)

HDC 常用命令

0x01 全局相关命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 显示hdc相关的帮助信息
hdc -h

# 显示hdc的版本信息
hdc -v

# 获取OTA系统版本号
hdc shell param get const.product.software.version

# 获取序列号(获取设备信息)
# 查询已连接的所有目标设备,添加-v选项,则会打印设备详细信息。
hdc list targets

# 交互命令,COMMAND表示需要执行的单次命令。不同类型或版本的系统支持的COMMAND命令有所差异,可以通过hdc shell ls /system/bin查阅支持的命令列表。
hdc shell
hdc shell ps -ef
hdc shell help -a // 查询全部可用命令

0x02 服务进程相关命令

1
2
3
4
5
6
7
8
# 重启目标设备,查看目标列表可用list targets命令。
hdc target boot

# 终止hdc服务进程,使用-r参数触发服务进程重新启动。
hdc kill [-r]

# 启动hdc服务进程,使用-r参数触发服务进程重新启动。
hdc start [-r]

0x03 文件相关命令

1
2
3
4
5
6
# 从本地发送文件至远端设备。
hdc file send E:\example.txt /data/local/tmp/example.txt

# 从远端设备发送文件至本地。
hdc file recv /data/local/tmp/a.txt ./a.txt

0x04 应用相关命令

1
2
3
4
5
6
7
8
9
# 安装指定的应用package文件。
hdc install -r E:\com.example.hello.hap

# 卸载指定的应用包package包名。
hdc uninstall com.example.hello

# 显示可调试应用列表。
hdc jpid

hdc help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
                        OpenHarmony device connector(HDC) ...

---------------------------------global commands:----------------------------------
-h/help [verbose] - Print hdc help, 'verbose' for more other cmds
-v/version - Print hdc version
-t connectkey - Use device with given connect key

---------------------------------component commands:-------------------------------
session commands(on server):
list targets [-v] - List all devices status, -v for detail
start [-r] - Start server. If with '-r', will be restart server
kill [-r] - Kill server. If with '-r', will be restart server

service commands(on daemon):
target mount - Set /system /vendor partition read-write
target boot [-bootloader|-recovery] - Reboot the device or boot into bootloader\recovery.
target boot [MODE] - Reboot the into MODE.
smode [-r] - Restart daemon with root permissions, '-r' to cancel root
permissions
tmode usb - Reboot the device, listening on USB
tmode port [port] - Reboot the device, listening on TCP port

---------------------------------task commands:-------------------------------------
file commands:
file send [option] local remote - Send file to device
file recv [option] remote local - Recv file from device
option is -a|-s|-z
-a: hold target file timestamp
-sync: just update newer file
-z: compress transfer
-m: mode sync

forward commands:
fport localnode remotenode - Forward local traffic to remote device
rport remotenode localnode - Reserve remote traffic to local host
node config name format 'schema:content'
examples are below:
tcp:<port>
localfilesystem:<unix domain socket name>
localreserved:<unix domain socket name>
localabstract:<unix domain socket name>
dev:<device name>
jdwp:<pid> (remote only)
fport ls - Display forward/reverse tasks
fport rm taskstr - Remove forward/reverse task by taskstring

app commands:
install [-r|-s] src - Send package(s) to device and install them
src examples: single or multiple packages and directories
(.hap .hsp)
-r: replace existing application
-s: install shared bundle for multi-apps
uninstall [-k] [-s] package - Remove application package from device
-k: keep the data and cache directories
-s: remove shared bundle

debug commands:
hilog [-h] - Show device log, -h for detail
shell [COMMAND...] - Run shell command (interactive shell if no command given)
bugreport [FILE] - Return all information from the device, stored in file if FILE is specified
jpid - List pids of processes hosting a JDWP transport

security commands:
keygen FILE - Generate public/private key; key stored in FILE and FILE.pub

参考

HarmonyOS NEXT Developer:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/hdc-V5

鸿蒙-Promise 并发(JS)

Promise 并发(JS)

在 async 函数中,“过度 await”代码非常普遍。将 Promise.all() 与异步函数一起使用,可以有效的实现并发。

例如,两个异步函数 fetchA, fetchB:

1
2
3
4
5
6
7
8
9
async function fetchA() {
const response = await fetch("/path/a");
return await response.json();
}

async function fetchB() {
const response = await fetch("/path/b");
return await response.json();
}

await 运算符会让异步函数串行执行,执行 fetchA()获得结果之后,才去执行 fetchB()。如下:

1
2
3
4
5
async function awaitFunc() {
const a = await fetchA();
const b = await fetchB();
return handleResult(a, b);
}

我们可以使用 Promise.all 让异步函数并发执行。

1
2
3
4
async function promiseAllFunc() {
const [a, b] = await Promise.all([fetchA(), fetchB()]);
return handleResult(a, b);
}

Promise 类提供了以下四种异步任务的并发。

Ox01 Promise.all()

Promise.all() 静态方法接受一个 Promise 可迭代对象作为输入,并返回一个 Promise。当所有输入的 Promise 都被兑现时,返回的 Promise 也将被兑现(即使传入的是一个空的可迭代对象),并返回一个包含所有兑现值的数组。

  • 所有的 Promise 都被兑现时兑现,并返回一个包含所有兑现值的数组;
  • 在任何一个输入的 Promise 被拒绝时立即拒绝,并带回被拒绝的原因;
1
2
3
4
5
6
7
8
9
10
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "foo");
});

Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// Expected output: Array [3, 42, "foo"]

Ox02 Promise.allSettled()

Promise.allSettled() 静态方法将一个 Promise 可迭代对象作为输入,并返回一个单独的 Promise。当所有输入的 Promise 都已敲定时(包括传入空的可迭代对象时),返回的 Promise 将被兑现,并带有描述每个 Promise 结果的对象数组。

  • 在所有的 Promise 都被敲定时兑现,返回一个带有描述每个 Promise 结果的对象数组;
  • 永远不会被 reject;
1
2
3
4
5
6
7
8
9
10
11
12
13
Promise.allSettled([
Promise.resolve(33),
new Promise((resolve) => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error("一个错误")),
]).then((values) => console.log(values));

// [
// { status: 'fulfilled', value: 33 },
// { status: 'fulfilled', value: 66 },
// { status: 'fulfilled', value: 99 },
// { status: 'rejected', reason: Error: 一个错误 }
// ]
  • status: 一个字符串,要么是 “fulfilled”,要么是 “rejected”,表示 promise 的最终状态。
  • value: 仅当 status 为 “fulfilled”,才存在。promise 兑现的值。
  • reason: 仅当 status 为 “rejected”,才存在,promsie 拒绝的原因。

Ox03 Promise.any()

在任意一个 Promise 被兑现时兑现;仅在所有的 Promise 都被拒绝时才会拒绝。

1
2
3
4
5
6
7
8
9
const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, "quick"));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, "slow"));

const promises = [promise1, promise2, promise3];

Promise.any(promises).then((value) => console.log(value));

// Expected output: "quick"

Ox04 Promise.race()

在任意一个 Promise 被敲定时敲定。换句话说,在任意一个 Promise 被兑现时兑现;在任意一个的 Promise 被拒绝时拒绝。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function sleep(time, value, state) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (state === "兑现") {
return resolve(value);
} else {
return reject(new Error(value));
}
}, time);
});
}

const p1 = sleep(500, "一", "兑现");
const p2 = sleep(100, "二", "兑现");

Promise.race([p1, p2]).then((value) => {
console.log(value); // “二”
// 两个都会兑现,但 p2 更快
});

const p3 = sleep(100, "三", "兑现");
const p4 = sleep(500, "四", "拒绝");

Promise.race([p3, p4]).then(
(value) => {
console.log(value); // “三”
// p3 更快,所以它兑现
},
(error) => {
// 不会被调用
}
);

const p5 = sleep(500, "五", "兑现");
const p6 = sleep(100, "六", "拒绝");

Promise.race([p5, p6]).then(
(value) => {
// 不会被调用
},
(error) => {
console.error(error.message); // “六”
// p6 更快,所以它拒绝
}
);

参考

MDN Web 开发技术:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

鸿蒙-MD5摘要(ArkTS)

SDK 版本:HarmonyOS NEXT Developer Beta2 SDK (5.0.0.31)
DevEco-Studio 版本:DevEco Studio NEXT Developer Beta2 (5.0.3.502)
工程机版本:ALN-AL00 NEXT.0.0.31

简介

MD5 算法常常被用来验证网络文件传输的完整性,防止文件被人篡改。MD5 全称是报文摘要算法(Message-Digest Algorithm 5),此算法对任意长度的信息逐位进行计算,产生一个二进制长度为 128 位(十六进制长度就是 32 位)的“指纹”(或称“报文摘要”),不同的文件产生相同的报文摘要的可能性是非常非常之小的。

Linux 下 md5sum 用法 (查看文件或字符串的 md5 值)

md5sum 命令采用 MD5 报文摘要算法(128 位)计算和检查文件的校验和。一般来说,安装了 Linux 后,就会有 md5sum 这个工具,直接在命令行终端直接运行。

windows 下如果安装了 git-bash 也可以在所在的文件夹下,右击,选择[Git Bash Here],也可以直接使用 md5sum 命令。

MD5 ArkTS 实现代码

MD5Util.ets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* Copyright (c) 2024. Dench.
* 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 { cryptoFramework } from "@kit.CryptoArchitectureKit";
import { buffer } from "@kit.ArkTS";
import { hash } from "@kit.CoreFileKit";
import { systemDateTime } from "@kit.BasicServicesKit";

/**
* 计算字符串Md5
*/
export async function md5(messageText: string): Promise<string> {
const md = cryptoFramework.createMd("MD5");
await md.update({
data: new Uint8Array(buffer.from(messageText, "utf-8").buffer),
});
const mdOutput = await md.digest();
console.info("md mdOutput: " + mdOutput.data);
let mdLen = md.getMdLength();
console.info("md mdLen: " + mdLen);
const result = buffer.from(mdOutput.data.buffer).toString("hex");
console.info("md result: " + result);
return result;
}

// 文件Md5, 哈希计算采用的算法。可选 "md5"、"sha1" 或 "sha256"。建议采用安全强度更高的 "sha256", 此处使用"md5"
export async function fileMd5(filePath: string): Promise<string> {
try {
const t = systemDateTime.getTime();
const result = await hash.hash(filePath, "md5");
console.info("fileMd5: result=" + result);
console.info(`fileMd5: duration=${systemDateTime.getTime() - t}`);
return result;
} catch (err) {
console.error(`fileMd5: ${JSON.stringify(err)}`);
return "";
}
}

// 文件MD5,大文件读写效率低,有性能瓶颈,采用上面的文件Hash算法
// export async function fileMd5(path: string, algName: string = "MD5"): Promise<string> {
// console.info("fileMd5: path=" + path)
// let md = cryptoFramework.createMd(algName);
// try {
// const t = systemDateTime.getTime();
// let file = await fs.open(path, fs.OpenMode.READ_ONLY);
// let arrayBuffer = new ArrayBuffer(4096);
// let offset = 0;
// let readOptions: ReadOptions = {
// offset: offset,
// length: 4096
// };
// let len = await fs.read(file.fd, arrayBuffer, readOptions);
// while (len > 0) {
// // console.info("md read file len: " + len);
// const bf = buffer.from(arrayBuffer).subarray(0, len);
// // console.info("md bf: " + bf.buffer.byteLength);
// const uint8 = new Uint8Array(bf.buffer);
// // console.info("md uint8: " + uint8.byteLength);
// await md.update({ data: uint8 });
// offset += len;
// readOptions.offset = offset;
// len = await fs.read(file.fd, arrayBuffer, readOptions);
// }
// try {
// fs.close(file);
// } catch (e) {
// console.info(JSON.stringify(e));
// }
// let mdOutput = await md.digest();
// // console.info("md mdOutput: " + mdOutput.data);
// let mdLen = md.getMdLength();
// // console.info("md mdLen: " + mdLen);
// const result = buffer.from(mdOutput.data.buffer).toString('hex');
// console.info("md succeed: " + result);
// console.info(`md duration=${systemDateTime.getTime() - t}`);
// return result;
// } catch (e) {
// console.error("md error: " + JSON.stringify(e));
// return ''
// }
// }

Reference

https://www.cnblogs.com/kevingrace/p/10201723.html
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-hash-V5

鸿蒙-Text组件使用自定义字体

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

1 导入字体文件

将字体文件BebasNeue-Regular.ttf放在项目的resources/rawfile文件夹下,如下图:

20240604201941

2 注册自定义字体

需要在组件的 aboutToAppear() 方法中,使用font注册自定义字体。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import font from '@ohos.font';

@Component
export struct CustomFontComponent {
aboutToAppear(): void {
font.registerFont({
familyName: 'BebasNeue',
familySrc: $rawfile('BebasNeue-Regular.ttf')
})
}

build() {
Column() {
Text('9999')
.fontSize(17)
.fontColor('#333333')
.fontFamily('BebasNeue')
.maxLines(1)
.textAlign(TextAlign.Center)
.fontWeight(FontWeight.Regular)
.textOverflow({
overflow: TextOverflow.Ellipsis
})
.height('100%')
.width('100%');
}
}
}

3 使用已注册的字体

在Text组件中使用已注册的字体,设置fontFamily为已注册的familyName即可。

参考

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-font-V5

鸿蒙-下拉刷新控件PullToRefresh使用

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)
PullToRefresh 版本:"@ohos/pulltorefresh": "2.0.5"

下拉刷新控件 PullToRefresh 使用

  • 支持自定义 header,footer
  • 没有更多了布局

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { HomeVM } from '../vm/HomeVM';
import { PullToRefresh } from '@ohos/pulltorefresh';

@Component
export struct ListAreaComponent {
@State data?: ListDataWrapper[] | null = null
private vm: HomeVM = new HomeVM()
// 需绑定列表或宫格组件
private scroller: Scroller = new Scroller();

aboutToAppear(): void {
// request data.
this.vm.requestData().then((data: ListDataWrapper[]) => {
this.data = data;
})
}

build() {
PullToRefresh({
// 必传项,列表组件所绑定的数据
data: this.data,
// 必传项,需绑定传入主体布局内的列表或宫格组件
scroller: this.scroller,
// 必传项,自定义主体布局,内部有列表或宫格组件
customList: () => {
// 一个用@Builder修饰过的UI方法
this.getListView()
},
// 可选项,下拉刷新回调
onRefresh: () => {
return new Promise<string>((resolve) => {
this.vm.requestData().then((data: ListDataWrapper[]) => {
this.data = data
resolve('')
}).catch((error: Error) => {
resolve('')
});
});
},
// 可选项,上拉加载更多回调
onLoadMore: () => {
return new Promise<string>((resolve) => {
resolve('')
});
},
customLoad: commonNoMore,
customRefresh: commonLoading,
})
.width('100%')
.height('100%')
}

@Builder
getListView() {
List({ space: 12, scroller: this.scroller }) {
ForEach(this.data, (item: ListDataWrapper, index: number) => {
ListItem() {
// ...
};
}, (item: ListDataWrapper, index?: number) => index + JSON.stringify(item));
}
.width('100%')
.height('100%')
.scrollBar(BarState.Off)
.edgeEffect(EdgeEffect.None)
}
}


@Builder
export function commonLoading(): void {
Stack() {
// Text(refreshText)
// .textAlign(TextAlign.Center)
// .fontColor( 0)
// .fontSize( 0)
Stack() {
Canvas(new CanvasRenderingContext2D(new RenderingContextSettings(true)))
.width('100%')
.height('100%')
.onReady(() => {
// this.initCanvas();
}) // .visibility(this.state == IS_PULL_DOWN_2 ? Visibility.Visible : Visibility.Hidden)
// .visibility(Visibility.Hidden)
LoadingProgress()
.color('#FF00A3FF')
.width(32)
.height(32)
}
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
.clip(true)
}

@Builder
export function commonNoMore(): void {
Stack() {
Text('已经到底了~')
.textAlign(TextAlign.Center)
.fontColor('#FF85888F')
.fontSize(14)
}
.width('100%')
.height('100%')
.clip(true)
}

@Builder
export function commonEmpty(): void {
Stack()
.width('100%')
.height('100%')
}

注意,列表组件需要设置为无边缘效果:List().edgeEffect(EdgeEffect.None)

参考

https://ohpm.openharmony.cn/#/cn/detail/@ohos%2Fpulltorefresh

解析<em></em>标签高亮显示

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

解析标签高亮显示

由于跟后端约定,接口中对于返回的字符串中,使用标签的内容需要使用主题色高亮显示。比如 <em>权力</em>的<em>游戏</em> 第<em>七</em>季

注意:当前版本不支持标签嵌套。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Text() {
buildHighLightSpan(item.title)
}
.fontSize(17)
.fontColor('#FF222222')
.fontWeight(600)
.textOverflow({
overflow: TextOverflow.Ellipsis
})
.width('100%')


/**
* 解析 <em> </em>标签高亮显示
*
* 注意:不支持嵌套
*
* @param highLightTitle 带标签的文本
*/
@Builder
function buildHighLightSpan(highLightTitle: string | undefined) {
if (highLightTitle == null || highLightTitle.indexOf('<em>') == -1 || highLightTitle.indexOf('</em>') == -1) {
Span(highLightTitle?.replace('<em>', '').replace('</em>', '')).fontColor('#FF222222')
} else {
ForEach(highLightTitle.split('</em>'), (attr: string) => {
ForEach(attr.split('<em>'), (item: string, index: number) => {
if (item != null || item != '') {
if (index == 0) {
Span(item).fontColor('#FF222222');
} else {
Span(item).fontColor('#FF00A3FF');
}
}
});
})
}
}

组件之间的数据同步,@State,@Prop,@Watch装饰器

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

组件之间的数据同步,@State,@Prop,@Watch 装饰器

这里是一个使用的@State,@Prop,@Watch 装饰器做组件之间的数据同步的 demo。

父组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Component
struct SearchResultPage {
@State input: string = '';
@State searchWord: string = ''

aboutToAppear(): void {
this.syncSearchWord(this.input)
}

build() {
Column() {
SearchDramaResultList({ searchWord: this.searchWord }).layoutWeight(1)
}
.width('100%')
.height('100%')
}

syncSearchWord(keyword: string) {
if (keyword == '') return;
this.searchWord = keyword
}
}

子组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component
export struct SearchDramaResultList {
@Prop @Watch('requestData') searchWord: string;
@State data?: SearchSeasonVo[] | null = null
private vm = new SearchVM()
// 需绑定列表或宫格组件
private scroller: Scroller = new Scroller();

aboutToAppear(): void {
// request data.
this.requestData()
}

requestData(propName: string) {
console.log("requestData: searchWord=", this.searchWord, ",propName=", propName);
// do data request with searchWord
}
}

超好用的字符串拼接类StringBuilder

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

字符串拼接类 StringBuilder

类似 Java 的 StringBuilder,拼接多个字符串。

  1. 支持空字符串过滤
  2. 支持多个字符串中间使用指定的字符拼接

StringBuilder.ets代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
* Copyright (c) 2024 @Dench.
* 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.
*/

export class StringBuilder {
private value: string[];

constructor() {
this.value = [];
}

append(str: string | number | undefined | null): StringBuilder {
this.value.push(String(str));
return this;
}

appendNotNull(str: string | number | undefined | null): StringBuilder {
if (str != null) {
this.value.push(String(str));
}
return this;
}

build(separator?: string): string {
return this.value.join(separator);
}
}

使用 Demo

1
2
3
4
5
6
7
8
let res = new StringBuilder()
.append("123")
.append("aaa")
.append("456")
.append("bbb")
.append("789")
.build(".");
console.info(res);

鸿蒙-TextInput清除按钮实现

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

TextInput 清除按钮实现

自定义 TextInput,TextArea 组件,实现一键清空已输入内容的按钮。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@State input: string = '';
@Builder
SearchLayout() {
Row() {
TextInput({placeholder: 'inupt your text...',})
.onChange((value) => {
this.input = value
})
.layoutWeight(1)
ImageView({
option: {
loadSrc: $r("app.media.clear"),
width: 16,
height: 16,
}
})
.visibility(this.input == '' ? Visibility.None : Visibility.Visible)
.onClick(() => {
this.input = ''
})
}
}

参考

https://ost.51cto.com/answer/8395

鸿蒙-TextInput首次进入页面不弹键盘

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

TextInput 首次进入页面不弹键盘

搜索结果页面的顶部有个 TextInput 输入框,导致一进入页面会自动拉起键盘。这是因为进入页面时,TextInput 会自动获得焦点。系统组件提供了defaultFocus()方法,用来手动控制是否默认获取焦点。

注意,单纯设置 TextInput 的defaultFocus(false)可能会不生效,需要当前页面中有主动承接默认焦点的控件才行。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
Image($r("app.media.back"))
.width(24)
.height(24)
.onClick(() => {})
.focusable(true)
.defaultFocus(true);

TextInput({
placeholder: "搜索您想要的内容",
})
.focusable(true)
.focusOnTouch(true)
.defaultFocus(false);

参考

https://blog.csdn.net/Mayism123/article/details/137349464

获取鸿蒙手机屏幕的宽高

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

获取鸿蒙手机屏幕的宽高

DeviceUtil.ets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* Copyright (c) 2022 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 { display } from "@kit.ArkUI";

export class DeviceUtil {
private static width = 0;
private static widthPx = 0;
private static height = 0;
private static heightPx = 0;

public static getDisplayWidth(): number {
if (DeviceUtil.width == 0) {
DeviceUtil.setupDisplaySize();
}
return DeviceUtil.width;
}

public static getDisplayWidthPx(): number {
if (DeviceUtil.widthPx == 0) {
DeviceUtil.setupDisplaySize();
}
return DeviceUtil.widthPx;
}

public static getDisplayHeight(): number {
if (DeviceUtil.height == 0) {
DeviceUtil.setupDisplaySize();
}
return DeviceUtil.height;
}

public static getDisplayHeightPx(): number {
if (DeviceUtil.heightPx == 0) {
DeviceUtil.setupDisplaySize();
}
return DeviceUtil.heightPx;
}

private static setupDisplaySize() {
let width = display.getDefaultDisplaySync().width;
let height = display.getDefaultDisplaySync().height;
DeviceUtil.widthPx = width;
DeviceUtil.width = px2vp(width);
DeviceUtil.heightPx = height;
DeviceUtil.height = px2vp(height);
}
}

参考

https://segmentfault.com/q/1010000044715976

ArkTS遍历Record对象

ArkTS 遍历 [key:values] 类型的 Record 和 object 对象

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

0x01 Object.keys

对于 key-values 类型的 Record 或者 object 对象,可以使用 Object.keys 得到一个 keys 的数组集合,然后遍历该数组获取 key 和 value 值。

1
2
3
4
// let data = { "a": "1", b: 2, c: 3 }; // this line api 11 no longer works.
Object.keys(data).forEach((key: string) => {
console.log(key, data[key]);
});

0x02 Object.entries

对于 key-values 类型的 Record 或者 object 对象,可以使用 Object.entries 把 key-values 对象变成数组,之后再组装成一个 Map 对象进行遍历。

1
2
3
4
5
6
7
// let data = { "a": "1", b: 2, c: 3 }; // this line api 11 no longer works.
let map: Map<ESObject, ESObject> = new Map<ESObject, ESObject>(
Object.entries(data)
);
map.forEach((value: ESObject, key: string) => {
console.log(key, value);
});

参考

https://segmentfault.com/q/1010000044602257

鸿蒙Problems:路由导航

鸿蒙 Problems:路由导航

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

0x01 The named route is not exist.

问题描述

在想要跳转到的 Har 或者 Hsp 子模块的页面(hara 模块的 Index 页面),已经使用 @Entry({ routeName: "hara_index_page" }) 给 Index 页面自定义命名,使用

1
2
3
4
router.pushNamedRoute({
name: "hara_index_page",
params: { data: "Hello World!" },
});

进行跳转,也对 hara 模块进行了依赖。然以执行跳转的时候,还是报了 The named route is not exist.异常。

解决方案

查看文档发现,还需要在配置成功后,手动在跳转的页面中 import 被跳转页面:

1
import("@ohos/hara/src/main/ets/pages/Index"); // 引入共享包中的命名路由页面

0x02 A page configured in ‘main_pages.json’ must have one and only one ‘@Entry’ decorator.

问题描述

main_pages.json文件中申明的 Page 页面,必须有且只有一个@Entry的装饰器。

但是我检查了项目中所有main_pages.json文件配置的 Page 页面都满足要求。然后怎么清除缓存重新安装都没有用。

后来,发现项目是分层+模块化架构,其中一个 har 模块没有配置 main 入口。(一般使用 DevEco Studio 直接创建 har 模块不会有这个问题)

解决方案

在模块的oh-package.json5文件中配置main入口如下:

1
2
3
4
5
6
7
8
9
{
"name": "hara",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "Index.ets",
"author": "",
"license": "Apache-2.0",
"dependencies": {}
}

基于ImageKnife库的图片加载框架封装

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)
ImageKnife 版本:"@ohos/imageknife": "3.0.0-rc.0"

基于 ImageKnife 库的图片加载框架封装

  • 显示本地图片
  • 显示网络图片
  • 支持图片圆角
  • 圆形头像和设置边框
  • 支持 SVG,Gif 格式(框架自动支持)
  • 自定义大小缩放和样式填充

关键代码 ImageLoader.ets封装如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* Copyright (c) 2022 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 { ImageKnifeComponent } from '@ohos/imageknife';

export interface ImageOption {
// 必须项
// 主图资源
loadSrc: string | PixelMap | Resource;
width: number;
height: number;

// 可选项
// 占位图
placeholderSrc?: PixelMap | Resource;

// 继承Image的能力,支持option传入objectFit设置图片缩放,
// 大图样式:objectFit为Contain时根据图片自适应高度
// 项目默认:objectFit为Cover时根据Image的容器大小缩放后居中裁剪
objectFit?: ImageFit
// 继承Image的能力,支持option传入border,设置边框,圆角
border?: BorderOptions
// priority? : taskpool.Priority = taskpool.Priority.LOW
//
// context?: common.UIAbilityContext;

customGetImage?: (context: Context, src: string | PixelMap | Resource) => Promise<ArrayBuffer | undefined>;
progressListener?: (progress: number) => void;

}

@Component
export struct ImageView {
option?: ImageOption

build() {
ImageKnifeComponent({
ImageKnifeOption: {
loadSrc: this.option?.loadSrc,
placeholderSrc: this.option?.placeholderSrc,
objectFit: this.option?.objectFit ?? ImageFit.Cover,
border: this.option?.border,
customGetImage: this.option?.customGetImage,
progressListener: this.option?.progressListener,
},
adaptiveWidth: this.option?.width,
adaptiveHeight: this.option?.height,
})
.width(this.option?.width)
.height(this.option?.height)
}
}

使用 Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import { ImageView } from '@ohos/tool';

const url = 'https://www.openharmony.cn/_nuxt/img/logo.dcf95b3.png'
const url2 = 'https://file.atomgit.com/uploads/user/1704857786989_8994.jpeg' // 642*642

@Entry
@Component
struct ImageTest {
build() {
Scroll() {
Column() {
Text("显示本地图片")
.fontSize(24)
.fontWeight(FontWeight.Bold)
ImageView({
option: {
loadSrc: $r("app.media.gif1"),
width: 100,
height: 100,
}
})
.backgroundColor(Color.Black)
.width(100).height(100).margin(20)

Text("显示网络图片")
.fontSize(24)
.fontWeight(FontWeight.Bold)
ImageView({
option: {
loadSrc: url2,
width: 100,
height: 100,
placeholderSrc: $r("app.media.app_icon"),
}
}).width(100).height(100).margin(20)

Text("图片圆角")
.fontSize(24)
.fontWeight(FontWeight.Bold)
Row() {
ImageView({
option: {
loadSrc: url2,
width: 100,
height: 100,
placeholderSrc: $r("app.media.app_icon"),
border: { radius: 8 }
}
}).width(100).height(100).margin(20)

ImageView({
option: {
loadSrc: url2,
width: 100,
height: 100,
placeholderSrc: $r("app.media.app_icon"),
border: {
radius: {
topLeft: 8,
topRight: 8,
},
},
}
}).width(100).height(100).margin(20)
}

Text("圆形头像和描边效果")
.fontSize(24)
.fontWeight(FontWeight.Bold)
ImageView({
option: {
loadSrc: url2,
width: 100,
height: 100,
placeholderSrc: $r("app.media.app_icon"),
border: {
radius: 50,
width: 2,
color: Color.Green,
style: BorderStyle.Solid
},
}
}).width(100).height(100).margin(20)

Text("自定义大小和填充样式:\n项目默认:ImageFit.Cover\n大图样式:ImageFit.Contain")
.fontSize(24)
.fontWeight(FontWeight.Bold)
Row() {
ImageView({
option: {
loadSrc: $r("app.media.gif1"),
width: 100,
height: 100,
objectFit: ImageFit.Auto
}
}).width(100).height(100).margin(20)
.backgroundColor(Color.Black)

ImageView({
option: {
loadSrc: $r("app.media.gif1"),
width: 100,
height: 100,
objectFit: ImageFit.Contain
}
}).width(100).height(100).margin(20)
.backgroundColor(Color.Black)
}

Row() {
ImageView({
option: {
loadSrc: $r("app.media.gif1"),
width: 100,
height: 100,
objectFit: ImageFit.Cover
}
}).width(100).height(100).margin(20)
.backgroundColor(Color.Black)

ImageView({
option: {
loadSrc: $r("app.media.gif1"),
width: 100,
height: 100,
objectFit: ImageFit.Fill
}
}).width(100).height(100).margin(20)
.backgroundColor(Color.Black)
}

Row() {
ImageView({
option: {
loadSrc: $r("app.media.gif1"),
width: 50,
height: 50,
objectFit: ImageFit.Cover
}
}).width(100).height(100).margin(20)
.backgroundColor(Color.Black)

ImageView({
option: {
loadSrc: $r("app.media.gif1"),
width: 50,
height: 50,
objectFit: ImageFit.Contain
}
}).width(100).height(100).margin(20)
.backgroundColor(Color.Black)
}

}.width('100%')
}.width('100%').height('100%').scrollBar(BarState.Off)
}
}

ArkTS中的typeof与instanceof使用说明

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)

ArkTS 中的 typeof 与 instanceof 使用说明

开发过程中遇到判断一个变量是否是 string 类型,先看下面一处代码:

1
2
3
4
5
6
7
let url: string | PixelMap | Resource | undefined = "xxx.xxx";
if ("string" == typeof url) {
// this is true.
}
if (url instanceof String) {
// this is false.
}

0x01 typeof

typeof 操作符用于检测基本数据类型(如:string, number, boolean, undefined, function, object 等),返回一个表示未定义变量类型的字符串。对于函数对象,它将返回“function”。对于 object 对象的具体类型(如 Array, Date 等)则无法判断。例如,对于数组,typeof 会返回“object”,无法区分是数组还是其他对象。需要注意的是,typeof对 null 返回的是“object”。

0x02 instanceof

instanceof操作符主要用于检测对象是否由特定的构造函数创建,因此可以用来判断对象的具体类型。例如,如果你有一个 Array 对象,你可以使用 instanceof 来检测它是否是一个数组:let arr = []; console.log(arr instanceof Array); // 输出:true。 instanceof 有一个限制,它只能用于对象,不能用于基本数据类型,而且它要求对象是通过构造函数创建的。对于不是通过构造函数创建的对象,instanceof 将返回 false。

0x03 总结

typeof 操作符用于检测基本数据类型,instanceof操作符用来判断 object 对象的具体类型。

相关文章

https://developer.baidu.com/article/detail.html?id=3318356

基于mmkv的Constant封装

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)
mmkv 版本:"@tencent/mmkv": "1.3.5"

基于 mmkv 的 Constant 封装

全局变量,支持 KV 直接保存到手机物理存储,使用超方便。

关键代码 Constant.ets封装如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* Copyright (c) 2022 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 { MMKV } from "@tencent/mmkv";

export default class Constant {
private static TAG = "Constant";
/**
* time millis distance between server time and local time.
*
* offsetTime = ${local.getTime() - server.getTime()}
*/
public static offsetTime: number = 0;
/**
* session id
*
* record local from server response session id.
*/
private static SESSION_ID = "SESSION_ID";

public static get st(): string {
return MMKV.defaultMMKV().decodeString(Constant.SESSION_ID) ?? "";
}

public static set st(value: string) {
if (value != null)
MMKV.defaultMMKV().encodeString(Constant.SESSION_ID, value);
}
}

基于axios和Promise的网络框架封装

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)
axios 版本:"@ohos/axios": "^2.2.0"

基于 axios 和 Promise 的网络框架封装

  • Get Post 方式支持
  • http 其他请求方式(method)支持
  • 接口 url 参数封装 和 全局的 baseUrl 设置
  • 超时时间设置
  • 全局 Headers,接口自定义 Headers 和 请求 headers 拦截器封装和实现
  • 请求 params 参数和 data 数据支持
  • post 支持 x-www-form-urlencoded 数据格式
  • 请求结果 Json 数据解析(框架已自动解析)
  • 请求结果流程控制,Promise 封装
  • 请求结果 header 数据解析,服务器时间戳和 session

关键代码 HttpUtil.ets封装如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*
* Copyright (c) 2022 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 axios, { AxiosError, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig, Method } from '@ohos/axios';

import ResponseResult from './ResponseResult';
import logger from '../util/Logger';
import { systemDateTime } from '@kit.BasicServicesKit';
import { HashMap } from '@kit.ArkTS';
import Constant from '../common/Constant';

const TAG: string = "HttpUtil"

const timeout = 20000 // 20s超时
const baseUrl = 'https://xxx.xxx.com'

export function httpDefaultSetting() {

// default settings
axios.defaults.baseURL = baseUrl;
axios.defaults.timeout = timeout;

// default headers
axios.defaults.headers.common['Client-Type'] = 'xxx';
axios.defaults.headers.common['Client-Version'] = '1.0.4';
axios.defaults.headers.common['Os'] = 'hmos';
axios.defaults.headers.common['Token'] = 'xxx';

// for post
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 添加请求拦截器
axios.interceptors.request.use((config: InternalAxiosRequestConfig) => {
return transRequest(config);
}, (error: AxiosError) => {
return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use((response: AxiosResponse) => {
return transResponse(response);
}, (error: AxiosError) => {
return Promise.reject(error);
});
}

/**
* 请在这里处理请求体的拦截器操作逻辑
*
*/
function transRequest(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig {
try {
let millis = systemDateTime.getTime();
config.headers['t'] = millis - Constant.offsetTime; // 同步时间

// 增加验签逻辑
// 验签可以仅在需要的请求中增加验签,通过增加特定的header属性来区分
} finally {
return config;
}
}

/**
* 请在这里处理请求结果的拦截器操作逻辑
*
*/
function transResponse(response: AxiosResponse): AxiosResponse {
try {
let millis = systemDateTime.getTime();
if (lt != 0 && millis - lt < 60000) return response; // 可选,性能优化 1分钟内避免重复处理
lt = millis
let headers: HashMap<string, ESObject> = JSON.parse(JSON.stringify(response.headers));
let t: number = headers['servertimestamp'];
Constant.offsetTime = millis - t;
return response;
} catch (e) {
console.error(e)
return response;
}
}

let lt = 0

/**
* Initiates an HTTP request to a given URL.
*
* @param url URL for initiating an HTTP request.
* @param params Params for initiating an HTTP request.
*/
export function httpGet<D>(url: string, params?: ESObject, headers?: ESObject): Promise<D> {
logger.debug(TAG, "httpGet: ");
return new Promise<D>((resolve: Function, reject: Function) => {
let startTime = systemDateTime.getTime()
axios.get<ResponseResult, AxiosResponse<ResponseResult>, null>(url, {

headers: headers,

// 指定请求超时的毫秒数(0 表示无超时时间)
timeout: timeout, // 超时

// `connectTimeout` 指定请求连接服务器超时的毫秒数(0 表示无超时时间)
// 如果请求连接服务器超过 `connectTimeout` 的时间,请求将被中断
// connectTimeout: 60000, // 文档和代码不一致,代码中无法设置连接超时时间

params: params,
})
.then((response: AxiosResponse<ResponseResult>) => {
let duration = (systemDateTime.getTime() - startTime).toString()
logger.debug(TAG, "httpGet: Success. duration=" + duration);
logger.debug(TAG, "--------------------------------------");
logger.debug(TAG, "config=" + JSON.stringify(response.config));
logger.debug(TAG, "status=" + response.status);
// logger.debug(TAG, "statusText=" + response.statusText); // always empty??
logger.debug(TAG, "headers=" + JSON.stringify(response.headers));
logger.debug(TAG, "data=" + JSON.stringify(response.data));
logger.debug(TAG, "--------------------------------------");
if (isSuccess(response)) {
if (isResultSuccess(response.data)) {
resolve(response.data.data);
} else {
const e: Error = { name: `${response.data.code}`, message: `${response.data.msg}` }
reject(e);
}
} else {
const e: Error = { name: `${response.status}`, message: `${response.statusText}` }
reject(e);
}
})
.catch((reason: AxiosError) => {
logger.error(TAG, JSON.stringify(reason));
reject(reason)
})
});
}


function getRequestFormData(data?: ESObject): string | undefined {
if (data == undefined) return undefined;
let sb = new StringBuilder();
Object.keys(data).forEach((key: string) => {
sb.append(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
})
const formData = sb.build('&');
logger.debug(TAG, "getRequestFormData: formData=" + formData);
return formData;
}

function buildPostRequestHeader(isFormUrlencoded: boolean, headers?: Record<ESObject, ESObject>): Record<ESObject, ESObject> {
if (headers != null) {
headers['Content-Type'] = isFormUrlencoded ? 'application/x-www-form-urlencoded' : 'application/json'
return headers
}
return {
'Content-Type': isFormUrlencoded ? 'application/x-www-form-urlencoded' : 'application/json',
}
}

/**
* Initiates an HTTP request to a given URL.
*
* @param url URL for initiating an HTTP request.
* @param params Params for initiating an HTTP request.
*/
// o: { [s: string]: ESObject }
export function httpPost<D>(url: string, isFormUrlencoded: boolean = true, data?: ESObject, params?: ESObject, headers?: ESObject): Promise<D> {
// logger.debug(TAG, "httpPost: ");
return new Promise<D>((resolve: Function, reject: Function) => {
let startTime = systemDateTime.getTime()


axios.post(url, isFormUrlencoded ? getRequestFormData(data) : data, {
headers: buildPostRequestHeader(isFormUrlencoded, headers),

// 指定请求超时的毫秒数(0 表示无超时时间)
timeout: timeout, // 超时

// `connectTimeout` 指定请求连接服务器超时的毫秒数(0 表示无超时时间)
// 如果请求连接服务器超过 `connectTimeout` 的时间,请求将被中断
// connectTimeout: 60000, // 文档和代码不一致,代码中无法设置连接超时时间

params: params,
})
.then((response: AxiosResponse<ResponseResult>) => {
let duration = (systemDateTime.getTime() - startTime).toString()
logger.debug(TAG, "httpPost: Success. duration=" + duration);
logger.debug(TAG, "--------------------------------------");
logger.debug(TAG, "config=" + JSON.stringify(response.config));
logger.debug(TAG, "status=" + response.status);
// logger.debug(TAG, "statusText=" + response.statusText); // always empty??
logger.debug(TAG, "headers=" + JSON.stringify(response.headers));
logger.debug(TAG, "data=" + JSON.stringify(response.data));
logger.debug(TAG, "--------------------------------------");
if (isSuccess(response)) {
if (isResultSuccess(response.data)) {
resolve(response.data.data);
} else {
const e: Error = { name: `${response.data.code}`, message: `${response.data.msg}` }
reject(e);
}
} else {
const e: Error = { name: `${response.status}`, message: `${response.statusText}` }
reject(e);
}
})
.catch((reason: AxiosError) => {
logger.error(TAG, JSON.stringify(reason));
reject(reason)
})
});
}

/**
* Initiates an HTTP request to a given URL.
*
* @param url URL for initiating an HTTP request.
* @param params Params for initiating an HTTP request.
*/
export function httpRequest<D>(url: string, method?: Method | string, data?: D, config?: AxiosRequestConfig<D>): Promise<ResponseResult> {
// logger.debug(TAG, "httpRequest: ");
return new Promise<ResponseResult>((resolve: Function, reject: Function) => {
let startTime = systemDateTime.getTime()
axios.request<ResponseResult, AxiosResponse<ResponseResult>, D>({
url: url,
method: method,
baseURL: baseUrl,
headers: config?.headers,

// 指定请求超时的毫秒数(0 表示无超时时间)
timeout: timeout, // 超时

// `connectTimeout` 指定请求连接服务器超时的毫秒数(0 表示无超时时间)
// 如果请求连接服务器超过 `connectTimeout` 的时间,请求将被中断
// connectTimeout: 60000, // 文档和代码不一致,代码中无法设置连接超时时间

params: config?.params,
data: data ?? config?.data
})
.then((response: AxiosResponse<ResponseResult>) => {
let duration = (systemDateTime.getTime() - startTime).toString()
logger.debug(TAG, "httpRequest: Success. duration=" + duration);
logger.debug(TAG, "--------------------------------------");
logger.debug(TAG, "config=" + JSON.stringify(response.config));
logger.debug(TAG, "status=" + response.status);
// logger.debug(TAG, "statusText=" + response.statusText); // always empty??
logger.debug(TAG, "headers=" + JSON.stringify(response.headers));
logger.debug(TAG, "data=" + JSON.stringify(response.data));
logger.debug(TAG, "--------------------------------------");
if (isSuccess(response)) {
if (isResultSuccess(response.data)) {
resolve(response.data.data);
} else {
const e: Error = { name: `${response.data.code}`, message: `${response.data.msg}` }
reject(e);
}
} else {
const e: Error = { name: `${response.status}`, message: `${response.statusText}` }
reject(e);
}
})
.catch((reason: AxiosError) => {
logger.error(TAG, JSON.stringify(reason));
reject(reason)
})
});
}

function isSuccess(response: AxiosResponse): boolean {
return response.status >= 200 && response.status < 300
}

function isResultSuccess(result: ResponseResult): boolean {
return result.code == 0
}

鸿蒙Next开启Wifi代理遇到的坑

鸿蒙 Next 开启 Wifi 代理遇到的坑

郑重申明:仅记录鸿蒙系统开发版挂代理遇到的坑

手机:华为 Mate60
OS 版本:HarmonyOS NEXT Developer Preview2

0x01 鸿蒙手机设置中没有安装证书入口

开发过程中需要挂 charles 代理,然后需要安装证书,但是设置中没有安装证书的入口。可以通过 hdc 命令打开隐藏的证书安装应用。

1
hdc shell aa start -a MainAbility -b com.ohos.certmanager

0x02 wifi 开启代理后,应用并没有走设置的代理

设置代理之后,关闭手机 wifi,然后重新打开 wifi,再启动应用就好了。

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×