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

Your browser is out-of-date!

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

×