嗨~我是小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);
关键提醒⚠️
权限必加:敏感能力(如传感器)需在
config.json
声明{ "reqPermissions": [{ "name": "ohos.permission.GET_SENSOR_DATA" }] }
- 异步处理:文件/网络操作必用
async/await
,别卡主线程 - 用完即关:传感器订阅、网络连接在
onDestroy
中释放
总结:能力调用「三板斧」
- 文件操作:本地用
FileIO
,跨设备用DistributedFile
- 传感器+网络:先订阅数据,再用
Http
上传 - 设备适配:根据
DeviceInfo
动态调整逻辑
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。