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