本節(jié)將介紹日志打印、時間換算等通用工具類的編寫和使用,工具類可以簡化應(yīng)用代碼編寫和業(yè)務(wù)流程處理。
日志類
日志類Logger旨在提供一個全局的日志打印、日志管理的地方,既可以規(guī)范整個應(yīng)用的日志打印,也方便日后對日志工具類進行修改,而不需要去改動代碼中每一個調(diào)用日志的地方,如切換具體的日志實現(xiàn)類(比如不使用Console而是HiLog),將日志記錄到本地文件等。
Logger對外的日志API全部使用靜態(tài)方法,方便調(diào)用者使用,目前分verbose,debug,info,warn,error五個級別。
開發(fā)前請熟悉鴻蒙開發(fā)指導(dǎo)文檔:[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md
]
使用方法如下:
- import Logger日志類:
import { Logger } from '../utils/log/Logger';
- 調(diào)用對應(yīng)級別的靜態(tài)方法:
Logger.debug('MyAbilityStage', 'onCreate');
3、Logger類中包括debug、info、warn、error,具體內(nèi)容如下:
// Logger.ets
import hilog from '@ohos.hilog';
const LOGGER_PREFIX: string = 'Healthy_life';
class Logger {
private domain: number;
private prefix: string;
...
constructor(prefix: string = '', domain: number = 0xFF00) {
this.prefix = prefix;
this.domain = domain;
}
debug(...args: string[]): void {
hilog.debug(this.domain, this.prefix, this.format, args);
}
info(...args: string[]): void {
hilog.info(this.domain, this.prefix, this.format, args);
}
warn(...args: string[]): void {
hilog.warn(this.domain, this.prefix, this.format, args);
}
error(...args: string[]): void {
hilog.error(this.domain, this.prefix, this.format, args);
}
}
export default new Logger(LOGGER_PREFIX, 0xFF02);
時間工具
為全局提供時間工具,避免重復(fù)定義。
- 常用時間相關(guān)常量:
// Utils.ets
const CHINESE_OF_WEEK: string[] = ['一', '二', '三', '四', '五', '六', '日'];
const YEAR: string = '年';
const MONTH: string = '月';
const DAY: string = '日';
const WEEK: string = '星期';
DAYS_OF_WEEK: number = 7;
const SUNDAY_FIRST_SHIFT: number = 6;
- 時間函數(shù)示例(由時間常量衍生出星期一到星期日和數(shù)字 1-7 的字典映射):
// Utils.ets
export const oneWeekDictFunc = () = > {
const oneWeekDict: Array< string > = [];
for (let index = 0;index < CHINESE_OF_WEEK.length; index++) {
oneWeekDict[index] = `${WEEK}${CHINESE_OF_WEEK[index]}`;
}
return oneWeekDict;
}
單位轉(zhuǎn)換工具
把比例等分浮點數(shù)轉(zhuǎn)換為百分比字符串。
例如成就頁面,每一行平均分布三個徽章,可以先定義一個浮點數(shù)代表等分比例,再轉(zhuǎn)換為百分比字符串。
// Utils.ets
export function ratio2percent(ratio: number): string {
return `${ratio * 100}%`;
}
使用方法如下:
- import 工具方法:
import { ratio2percent } from '../common/utils/Utils'
- 引用工具方法 ( 例如成就頁面,每個徽章占據(jù)屏幕寬度的三分之一 ) :
// BadgeCardComponent.ets Column({space: commonConst.DEFAULT_18}) { ... // 省略徽章卡片的 UI 布局細節(jié) } .width(ratio2percent(Const.ACHIEVE_SPLIT_RATIO)) // achieveConst.ACHIEVE_SPLIT_RATIO = 1 / 3
事件分發(fā)類
事件分發(fā)類提供應(yīng)用全局的事件注冊,分發(fā),接受,可以實現(xiàn)組件之間的解耦。
事件分發(fā)類全局共享一個實例, 將事件處理統(tǒng)一管理(HealthDataSrcMgr是單例):
獲取事件分發(fā)實例:
// HomeComponent.ets
@Provide broadCast: BroadCast = HealthDataSrcMgr.getInstance().getBroadCast();
// HealthDataSrcMgr.ets
public getBroadCast(): BroadCast {
return this.broadCast;
}
事件注冊:
// CustomDialogView.ets
aboutToAppear() {
Logger.debug('CustomDialogView', 'aboutToAppear');
// 成就對話
this.broadCast.on(BroadCastType.SHOW_ACHIEVEMENT_DIALOG, (achievementLevel: number) = > {
Logger.debug('CustomDialogView', 'SHOW_ACHIEVEMENT_DIALOG');
this.achievementLevel = achievementLevel;
this.achievementDialog.open();
});
// 任務(wù)時鐘對話框
this.broadCast.on(BroadCastType.SHOW_TASK_DETAIL_DIALOG,
(currentTask: TaskInfo, dialogCallBack: CustomDialogCallback) = > {
Logger.debug('CustomDialogView', 'SHOW_TASK_DETAIL_DIALOG');
this.currentTask = currentTask || TaskItem;
this.dialogCallBack = dialogCallBack;
this.taskDialog.open();
});
}
// BroadCast.ets
public on(event: string, callback: Function) {
Logger.info(FILE_TAG, 'register broadcast with type '+ event);
switch (event) {
case BroadCastType.SHOW_ACHIEVEMENT_DIALOG:
this.callBackArray.showAchievementDialog = callback;
break;
case BroadCastType.SHOW_TASK_DETAIL_DIALOG:
this.callBackArray.showTaskDetailDialog = callback;
break;
case BroadCastType.SHOW_TARGET_SETTING_DIALOG:
this.callBackArray.showTargetSettingDialog = callback;
break;
case BroadCastType.SHOW_REMIND_TIME_DIALOG:
this.callBackArray.showRemindTimeDialog = callback;
break;
case BroadCastType.SHOW_FREQUENCY_DIALOG:
this.callBackArray.showFrequencyDialog = callback;
break;
default:
break;
}
}
取消事件注冊:
// TaskDetailComponent.ets
aboutToAppear() {
this.broadCast.off(BroadCastType.SHOW_TARGET_SETTING_DIALOG, () = > {});
this.broadCast.off(BroadCastType.SHOW_REMIND_TIME_DIALOG, () = > {});
this.broadCast.off(BroadCastType.SHOW_FREQUENCY_DIALOG, () = > {});
}
// BroadCast.ets
public off(event: string, callback: Function) {
if (event === null) {
Logger.info(FILE_TAG, 'cancel all broadcast');
this.callBackArray = callBackArrayTemp;
}
Logger.info(FILE_TAG, 'cancel broadcast with type '+ event);
const cbs = this.callBackArray;
if (!cbs) {
return;
}
if (callback === null) {
switch (event) {
case BroadCastType.SHOW_ACHIEVEMENT_DIALOG:
this.callBackArray.showAchievementDialog = () = > {};
break;
case BroadCastType.SHOW_TASK_DETAIL_DIALOG:
this.callBackArray.showTaskDetailDialog = () = > {};
break;
case BroadCastType.SHOW_TARGET_SETTING_DIALOG:
this.callBackArray.showTargetSettingDialog = () = > {};
break;
case BroadCastType.SHOW_REMIND_TIME_DIALOG:
this.callBackArray.showRemindTimeDialog = () = > {};
break;
case BroadCastType.SHOW_FREQUENCY_DIALOG:
this.callBackArray.showFrequencyDialog = () = > {};
break;
default:
break;
}
}
}
`HarmonyOS與OpenHarmony鴻蒙文檔籽料:mau123789是v直接拿`
發(fā)送事件:
// HomeComponent.ets
taskItemAction(item: TaskInfo, isClick: boolean): void {
if (!this.homeStore.checkCurrentDay()) {
return;
}
if (isClick) {
// 點擊時鐘
let callback: CustomDialogCallback = { confirmCallback: (taskTemp: TaskInfo) = > {
this.onConfirm(taskTemp)
}, cancelCallback: () = > {
} };
this.broadCast.emit(BroadCastType.SHOW_TASK_DETAIL_DIALOG, [item, callback]);
} else {
// 編輯任務(wù)
let editTaskStr: string = JSON.stringify(TaskMapById[item.taskID - 1]);
let editTask: ITaskItem = JSON.parse(editTaskStr);
editTask.targetValue = item?.targetValue;
editTask.isAlarm = item.isAlarm;
editTask.startTime = item.startTime;
editTask.frequency = item.frequency;
editTask.isOpen = item.isOpen;
router.pushUrl({ url: 'pages/TaskEditPage', params: { params: JSON.stringify(editTask) } });
}
}
審核編輯 黃宇
-
鴻蒙
+關(guān)注
關(guān)注
57文章
2302瀏覽量
42689 -
HarmonyOS
+關(guān)注
關(guān)注
79文章
1966瀏覽量
29962 -
OpenHarmony
+關(guān)注
關(guān)注
25文章
3641瀏覽量
16061
發(fā)布評論請先 登錄
相關(guān)推薦
評論