【HarmonyOS 5】鴻蒙中Stage模型與FA模型詳解
##鴻蒙開發能力 ##HarmonyOS SDK應用服務##鴻蒙金融類應用 (金融理財#
一、前言
在HarmonyOS 5的應用開發模型中, featureAbility
是舊版FA模型(Feature Ability)的用法 ,Stage模型已采用全新的應用架構,推薦使用 組件化的上下文獲取方式 ,而非依賴featureAbility
。
FA大概是API7之前的開發模型。所謂的開發模型,值得是創建鴻蒙開發工程后,你在什么樣子的系統容器和接口上進行開發。
當初我在開發OpenHarmony的時候,最早用的就是FA模型,正是因為FA模型在開發過程中的諸多不方便,大概在API8時,官方推出了Stage模型,進行初步替代。
Stage模型,見名知意,是在系統提供的舞臺容器上,進行應用的開發。整理更新的低耦合,高內聚。應用進程的管理也更加合理高效。
本文主要針對Stage模型與FA模型的區別。以及Stage模型如何獲取上下文作出講解。
二、Stage模型與FA模型的核心區別
下面的表格是官方文檔的信息梳理,建議針對FA模型有大概了解即可。重點關注Stage模型的內容。
特性 | Stage模型(推薦) | FA模型(舊版) |
---|---|---|
應用單元 | 以AbilityStage 為基礎,通過UIAbility 管理UI組件 | 以FeatureAbility 和PageAbility 為主 |
上下文獲取 | 通過組件context 屬性或@ohos.app.ability.Context | 使用featureAbility.getContext() |
生命周期管理 | 基于UIAbility 的生命周期回調(onCreate /onDestroy ) | 基于FeatureAbility 的生命周期 |
在HarmonyOS 5 的Stage模型開發中, featureAbility
屬于過時的FA模型接口 ,必須通過組件或UIAbility
的context
屬性獲取上下文。這一變化體現了Stage模型“一切皆組件”的設計思想,確保代碼結構更簡潔、組件化更徹底,同時避免與舊版API的耦合。
三、Stage模型中正確的上下文獲取方式
在Stage模型中, 組件的上下文(Context
)直接通過組件實例的context
屬性獲取 ,無需通過featureAbility
。
代碼示例:
// Stage模型中,組件內直接通過this.context獲取上下文
@Entry
@Component
struct FileStorageDemo {
// 文件寫入
async writeToFile() {
try {
// 正確方式:使用組件的context屬性
const filesDir = await this.context.getFilesDir();
const filePath = `${filesDir}/example.txt`;
const fd = await fileio.open(filePath, 0o102); // 0o102表示寫入模式(O_WRONLY | O_CREAT)
const data = 'Stage模型下的文件存儲示例';
await fileio.write(fd, data);
await fileio.close(fd);
console.log('文件寫入成功');
} catch (error) {
console.error('文件寫入失敗:', error);
}
}
// 文件讀取
async readFromFile() {
try {
const filesDir = await this.context.getFilesDir();
const filePath = `${filesDir}/example.txt`;
const fd = await fileio.open(filePath, 0o100); // 0o100表示讀取模式(O_RDONLY)
const buffer = new ArrayBuffer(1024);
const bytesRead = await fileio.read(fd, buffer);
const data = new TextDecoder('utf-8').decode(buffer.slice(0, bytesRead));
await fileio.close(fd);
console.log('文件內容:', data);
} catch (error) {
console.error('文件讀取失敗:', error);
}
}
build() {
Column() {
Button('寫入文件').onClick(() = > this.writeToFile())
Button('讀取文件').onClick(() = > this.writeToFile())
}
}
}
上下文獲取原則
組件內直接使用this.context
(繼承自Component
的上下文屬性)。UIAbility
中使用this.context
(代表當前Ability的上下文)。
避免使用任何以featureAbility
開頭的舊版API。
審核編輯 黃宇
-
鴻蒙
+關注
關注
59文章
2594瀏覽量
43965 -
Harmony
+關注
關注
0文章
108瀏覽量
2994
發布評論請先 登錄
評論