Skip to content

工具类

概述

工具类模块提供了一系列常用的工具函数,简化开发工作。

主要工具类

工具类职责
ContextUtil上下文工具
PreferencesUtil本地存储工具
ToastUtilsToast 提示工具
ValidationUtil验证工具
ImageUtil图片处理工具
LoggerUtil日志工具
NotificationUtil通知工具
PermissionUtils权限工具

ContextUtil

初始化

typescript
import { ContextUtil } from "@core/util";

ContextUtil.init(context);

获取上下文

typescript
const context = ContextUtil.getContext();

PreferencesUtil

保存数据

typescript
import { PreferencesUtil } from "@core/util";

await PreferencesUtil.put("key", "value");
await PreferencesUtil.put("count", 100);
await PreferencesUtil.put("isLoggedIn", true);

读取数据

typescript
const value = await PreferencesUtil.get("key", "defaultValue");
const count = await PreferencesUtil.get("count", 0);
const isLoggedIn = await PreferencesUtil.get("isLoggedIn", false);

删除数据

typescript
await PreferencesUtil.remove("key");

清空数据

typescript
await PreferencesUtil.clear();

ToastUtils

显示 Toast

typescript
import { ToastUtils } from "@core/util";

ToastUtils.show("操作成功");
ToastUtils.showSuccess("保存成功");
ToastUtils.showError("操作失败");
ToastUtils.showWarning("请注意");

ValidationUtil

验证工具

typescript
import { ValidationUtil } from "@core/util";

// 验证邮箱
ValidationUtil.isEmail("test@example.com");  // true

// 验证手机号
ValidationUtil.isPhone("13800138000");  // true

// 验证身份证号
ValidationUtil.isIdCard("110101199001011234");  // true

// 验证 URL
ValidationUtil.isUrl("https://example.com");  // true

ImageUtil

图片处理工具

获取 PixelMap

typescript
import { ImageUtil } from "@core/util";

// 从 Resource 获取 PixelMap
const pixelMap = await ImageUtil.getPixelMapFromResource($r("app.media.icon"));

// 带解码选项
const pixelMap = await ImageUtil.getPixelMapFromResource(
  $r("app.media.icon"),
  {
    desiredSize: { width: 100, height: 100 },
    desiredPixelFormat: image.PixelMapFormat.RGBA_8888
  }
);

PixelMap 与 Base64 转换

typescript
// PixelMap 转 Base64
const base64 = await ImageUtil.pixelMapToBase64(pixelMap, "image/png");

// Base64 转 PixelMap
const pixelMap = await ImageUtil.base64ToPixelMap(base64);

图片压缩

typescript
// 压缩图片到指定大小(默认 2MB)
const compressedPixelMap = await ImageUtil.createCompressedPixelMap(
  $r("app.media.large_image"),
  1 * 1024 * 1024  // 1MB
);

// 压缩 PixelMap 对象
const compressedPixelMap = await ImageUtil.createCompressedPixelMap(
  pixelMap,
  500 * 1024  // 500KB
);

图片打包

typescript
// 将 PixelMap 打包为 ArrayBuffer
const arrayBuffer = await ImageUtil.packingFromPixelMap(pixelMap, {
  format: "image/jpeg",
  quality: 90
});

LoggerUtil

日志工具

初始化

typescript
import { Logger, LogLevel } from "@core/util";

// 初始化日志配置
Logger.init({
  domain: 0xFF00,
  tag: "MyApp",
  icon: "📝",
  close: false
});

基本使用

typescript
// 调试日志
Logger.debug("这是调试信息");
Logger.debug({ userId: "123", name: "张三" });

// 信息日志
Logger.info("应用启动成功");

// 警告日志
Logger.warn("内存使用率较高");

// 错误日志
Logger.error("网络请求失败");
Logger.error(new Error("发生错误"));

// 致命错误日志
Logger.fatal("应用崩溃");

自定义标签

typescript
// 使用自定义标签
Logger.debug("用户登录", "Auth");
Logger.info("数据加载完成", "DataService");
Logger.error("支付失败", "Payment");

控制日志输出

typescript
// 禁用所有日志
Logger.disable();

// 启用所有日志
Logger.enable();

自定义日志写入器

typescript
import { LogWriter, LogLevel } from "@core/util";

// 创建文件日志写入器
class FileLogWriter extends LogWriter {
  write(level: LogLevel, domain: number, tag: string, message: string): void {
    // 将日志写入文件
    const logEntry = `[${new Date().toISOString()}] [${tag}] ${message}\n`;
    // 写入文件逻辑...
  }
}

// 设置自定义写入器
Logger.setWriter(new FileLogWriter());

// 或在初始化时设置
Logger.init({
  domain: 0xFF00,
  tag: "MyApp"
}, new FileLogWriter());

NotificationUtil

通知工具

发送通知

typescript
import { NotificationUtil } from "@core/util";

// 发送简单通知
await NotificationUtil.sendNotification({
  title: "新消息",
  text: "您有一条新消息"
});

// 发送带图片的通知
await NotificationUtil.sendNotification({
  title: "新消息",
  text: "您有一条新消息",
  largeIcon: $r("app.media.avatar"),
  picture: $r("app.media.notification_image")
});

// 发送带操作按钮的通知
await NotificationUtil.sendNotification({
  title: "新消息",
  text: "您有一条新消息",
  actions: [
    { title: "查看", action: "view" },
    { title: "忽略", action: "dismiss" }
  ]
});

取消通知

typescript
// 取消指定 ID 的通知
await NotificationUtil.cancelNotification(notificationId);

// 取消所有通知
await NotificationUtil.cancelAllNotifications();

PermissionUtils

权限工具

检查权限

typescript
import { PermissionUtils } from "@core/util";

// 检查单个权限
const hasPermission = await PermissionUtils.checkPermission(
  "ohos.permission.CAMERA"
);

// 检查多个权限
const hasPermissions = await PermissionUtils.checkPermissions([
  "ohos.permission.CAMERA",
  "ohos.permission.MICROPHONE"
]);

请求权限

typescript
// 请求单个权限
const granted = await PermissionUtils.requestPermission(
  "ohos.permission.CAMERA"
);

if (granted) {
  // 权限已授予
} else {
  // 权限被拒绝
}

// 请求多个权限
const results = await PermissionUtils.requestPermissions([
  "ohos.permission.CAMERA",
  "ohos.permission.MICROPHONE",
  "ohos.permission.LOCATION"
]);

// 检查结果
if (results.every(r => r.granted)) {
  // 所有权限已授予
} else {
  // 部分权限被拒绝
  const deniedPermissions = results
    .filter(r => !r.granted)
    .map(r => r.permission);
  console.log("被拒绝的权限:", deniedPermissions);
}

打开应用设置

typescript
// 引导用户到应用设置页面手动授权
await PermissionUtils.openAppSettings();

使用示例

完整的工具类使用

typescript
import {
  ContextUtil,
  PreferencesUtil,
  ToastUtils,
  DateUtil,
  StringUtil,
  ValidationUtil
} from "@core/util";

export class UserService {
  async saveUserInfo(userInfo: UserInfo): Promise<void> {
    // 验证邮箱
    if (!ValidationUtil.isEmail(userInfo.email)) {
      ToastUtils.showError("邮箱格式不正确");
      return;
    }

    // 保存到本地存储
    await PreferencesUtil.put("userInfo", JSON.stringify(userInfo));

    // 保存时间
    const now = DateUtil.format(new Date(), "YYYY-MM-DD HH:mm:ss");
    await PreferencesUtil.put("lastSaveTime", now);

    ToastUtils.showSuccess("保存成功");
  }

  async getUserInfo(): Promise<UserInfo | null> {
    const json = await PreferencesUtil.get("userInfo", "");
    if (StringUtil.isEmpty(json)) {
      return null;
    }
    return JSON.parse(json);
  }
}

最佳实践

1. 统一使用工具类

typescript
// 推荐
import { ToastUtils } from "@core/util";
ToastUtils.show("提示信息");

// 不推荐
promptAction.showToast({ message: "提示信息" });

2. 错误处理

typescript
try {
  await PreferencesUtil.put("key", "value");
} catch (error) {
  console.error("保存失败:", error);
  ToastUtils.showError("保存失败");
}

3. 类型安全

typescript
// 使用泛型确保类型安全
const userInfo = await PreferencesUtil.get<UserInfo>("userInfo", null);

注意事项

  1. 初始化:确保在使用前初始化 ContextUtil
  2. 异步操作:PreferencesUtil 的操作是异步的,需要使用 await
  3. 错误处理:始终处理可能的错误

下一步