当我第一次接触鸿蒙系统时,面对全新的开发环境和架构概念,内心既充满期待又有些忐忑。回顾这段成长历程,我希望通过分享自己的学习路径和实践经验,帮助更多开发者顺利走进鸿蒙的世界。
**初识鸿蒙:环境搭建与基础认知**
起步阶段最重要的是正确搭建开发环境。我选择使用DevEco Studio作为主要开发工具,这是专为鸿蒙应用开发定制的集成开发环境。
```typescript
// 第一个鸿蒙应用:Hello World
// entry/src/main/ets/entryability/EntryAbility.ts
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
console.log('EntryAbility onCreate');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
console.log('EntryAbility onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
console.error('Failed to load the content. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
});
}
}
```
对应的页面布局文件:
```typescript
// entry/src/main/ets/pages/Index.ets
@Entry
@Component
struct Index {
@State message: string = 'Hello HarmonyOS'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() =><"1K.6370.HK"> {
this.message = '欢迎来到鸿蒙世界!'
})
}
.width('100%')
}
.height('100%')
}
}
```
这个简单的Hello World程序让我理解了鸿蒙应用的基本结构:Ability作为应用组件,Page作为界面载体,通过声明式UI构建用户界面。
**布局与组件:构建用户界面**
掌握了基础后,我开始深入学习鸿蒙的UI组件系统。ArkTS语言结合声明式语法,让界面开发变得直观而高效。
```typescript
// 综合布局示例:用户信息卡片
@Component
struct UserCard {
@State isExpanded: boolean = false
build() {
Column() {
// 用户头像和基本信息
Row() {
Image($r('app.media.user_avatar'))
.width(60)
.height(60)
.borderRadius(30)
Column() {
Text('张三')
.fontSize(20)
.fontColor(Color.Black)
Text('高级开发工程师')
.fontSize(14)
.fontColor(Color.Gray)
}
.alignItems(HorizontalAlign.Start)
.margin({ left: 12 })
Blank()
Image($r(this.isExpanded ? 'app.media.arrow_up' : 'app.media.arrow_down'))
.width(24)
.height(24)
.onClick(() => {
this.isExpanded = !this.isExpanded
})
}
.width('100%')
.padding(16)
// 可展开的详细信息
if (this.isExpanded) {
Column() {
Divider()
Row() {
Text('邮箱:')
.fontSize(14)
.fontColor(Color.Gray)
Text('zhangsan@example.com')
.fontSize<"2Y.6370.HK">(14)
.fontColor(Color.Black)
}
.width('100%')
.margin({ top: 8, bottom: 8 })
Row() {
Text('部门:')
.fontSize(14)
.fontColor(Color.Gray)
Text('技术研发部')
.fontSize(14)
.fontColor(Color.Black)
}
.width('100%')
.margin({ bottom: 8 })
}
.width('100%')
.padding(16)
}
}
.width('100%')
.backgroundColor(Color.White)
.borderRadius(12)
.shadow({ radius: 8, color: '#1A000000', offsetX: 0, offsetY: 4 })
.margin({ top: 12, left: 16, right: 16 })
}
}
```
通过这个组件,我学会了状态管理、条件渲染和事件处理等核心概念。
**数据管理与持久化存储**
在实际应用中,数据管理是必不可少的部分。我学习了鸿蒙提供的多种数据持久化方案。
```typescript
// 使用Preferences进行轻量级数据存储
import preferences from '@ohos.data.preferences';
@Entry
@Component
struct SettingsPage {
@State username: string = ''
@State notificationsEnabled: boolean = true
private prefs: preferences.Preferences | null = null
async aboutToAppear() <"3P.6370.HK">{
try {
this.prefs = await preferences.getPreferences(this.context, 'mySettings');
this.username = await this.prefs.get('username', '');
this.notificationsEnabled = await this.prefs.get('notificationsEnabled', true);
} catch (err) {
console.error('Failed to load preferences: ' + JSON.stringify(err));
}
}
async saveSettings() {
if (this.prefs) {
await this.prefs.put('username', this.username);
await this.prefs.put('notificationsEnabled', this.notificationsEnabled);
await this.prefs.flush();
promptAction.showToast({ message: '设置已保存' });
}
}
build() {
Column() {
Text('应用设置')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 20, bottom: 30 })
List({ space: 12 }) {
ListItem() {
Row() {
Text('用户名')
.fontSize(18)
TextInput({ placeholder: '请输入用户名', text: this.username })
.onChange((value: string) => {
this.username = value
})
}
.padding(16)
}
ListItem() {
Row() {
Text('启用消息通知')
.fontSize(18)
Toggle({ type: ToggleType.Switch, isOn: this.notificationsEnabled })
.onChange((value: boolean) => {
this.notificationsEnabled = value
})
}
.padding(16)
}
}
.layoutWeight(1)
Button('保存设置')
.width('90%')
.height(48)
.fontSize(18)
.onClick(() =><"4G.6370.HK"> {
this.saveSettings()
})
.margin({ bottom: 20 })
}
.width('100%')
.height('100%')
.backgroundColor('#F5F5F5')
}
}
```
**网络请求与数据交互**
现代应用离不开网络通信,我学习了如何在鸿蒙应用中发起网络请求并处理响应。
```typescript
// 网络请求封装示例
import http from '@ohos.net.http';
class ApiService {
private static instance: ApiService;
private httpRequest: http.HttpRequest;
private constructor() {
this.httpRequest = http.createHttp();
}
static getInstance(): ApiService {
if (!ApiService.instance) {
ApiService.instance = new ApiService();
}
return ApiService.instance;
}
async get<T>(url: string, params?: Record<string, string>): Promise<T> {
try {
let fullUrl = url;
if (params) {
const queryParams = new URLSearchParams(params).toString();
fullUrl += '?' + queryParams;
}
const response = await this.httpRequest.request(fullUrl, {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
});
if (response.responseCode === 200) {
return JSON.parse(response.result as string) as T;
} else {
throw new Error(`HTTP ${response.responseCode}: ${response.result}`);
}
} catch (err) {
console.error('Request failed: ' + JSON.stringify(err));
throw err;
}
}
async post<T>(url: string, data: object): Promise<T> {
try {
const response = await this.httpRequest.request(url, {
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json',
},
extraData: JSON.stringify(data),
connectTimeout: 60000,
readTimeout: <"5D.6370.HK">60000,
});
if (response.responseCode === 200) {
return JSON.parse(response.result as string) as T;
} else {
throw new Error(`HTTP ${response.responseCode}: ${response.result}`);
}
} catch (err) {
console.error('Request failed: ' + JSON.stringify(err));
throw err;
}
}
}
// 在组件中使用API服务
@Component
struct NewsList {
@State newsItems: NewsItem[] = []
@State isLoading: boolean = true
async aboutToAppear() {
await this.loadNews();
}
async loadNews() {
try {
this.isLoading = true;
const api = ApiService.getInstance();
this.newsItems = await api.get<NewsItem[]>('https://api.example.com/news');
} catch (err) {
console.error('Failed to load news: ' + JSON.stringify(err));
promptAction.showToast({ message: '加载失败,请重试' });
} finally {
this.isLoading = false;
}
}
build() {
Column() {
if (this.isLoading) {
LoadingProgress()
.color(Color.Blue)
.margin({ top: 20 })
Text('加载中...')
.fontSize(16)
.margin({ top: 12 })
} else {
List({ space: 8 }) {
ForEach(this.newsItems, (item: NewsItem) => {
ListItem() {
NewsCard({ item: item })
}
}, (item: NewsItem) => item.id.toString())
}
.layoutWeight(1)
}
}
.width('100%')<"6M.6370.HK">
.height('100%')
}
}
```
**分布式能力探索**
鸿蒙的分布式特性是其核心优势之一,我花时间学习了如何实现跨设备协同。
```typescript
// 分布式数据管理示例
import distributedObject from '@ohos.data.distributedDataObject';
class DistributedSession {
private session: distributedObject.DataObject;
constructor(sessionId: string) {
this.session = distributedObject.createDataObject(sessionId);
// 监听数据变化
this.session.on('change', (fields: string[]) => {
console.info('分布式数据发生变化: ' + JSON.stringify(fields));
// 通知界面更新
this.notifyDataChange();
});
}
// 设置共享数据
setValue(key: string, value: any): void {
this.session[key] = value;
this.session.save().then(() => {
console.info('数据保存成功');
}).catch((err) => {
console.error('数据保存失败: ' + JSON.stringify(err));
});
}
// 获取共享数据
getValue(key: string): any {
return this.session[key];
}
// 设备状态同步
syncDeviceStatus(deviceId: string, status: DeviceStatus): void {
this.setValue(`device_${deviceId}`, status);
}
}
// 在组件中使用分布式能力
@Entry
@Component
struct CollaborativeWhiteboard {
private distSession: DistributedSession = new DistributedSession('whiteboard_session');
@State strokes: Stroke[] = []
@State connectedDevices: string[] = []
aboutToAppear() {
this.distSession.setValue('whiteboard_data', this.strokes);
}
build() {
Column() <"UF.5283.HK">{
// 设备连接状态显示
Row() {
Text('协作设备:')
.fontSize(16)
ForEach(this.connectedDevices, (device: string) => {
Text(device)
.fontSize(14)
.backgroundColor(Color.Green)
.padding(4)
.margin({ left: 8 })
})
}
.padding(12)
// 画板区域
Canvas(this.context)
.width('100%')
.height('80%')
.backgroundColor(Color.White)
.onTouch((event: TouchEvent) => {
this.handleTouch(event);
})
// 工具栏
Toolbar({
onColorChange: (color: string) => this.setStrokeColor(color),
onClear: () => this.clearWhiteboard()
})
}
}
private handleTouch(event: TouchEvent): void {
// 处理触摸事件并同步到其他设备
const newStroke = this.createStrokeFromTouch(event);
this.strokes.push(newStroke);
this.distSession.setValue('whiteboard_data', this.strokes);
}
}
```
**项目实战:天气预报应用**
将所学知识整合起来,我开发了一个功能完整的天气预报应用。
```typescript
// 主页面组件
@Entry
@Component
struct WeatherApp {
@State currentWeather: WeatherData | null = null
@State forecast: ForecastItem[] = []
@State currentCity: string = '北京市'
async aboutToAppear() {
await this.loadWeatherData();
}
async loadWeatherData() {
try {
const api = ApiService.getInstance();
// 获取当前天气
this.currentWeather = await api.get<WeatherData>(
`https://api.weather.com/current?city=${this.currentCity}`
);
// 获取天气预报
this.forecast = await api.get<ForecastItem[]>(
`https://api.weather.com/forecast?city=${this.currentCity}`
);
} catch (err) {
console.error('Failed to load weather data: ' + JSON.stringify(err));
}
}
build() {
Column() {
// 标题栏
Row() {
Text('天气预报')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.fontColor(Color.White)
Blank()
Button('切换城市')
.fontSize(14)
.backgroundColor(Color.Transparent)
.fontColor(Color.White)
.onClick(() => {
this.showCitySelector();
})
}
.width('100%')
.padding(20)
.backgroundColor(Color.Blue)
Scroll() {
Column() {
// 当前天气信息
if (this.currentWeather) {
CurrentWeather({ weather: this.currentWeather })
}
// 天气预报列表
Text('未来预报')
.fontSize(20)
.fontWeight(FontWeight.Medium)
.margin({ top: 24, bottom: 16, left: 16 })
ForEach(this.forecast, (item: ForecastItem) => {
ForecastRow({ item: item })
})
}
}
.layoutWeight(1)
}
.width('100%')
.height('100%')
}
}
```
通过这个完整的学习路径,我从一个对鸿蒙开发一无所知的"小白",逐步成长为能够独立开发应用的开发者。这个过程虽然充满挑战,但每解决一个问题、每完成一个功能,都带来了巨大的成就感。鸿蒙生态正在快速发展,我相信现在正是学习和参与的最佳时机。