【HarmonyOS 5】鴻蒙中Stage模型與FA模型詳解
##鴻蒙開發(fā)能力 ##HarmonyOS SDK應(yīng)用服務(wù)##鴻蒙金融類應(yīng)用 (金融理財#
一、前言
在HarmonyOS 5的應(yīng)用開發(fā)模型中, featureAbility
是舊版FA模型(Feature Ability)的用法 ,Stage模型已采用全新的應(yīng)用架構(gòu),推薦使用 組件化的上下文獲取方式 ,而非依賴featureAbility
。
FA大概是API7之前的開發(fā)模型。所謂的開發(fā)模型,值得是創(chuàng)建鴻蒙開發(fā)工程后,你在什么樣子的系統(tǒng)容器和接口上進行開發(fā)。
當初我在開發(fā)OpenHarmony的時候,最早用的就是FA模型,正是因為FA模型在開發(fā)過程中的諸多不方便,大概在API8時,官方推出了Stage模型,進行初步替代。
Stage模型,見名知意,是在系統(tǒng)提供的舞臺容器上,進行應(yīng)用的開發(fā)。整理更新的低耦合,高內(nèi)聚。應(yīng)用進程的管理也更加合理高效。
本文主要針對Stage模型與FA模型的區(qū)別。以及Stage模型如何獲取上下文作出講解。
二、Stage模型與FA模型的核心區(qū)別
下面的表格是官方文檔的信息梳理,建議針對FA模型有大概了解即可。重點關(guān)注Stage模型的內(nèi)容。
特性 | Stage模型(推薦) | FA模型(舊版) |
---|---|---|
應(yīng)用單元 | 以AbilityStage 為基礎(chǔ),通過UIAbility 管理UI組件 | 以FeatureAbility 和PageAbility 為主 |
上下文獲取 | 通過組件context 屬性或@ohos.app.ability.Context | 使用featureAbility.getContext() |
生命周期管理 | 基于UIAbility 的生命周期回調(diào)(onCreate /onDestroy ) | 基于FeatureAbility 的生命周期 |
在HarmonyOS 5 的Stage模型開發(fā)中, featureAbility
屬于過時的FA模型接口 ,必須通過組件或UIAbility
的context
屬性獲取上下文。這一變化體現(xiàn)了Stage模型“一切皆組件”的設(shè)計思想,確保代碼結(jié)構(gòu)更簡潔、組件化更徹底,同時避免與舊版API的耦合。
三、Stage模型中正確的上下文獲取方式
在Stage模型中, 組件的上下文(Context
)直接通過組件實例的context
屬性獲取 ,無需通過featureAbility
。
代碼示例:
// Stage模型中,組件內(nèi)直接通過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('文件內(nèi)容:', data);
} catch (error) {
console.error('文件讀取失敗:', error);
}
}
build() {
Column() {
Button('寫入文件').onClick(() = > this.writeToFile())
Button('讀取文件').onClick(() = > this.writeToFile())
}
}
}
上下文獲取原則
組件內(nèi)直接使用this.context
(繼承自Component
的上下文屬性)。UIAbility
中使用this.context
(代表當前Ability的上下文)。
避免使用任何以featureAbility
開頭的舊版API。
審核編輯 黃宇
-
鴻蒙
+關(guān)注
關(guān)注
60文章
2623瀏覽量
44077 -
Harmony
+關(guān)注
關(guān)注
0文章
108瀏覽量
3027
發(fā)布評論請先 登錄
評論