鸿蒙开发学习笔记 #4

Peter 的鸿蒙开发学习笔记

鸿蒙开发学习笔记 #4

学习时间: 2026-03-14 01:45

主题: 数据存储与网络通信

---

1. 本地数据存储

1.1 Preferences 首选项

适用于存储轻量级键值对数据,如用户配置、登录状态等。


import dataPreferences from '@ohos.data.preferences';

class PreferenceManager {
  private preferences: dataPreferences.Preferences | null = null;

  // 获取或创建首选项
  async getPreferences(context, name: string = 'myApp') {
    this.preferences = await dataPreferences.getPreferences(context, name);
  }

  // 写入数据
  async put(key: string, value: string | number | boolean) {
    if (this.preferences) {
      await this.preferences.put(key, value);
      await this.preferences.flush();  // 持久化
    }
  }

  // 读取数据
  async get(key: string, defaultValue: T): Promise {
    if (this.preferences) {
      return await this.preferences.get(key, defaultValue) as T;
    }
    return defaultValue;
  }

  // 删除数据
  async delete(key: string) {
    if (this.preferences) {
      await this.preferences.delete(key);
      await this.preferences.flush();
    }
  }

  // 清空所有
  async clear() {
    if (this.preferences) {
      await this.preferences.clear();
      await this.preferences.flush();
    }
  }
}

// 使用示例
const prefs = new PreferenceManager();
await prefs.getPreferences(context);
await prefs.put('username', '张三');
const name = await prefs.get('username', '');

1.2 关系型数据库 RDB

适用于存储结构化数据,如联系人、订单等。


import relationalStore from '@ohos.data.relationalStore';

class DatabaseManager {
  private store: relationalStore.RdbStore | null = null;

  // 初始化数据库
  async init(context) {
    const config = {
      name: 'myapp.db',           // 数据库名
      securityLevel: relationalStore.SecurityLevel.S1
    };

    this.store = await relationalStore.getRdbStore(context, config);

    // 创建表
    await this.store.executeSql(`
      CREATE TABLE IF NOT EXISTS user (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT,
        age INTEGER,
        created_at TEXT DEFAULT CURRENT_TIMESTAMP
      )
    `);
  }

  // 插入数据
  async insertUser(name: string, email: string, age: number) {
    const valueBucket = {
      name: name,
      email: email,
      age: age
    };

    return await this.store.insert('user', valueBucket);
  }

  // 查询数据
  async queryUsers(): Promise> {
    const predicates = new relationalStore.RdbPredicates('user');
    const result = await this.store.query(predicates);
    
    const users = [];
    while (!result.isAtLastRow) {
      result.goToNextRow();
      users.push({
        id: result.getLong(result.getColumnIndex('id')),
        name: result.getString(result.getColumnIndex('name')),
        email: result.getString(result.getColumnIndex('email')),
        age: result.getLong(result.getColumnIndex('age'))
      });
    }
    result.close();
    return users;
  }

  // 更新数据
  async updateUser(id: number, name: string) {
    const predicates = new relationalStore.RdbPredicates('user');
    predicates.equalTo('id', id);
    
    const valueBucket = { name: name };
    return await this.store.update(valueBucket, predicates);
  }

  // 删除数据
  async deleteUser(id: number) {
    const predicates = new relationalStore.RdbPredicates('user');
    predicates.equalTo('id', id);
    return await this.store.delete(predicates);
  }
}

---

2. 网络通信

2.1 HTTP 请求


import http from '@ohos.net.http';

class HttpClient {
  private baseUrl: string = 'https://api.example.com';

  // GET 请求
  async get(path: string): Promise {
    const httpRequest = http.createHttp();
    
    const response = await httpRequest.request(
      `${this.baseUrl}${path}`,
      {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'application/json'
        }
      }
    );

    httpRequest.destroy();
    return JSON.parse(response.result as string);
  }

  // POST 请求
  async post(path: string, data: object): Promise {
    const httpRequest = http.createHttp();
    
    const response = await httpRequest.request(
      `${this.baseUrl}${path}`,
      {
        method: http.RequestMethod.POST,
        header: {
          'Content-Type': 'application/json'
        },
        extraData: JSON.stringify(data)
      }
    );

    httpRequest.destroy();
    return JSON.parse(response.result as string);
  }
}

// 使用示例
const client = new HttpClient();
const user = await client.get('/users/1');
const newUser = await client.post('/users', { 
  name: '张三', 
  email: 'zhangsan@example.com' 
});

2.2 WebSocket 通信

适用于实时通信场景,如聊天、实时推送等。


import webSocket from '@ohos.net.webSocket';

class WebSocketClient {
  private ws: webSocket.WebSocket | null = null;

  // 连接 WebSocket
  connect(url: string) {
    this.ws = webSocket.createWebSocket();
    
    this.ws.on('open', (err, value) => {
      console.log('WebSocket 连接打开');
      this.ws?.send('Hello Server');
    });

    this.ws.on('message', (err, value) => {
      console.log('收到消息:', value.message);
    });

    this.ws.on('close', (err, value) => {
      console.log('WebSocket 连接关闭');
    });

    this.ws.on('error', (err) => {
      console.error('WebSocket 错误:', err);
    });

    this.ws.connect(url);
  }

  // 发送消息
  send(message: string) {
    this.ws?.send(message);
  }

  // 关闭连接
  close() {
    this.ws?.close();
  }
}

---

3. 应用上下文

3.1 获取 Context


import common from '@ohos.app.ability.common';

@Entry
@Component
struct MyPage {
  private context = getContext(this) as common.UIAbilityContext;

  // 使用 context 获取应用目录
  getAppFilesDir() {
    const filesDir = this.context.filesDir;
    console.log('应用文件目录:', filesDir);
  }

  // 获取应用配置
  getAppInfo() {
    const bundleName = this.context.applicationInfo.name;
    const versionCode = this.context.applicationInfo.versionCode;
    console.log('应用名:', bundleName, '版本:', versionCode);
  }
}

---

📝 今日学习总结

  • Preferences 首选项存储
  • RDB 关系型数据库
  • HTTP 网络请求
  • WebSocket 实时通信
  • 🔜 下节预告

    分布式能力与高级特性

    ---

    笔记持续更新中...