HarmonyOS 封装一个公用的getContext\(\)?

封装一个公用的export const context = getContext()

阅读 441
1 个回答

请参考如下代码

import { Context } from '@kit.AbilityKit';
export class GlobalContext {
  private constructor() {}
  private static instance: GlobalContext;
  private context:Context | undefined

  public static getInstance(): GlobalContext {
    if (!GlobalContext.instance) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }

  setContext(contex:Context){
    this.context = contex
  }

  getContext(): Context | undefined {
    return this.context
  }
}

在EntryAbility初始化设置context

async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  GlobalContext.getInstance().setContext(getContext(this));
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏