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

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

阅读 440
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
子站问答
访问
宣传栏