2024年鸿蒙最新学习HarmonyOS这么久,你有代码积累吗?_鸿蒙 preferences(1),头条面试HarmonyOS鸿蒙

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!


img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上鸿蒙开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化的资料的朋友,可以戳这里获取

StringUtil.ets:

/**

  • 判断字符串是否为空
  • @param str 字符串
  • @returns 判断结果
    */
    export function isBlank(str: string): boolean {
    return (null == str) || (undefined == str) || (str.trim() === “”);
    }

使用示例:

// 引入工具类方法
import { isBlank } from ‘…/utils/StringUtil’;

let result = “hello”;
// 使用方法
this.message = isBlank(result) ? ‘没有数据’ : result;

2 Logger

日志管理对于追踪问题和优化应用至关重要。Logger工具类对HarmonyOS的hilog进行了扩展,提供了格式化日志的打印功能。这使得日志信息更加清晰、易于阅读,同时也便于后期的日志分析。

Logger.ets:

import hilog from ‘@ohos.hilog’;

export class Logger {
private domain: number;
private prefix: string;
private format: string = %{public}s, %{public}s;

constructor(prefix: string) {
this.prefix = prefix;
this.domain = 0xFF00;
}

debug(…args: string[]) {
hilog.debug(this.domain, this.prefix, this.format, args);
}

info(…args: string[]) {
hilog.info(this.domain, this.prefix, this.format, args);
}

warn(…args: string[]) {
hilog.warn(this.domain, this.prefix, this.format, args);
}

error(…args: string[]) {
hilog.error(this.domain, this.prefix, this.format, args);
}

fatal(…args: string[]) {
hilog.fatal(this.domain, this.prefix, this.format, args);
}

isLoggable(level: number) {
hilog.isLoggable(this.domain, this.prefix, level);
}
}

export default new Logger(‘[Logger]’);

使用示例:

import Logger from ‘…/utils/Logger’;

Logger.info(“TAG”, “使用Logger.info”));

3 DataPreferencesUtil

数据持久化是应用开发中不可或缺的一部分。DataPreferencesUtil工具类利用HarmonyOS的dataPreferences功能,提供了一套简洁的API来保存和读取用户偏好设置。

DataPreferencesUtil.ets:

import Logger from ‘…/utils/Logger’;
import common from ‘@ohos.app.ability.common’;
import dataPreferences from ‘@ohos.data.preferences’;
import { BusinessError } from ‘@ohos.base’;

const TAG = ‘[DataPreferencesUtil]’;
let preferences: dataPreferences.Preferences | null = null;

export class DataPreferencesUtil {
// The preferences file name
private dataPreferencesName = ‘myStore’;

/**

  • 构造函数
  • @param context 上下文
    */
    constructor(context: common.UIAbilityContext) {
    try {
    let options: dataPreferences.Options = { name: this.dataPreferencesName };
    preferences = dataPreferences.getPreferencesSync(context, options);

} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(Failed to get preferences. Code:${code},message:${message});
}

}

/**

  • 保存数据
  • @param key 键
  • @param value 值
  • @returns
    */
    saveData(key: string, value: string): boolean {
    try {
    preferences?.putSync(key, value);
    preferences?.flush();
    return true;
    } catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    Logger.error(TAG, Failed to check the key 'startup'. Code:${code}, message:${message});
    return false;
    }
    }

/**

  • 获取数据
  • @param key 键
  • @returns 值,可能为null或""
    */
    getDate(key: string): string {
    try {
    let val = preferences?.getSync(key, null) as string;
    Logger.info(TAG, Succeeded in getting value of 'startup'. val: ${val}.);
    return val;
    } catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    Logger.error(TAG, Failed to get value of 'startup'. Code:${code}, message:${message});
    return “”;
    }
    }
    }

使用示例:

import Logger from ‘…/utils/Logger’;
import common from ‘@ohos.app.ability.common’;
import { BusinessError } from ‘@ohos.base’;
import { isBlank } from ‘…/utils/StringUtil’;
import { DataPreferencesUtil } from ‘…/utils/DataPreferencesUtil’;

const TAG = ‘[DataPreferencesPage]’;

@Entry
@Component
struct DataPreferencesPage {
@State message: string = ‘Hello World’
// ets文件中获取上下文
private context = getContext(this) as common.UIAbilityContext;
dataPreferences: DataPreferencesUtil = new DataPreferencesUtil(this.context);

onPageShow(): void {
try {
let result = this.dataPreferences.getDate(“Key”);

this.message = isBlank(result) ? ‘没有数据’ : result;
Logger.info(TAG, "message: " + this.message);
} catch (err) {
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(Failed to get preferences. Code:${code},message:${message});
}
}

build() {

Row() {
Column({ space: 12 }) {

Text(this.message)

Button(‘isBlank’).onClick(() => {

Logger.info(TAG, “isBlank(): " + isBlank(”"));
Logger.info(TAG, “isBlank(): " + isBlank(” "));
})

Button(‘保存数据’).onClick(() => {
let result = this.dataPreferences.saveData(“Key”, “hello”);
Logger.info(TAG, "saveData result: " + result);
})

Button(‘获取数据’).onClick(() => {
let result = this.dataPreferences.getDate(“Key”);
Logger.info(TAG, "getDate result: " + result);
this.message = result;
})
}
.width(‘100%’)
}
.height(‘100%’)
}
}

4 PhotoPickerUtil

在HarmonyOS应用中,用户经常需要从相册中选择图片。PhotoPickerUtil工具类封装了ohos.file.picker的相关操作,使得从相册中选择照片变得简单快捷。

PhotoPickerUtil.ets:

import picker from ‘@ohos.file.picker’;
import Logger from ‘…/utils/Logger’;
import { BusinessError } from ‘@ohos.base’

const TAG = ‘[PhotoPickerUtil]’;

/**

  • 从相册中获取图片路径
  • @param callback,通过回调返回
    */
    export function getPhotoPath(callback: Function) {
    const photoSelectOptions = new picker.PhotoSelectOptions();

photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
photoSelectOptions.maxSelectNumber = 5; // 选择媒体文件的最大数目

const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
let filePath = photoSelectResult.photoUris[0];

Logger.info(TAG, filePath: ${filePath});

// 通过回调返回 filePath
if (callback && typeof callback === ‘function’) {
callback(null, filePath); // 第一个参数为错误对象,为 null 表示没有错误
}

}).catch((err: BusinessError) => {
// 通过回调返回错误信息
if (callback && typeof callback === ‘function’) {
// 第二个参数为返回的数据,为 null 表示没有数据
callback(err, null);
}

Logger.error(TAG, Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message});
})
}

使用示例:

import picker from ‘@ohos.file.picker’;
import Logger from ‘…/utils/Logger’;
import { getPhotoPath } from ‘…/utils/PhotoPickerUtil’
import {BusinessError} from ‘@ohos.base’;

const TAG = ‘[PhotoViewPickerPage]’;

@Entry
@Component
struct PhotoViewPickerPage {
@State message: string = ‘Hello World’
@State imagePath: string = ‘’

getSelectedPhotoPath() {
const photoSelectOptions = new picker.PhotoSelectOptions();

photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
photoSelectOptions.maxSelectNumber = 5; // 选择媒体文件的最大数目

const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!


img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上鸿蒙开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化的资料的朋友,可以戳这里获取

259a5ffe804fa6d0db.png)
[外链图片转存中…(img-7kyDfqnt-1715277489796)]
[外链图片转存中…(img-hVxlDaCt-1715277489796)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上鸿蒙开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

需要这份系统化的资料的朋友,可以戳这里获取

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值