嗨~我是小L!鸿蒙系统藏着超多「超能力」,学会调用能让应用秒变全能。今天用3个关键场景,教你快速上手核心能力~

一、文件操作:数据存储的「瑞士军刀」🔧

1. 本地文件读写(异步最佳实践)

// 读取配置文件  
async function readConfig() {  
  const file = await FileIO.open('/data/config.json', 'r');  
  const content = await file.read();  
  file.close(); // 重要!释放资源  
  return JSON.parse(new TextDecoder().decode(content));  
}  

// 写入日志文件(追加模式)  
async function logData(data: string) {  
  const file = await FileIO.open('/data/logs.txt', 'a+');  
  await file.write(new TextEncoder().encode(data + '\n'));  
  file.close();  
}  

2. 分布式文件同步(手机→平板)

import { DistributedFile } from '@ohos.distributedFile';  

// 跨设备传文件  
async function shareToTablet(filePath: string, deviceId: string) {  
  const df = await DistributedFile.create();  
  await df.open(filePath, 'r');  
  await df.transferTo(deviceId, '/shared/file.pdf');  
  df.close();  
}  

二、传感器+网络:打造「感知型」应用🌐

1. 采集加速度数据(计步器)

import { Sensor, SensorTypeId } from '@ohos.sensor';  

const accelerometer = Sensor.getDefaultSensor(SensorTypeId.ACCELEROMETER);  
let stepCount = 0;  

// 订阅传感器(在onCreate中)  
accelerometer.subscribe((data) => {  
  if (Math.abs(data.x) > 0.8) stepCount++; // 简单计步逻辑  
});  

// 取消订阅(在onDestroy中)  
accelerometer.unsubscribe();  

2. 数据上传云端(实时同步)

import { Http } from '@ohos.net.http';  

async function uploadStepData(count: number) {  
  const request = Http.createHttp();  
  await request.request({  
    url: 'https://api.example.com/step',  
    method: 'POST',  
    body: JSON.stringify({ count }),  
    headers: { 'Content-Type': 'application/json' }  
  });  
  request.destroy(); // 释放连接  
}  

三、设备管理:性能优化「幕后军师」📊

1. 获取设备信息(动态适配)

import { DeviceInfo } from '@ohos.deviceInfo';  

const device = DeviceInfo.getInfo();  
if (device.type === 'phone') {  
  loadSimpleUI(); // 手机用轻量级界面  
} else {  
  loadFullUI(); // 平板/车机用全功能界面  
}  

2. 内存监控(防卡顿)

import { MemoryManager } from '@ohos.memory';  

// 每5秒检查内存  
setInterval(() => {  
  const { usedRate } = MemoryManager.getMemoryInfo();  
  if (usedRate > 80%) clearCache(); // 超过80%清理缓存  
}, 5000);  

关键提醒⚠️

  1. 权限必加:敏感能力(如传感器)需在config.json声明

    { "reqPermissions": [{ "name": "ohos.permission.GET_SENSOR_DATA" }] }  
  2. 异步处理:文件/网络操作必用async/await,别卡主线程
  3. 用完即关:传感器订阅、网络连接在onDestroy中释放

总结:能力调用「三板斧」

  1. 文件操作:本地用FileIO,跨设备用DistributedFile
  2. 传感器+网络:先订阅数据,再用Http上传
  3. 设备适配:根据DeviceInfo动态调整逻辑

lyc233333
1 声望0 粉丝