鸿蒙仓颉:如何获取全局定义的Context以及使用方法
在使用仓颉语言开发App的时候,使用全局的context,如果采用文档中的方案,定义在index.cj中的话,使用起来很局限化,如果在子主包和子包中都使用全局的context,如果主包的UI需要使用子包中的逻辑,主包和子包就会产生相互依赖的问题(combind), 编译就会报错。
如何解决这个问题呢?
**思路:**剥离全局的context,存储context到全局的单例中,那不管子包还是主包,引用全局的context的都不会产生相互依赖的问题,就可以正常使用全局的context了。
存储全局的context
package ohos_app_cangjie_entry.utils
import ohos.ark_interop_helper.StageContextvar globalAppStageContext: Option<StageContext> = Option<StageContext>.Nonepublic class WinAppUtil {public init(context:StageContext) {AppLogUtil.info('WinAppUtil init');globalAppStageContext = context;}public static func getGlobalAppContext(){return globalAppStageContext;}
}
入口类main_ability.cj中初始化存储全局的context
public override func onWindowStageCreate(windowStage: WindowStage): Unit {AppLog.info("MainAbility onWindowStageCreate.")let appStageContext = getStageContext(globalAbilityContext.getOrThrow());DatabaseHelper(appStageContext);WinAppUtil(appStageContext);windowStage.loadContent("EntryView")
}
如何实际应用呢?
在使用系统的Preferences的时候,如果没有全局管理的文件,就会很麻烦,我们就可以整理成一个文件,在子包中整理。
Preferences实例与持久化文件一一对应,文件路径通过应用上下文(context)获取(路径格式:/data/app/el1/100/base/[包名])。数据加载到内存中的Preferences实例,直到主动移除或删除文件。
package ohos_app_cangjie_entry.utilsimport ohos.preferences.ValueType as PValueType
import ohos.preferences.Preferences
import ohos_app_cangjie_entry.constants.CommonTagConstantspublic class WinPreferencesManager {/*** 存储数据至沙盒中*/public static func putPreferencesInfo(key: String, value: PValueType) {let appContext = WinAppUtil.getGlobalAppContext().getOrThrow();var my_preference = Preferences.getPreferences(appContext, CommonTagConstants.PRE_TAG);my_preference.put(key, value)my_preference.flush();}/*** 获取沙盒存储数据的值*/public static func getPreferencesInfo(key: String) {let appContext = WinAppUtil.getGlobalAppContext().getOrThrow();var my_preference = Preferences.getPreferences(appContext, CommonTagConstants.PRE_TAG);if (my_preference.has(key)) {let value = my_preference.get(key, PValueType.string(''))match (value) {case PValueType.string(n) => return ncase _ => return ''}}return ''}
}
目录结构如下:
如果你的目录结构中,还有其他子包,怎么使用WinPreferencesManager都不会用相互引用的问题。