HarmonyOS3.1/4.0切换到HarmonyOS Next后有一些变化,目前我个人在使用过程中发现这些差异最为明显。
1 变量定义
ArkTS不支持any和unknown类型。显式指定具体类型。强制进行严格类型检查。
不能这样写:
let value1: any
value1 = true;
value1 = 42;
let value2: unknown
value2 = true;
value2 = 42;
需要这样写:
let value_b: boolean = true; // 或者 let value_b = true
let value_n: number = 42; // 或者 let value_n = 42
let value_o1: Object = true;
let value_o2: Object = 42;
2 路由的传参,需要使用class
使用router进行页面跳转传递参数时,原来直接设置params参数即可,现在需要定义params为对象类型,构建routerParams对象进行传参。
如下,注释掉的代码为之前原有代码,在HarmonyOS Next4.1上无法使用。
2.1 在第一个页面中设置传递的参数
import router from '@ohos.router';
import promptAction from '@ohos.promptAction';
export class routerParams {
msg: string
constructor(msg: string) {
this.msg = msg
}
}
@Entry
@Component
struct LoginPage {
@State message: string = 'Login Page'
@State userName: string = ''
@State password: string = ''
build() {
Row() {
Column() {
Button('跳转1')
.width(100)
.margin({ top: 10 })
.onClick(() => {
// router.pushUrl({ url: 'pages/HomePage', params: { msg: 'hello world,我是上一个页面传递过来的' } },
// router.RouterMode.Standard, (err) => {
// if (err) {
// promptAction.showToast({ message: `跳转失败:code is ${err.code}, message is ${err.message}` })
// return;
// } else {
// promptAction.showToast({ message: `跳转成功` })
// }
//
// }
// )
router.pushUrl({ url: 'pages/HomePage', params: new routerParams("hello world,我是上一个页面传递过来的") },
router.RouterMode.Standard, (err) => {
if (err) {
promptAction.showToast({ message: `跳转失败:code is ${err.code}, message is ${err.message}` })
return;
} else {
promptAction.showToast({ message: `跳转成功` })
}
}
)
})
}
.width('100%')
}
.height('100%')
}
}
2.2 在第二个页面中接收传递的参数
接收上一个页面传递过来的参数时,需要注意判空,避免出现空指针问题。
import router from '@ohos.router';
import promptAction from '@ohos.promptAction';
import {routerParams} from './LoginPage';
@Entry
@Component
struct HomePage {
@State message: string = 'HomePage'
@State msg: string = '';
onPageShow() {
// const params: routerParams = router.getParams();
// if (params != null && this.msg != null) {
// // 获取info属性的值
// this.msg = params['msg'];
// } else {
// this.msg = '没有参数传递过来'
// }
// 获取传递过来的参数对象
const params = router.getParams() as routerParams;
if (params != null && this.msg != null) {
// 获取info属性的值
this.msg = params.msg;
} else {
this.msg = '没有参数传递过来'
}
}
build() {
Row() {
Column() {
Text(this.msg)
.fontSize(20)
}
.width('100%')
}
.height('100%')
}
}
3 应用文件访问代码修改
FileUtil.ets中
-
context通过getContext(this);进行获取,不能再使用getContext(this) as common.UIAbilityContext; 进行获取。
-
调用fs.listFileSync获取文件列表时,需要传入ListFileOption对象,不能传入定义的options。
import fs,{ Filter } from '@ohos.file.fs';
import Logger from '../utils/Logger';
const TAG = '[FileUtil]';
const context = getContext(this);
/**
* 创建文件,写入文件,并返回文件内容
* @returns
*/
export function createFile(): string {
// 获取应用文件路径
// let context = getContext(this) as common.UIAbilityContext;
// filesDir为 /data/storage/el2/base/haps/entry/files
let filesDir = context.filesDir;
let filePath = filesDir + '/test.txt'
// 新建并打开文件
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// 写入一段内容至文件
let writeLen = fs.writeSync(file.fd, "Try to write str.");
console.info("The length of str is: " + writeLen);
Logger.info(TAG, "The length of str is: " + writeLen);
// // 从文件读取一段内容,方式一
// let buf = new ArrayBuffer(1024);
// let readLen = fs.readSync(file.fd, buf, { offset: 0 });
// let content = String.fromCharCode.apply(null, new Uint8Array(buf.slice(0, readLen)));
// Logger.info(TAG, "readSync the content of file: " + content);
// 从文件读取内容,方式二
let content = fs.readTextSync(filePath);
Logger.info(TAG, "readTextSync the content of file: " + content);
// 关闭文件
fs.closeSync(file);
return content;
}
export function readWriteFile() {
// 获取应用文件路径
// let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 打开文件
let srcFile = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE);
let destFile = fs.openSync(filesDir + '/destFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// 读取源文件内容并写入至目的文件
let bufSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(bufSize);
let readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
while (readLen > 0) {
readSize += readLen;
fs.writeSync(destFile.fd, buf);
readLen = fs.readSync(srcFile.fd, buf, { offset: readSize });
}
// 关闭文件
fs.closeSync(srcFile);
fs.closeSync(destFile);
Logger.info(TAG, "readWriteFile success");
}
export async function readWriteFileWithStream() {
// 获取应用文件路径
// let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 打开文件流
let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+');
let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+");
// 以流的形式读取源文件内容并写入目的文件
let bufSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(bufSize);
let readLen = await inputStream.read(buf, { offset: readSize });
readSize += readLen;
while (readLen > 0) {
await outputStream.write(buf);
readLen = await inputStream.read(buf, { offset: readSize });
readSize += readLen;
}
// 关闭文件流
inputStream.closeSync();
outputStream.closeSync();
}
/**
* 查看文件列表
* @returns 文件名[]
*/
export function getFileList(): string[] {
// 获取应用文件路径
// let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;
// 查看文件列表
// let options = {
// recursion: false,
// listNum: 0,
// filter: {
// suffix: ['.png', '.jpg', '.txt'], // 匹配文件后缀名为'.png','.jpg','.txt'
// //displayName: ['test*'], // 匹配文件全名以'test'开头
// fileSizeOver: 0, // 匹配文件大小大于等于0
// lastModifiedAfter: new Date(0).getTime(), // 匹配文件最近修改时间在1970年1月1日之后
// },
// }
class ListFileOption {
public recursion: boolean = false;
public listNum: number = 0;
public filter: Filter = {};
}
let option = new ListFileOption();
option.filter.suffix = ['.png', '.jpg', '.txt']; // 匹配文件后缀名为'.png','.jpg','.txt'
option.filter.displayName = ['test*']; // 匹配文件全名以'test'开头
option.filter.fileSizeOver = 0; // 匹配文件大小大于等于0
option.filter.lastModifiedAfter = new Date(0).getTime(); // 匹配文件最近修改时间在1970年1月1日之后
let files = fs.listFileSync(filesDir, option);
for (let i = 0; i < files.length; i++) {
console.info(`The name of file: ${files[i]}`);
}
return files;
}
FilePage页面使用工具类
import common from '@ohos.app.ability.common';
import { createFile, readWriteFile, getFileList } from '../utils/FileUtil';
import Logger from '../utils/Logger';
const TAG = '[FilePage]';
@Entry
@Component
struct FilePage {
@State message: string = 'Hello World'
// ets文件中获取上下文
private context = getContext(this) as common.UIAbilityContext;
build() {
Row() {
Column() {
Button('新建并读写文件')
.onClick(() => {
// 读取文件内容
let content = createFile()
Logger.info(TAG, content)
})
Button('读取文件内容并写入到另一个文件')
.onClick(() => {
readWriteFile()
}).margin({ top: 10 })
Button('查看文件列表')
.onClick(() => {
// 查看文件列表
let file = getFileList()
Logger.info(TAG, file.toString())
}).margin({ top: 10 })
}
.width('100%')
}
.height('100%')
}
}
最后,为了能够让大家跟上互联网时代的技术迭代,赶上互联网开发人员寒冬期间一波红利,在这里跟大家分享一下我自己近期学习心得以及参考网上资料整理出的一份最新版的鸿蒙学习提升资料,有需要的小伙伴自行领取,限时开源,先到先得~无套路领取!!!
🚀写在最后
- 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
- 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
- 关注小编,同时可以期待后续文章ing🚀,不定期分享原创知识。
- 想要获取更多完整鸿蒙最新VIP学习资料,请点击→纯血版全套鸿蒙HarmonyOS学习资料